This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

314 lines
12 KiB

  1. from __future__ import absolute_import
  2. import os
  3. import time
  4. from collections import defaultdict
  5. from io import open
  6. from .utils import STRING_TYPE, Serialize, SerializeMemoizer
  7. from .load_grammar import load_grammar
  8. from .tree import Tree
  9. from .common import LexerConf, ParserConf
  10. from .lexer import Lexer, TraditionalLexer
  11. from .parse_tree_builder import ParseTreeBuilder
  12. from .parser_frontends import get_frontend
  13. from .grammar import Rule
  14. ###{standalone
  15. class LarkOptions(Serialize):
  16. """Specifies the options for Lark
  17. """
  18. OPTIONS_DOC = """
  19. parser - Decides which parser engine to use, "earley" or "lalr". (Default: "earley")
  20. Note: "lalr" requires a lexer
  21. lexer - Decides whether or not to use a lexer stage
  22. "standard": Use a standard lexer
  23. "contextual": Stronger lexer (only works with parser="lalr")
  24. "dynamic": Flexible and powerful (only with parser="earley")
  25. "dynamic_complete": Same as dynamic, but tries *every* variation
  26. of tokenizing possible. (only with parser="earley")
  27. "auto" (default): Choose for me based on grammar and parser
  28. ambiguity - Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
  29. "resolve": The parser will automatically choose the simplest derivation
  30. (it chooses consistently: greedy for tokens, non-greedy for rules)
  31. "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
  32. transformer - Applies the transformer to every parse tree
  33. debug - Affects verbosity (default: False)
  34. keep_all_tokens - Don't automagically remove "punctuation" tokens (default: False)
  35. cache_grammar - Cache the Lark grammar (Default: False)
  36. postlex - Lexer post-processing (Default: None) Only works with the standard and contextual lexers.
  37. start - The start symbol, either a string, or a list of strings for multiple possible starts (Default: "start")
  38. profile - Measure run-time usage in Lark. Read results from the profiler proprety (Default: False)
  39. priority - How priorities should be evaluated - auto, none, normal, invert (Default: auto)
  40. propagate_positions - Propagates [line, column, end_line, end_column] attributes into all tree branches.
  41. lexer_callbacks - Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
  42. maybe_placeholders - Experimental feature. Instead of omitting optional rules (i.e. rule?), replace them with None
  43. """
  44. if __doc__:
  45. __doc__ += OPTIONS_DOC
  46. _defaults = {
  47. 'debug': False,
  48. 'keep_all_tokens': False,
  49. 'tree_class': None,
  50. 'cache_grammar': False,
  51. 'postlex': None,
  52. 'parser': 'earley',
  53. 'lexer': 'auto',
  54. 'transformer': None,
  55. 'start': 'start',
  56. 'profile': False,
  57. 'priority': 'auto',
  58. 'ambiguity': 'auto',
  59. 'propagate_positions': False,
  60. 'lexer_callbacks': {},
  61. 'maybe_placeholders': False,
  62. 'edit_terminals': None,
  63. }
  64. def __init__(self, options_dict):
  65. o = dict(options_dict)
  66. options = {}
  67. for name, default in self._defaults.items():
  68. if name in o:
  69. value = o.pop(name)
  70. if isinstance(default, bool):
  71. value = bool(value)
  72. else:
  73. value = default
  74. options[name] = value
  75. if isinstance(options['start'], str):
  76. options['start'] = [options['start']]
  77. self.__dict__['options'] = options
  78. assert self.parser in ('earley', 'lalr', 'cyk', None)
  79. if self.parser == 'earley' and self.transformer:
  80. raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.'
  81. 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
  82. if o:
  83. raise ValueError("Unknown options: %s" % o.keys())
  84. def __getattr__(self, name):
  85. return self.options[name]
  86. def __setattr__(self, name, value):
  87. assert name in self.options
  88. self.options[name] = value
  89. def serialize(self, memo):
  90. return self.options
  91. @classmethod
  92. def deserialize(cls, data, memo):
  93. return cls(data)
  94. class Profiler:
  95. def __init__(self):
  96. self.total_time = defaultdict(float)
  97. self.cur_section = '__init__'
  98. self.last_enter_time = time.time()
  99. def enter_section(self, name):
  100. cur_time = time.time()
  101. self.total_time[self.cur_section] += cur_time - self.last_enter_time
  102. self.last_enter_time = cur_time
  103. self.cur_section = name
  104. def make_wrapper(self, name, f):
  105. def wrapper(*args, **kwargs):
  106. last_section = self.cur_section
  107. self.enter_section(name)
  108. try:
  109. return f(*args, **kwargs)
  110. finally:
  111. self.enter_section(last_section)
  112. return wrapper
  113. class Lark(Serialize):
  114. def __init__(self, grammar, **options):
  115. """
  116. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  117. options : a dictionary controlling various aspects of Lark.
  118. """
  119. self.options = LarkOptions(options)
  120. # Some, but not all file-like objects have a 'name' attribute
  121. try:
  122. self.source = grammar.name
  123. except AttributeError:
  124. self.source = '<string>'
  125. # Drain file-like objects to get their contents
  126. try:
  127. read = grammar.read
  128. except AttributeError:
  129. pass
  130. else:
  131. grammar = read()
  132. assert isinstance(grammar, STRING_TYPE)
  133. if self.options.cache_grammar:
  134. raise NotImplementedError("Not available yet")
  135. assert not self.options.profile, "Feature temporarily disabled"
  136. # self.profiler = Profiler() if self.options.profile else None
  137. if self.options.lexer == 'auto':
  138. if self.options.parser == 'lalr':
  139. self.options.lexer = 'contextual'
  140. elif self.options.parser == 'earley':
  141. self.options.lexer = 'dynamic'
  142. elif self.options.parser == 'cyk':
  143. self.options.lexer = 'standard'
  144. else:
  145. assert False, self.options.parser
  146. lexer = self.options.lexer
  147. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  148. if self.options.ambiguity == 'auto':
  149. if self.options.parser == 'earley':
  150. self.options.ambiguity = 'resolve'
  151. else:
  152. disambig_parsers = ['earley', 'cyk']
  153. assert self.options.parser in disambig_parsers, (
  154. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  155. if self.options.priority == 'auto':
  156. if self.options.parser in ('earley', 'cyk', ):
  157. self.options.priority = 'normal'
  158. elif self.options.parser in ('lalr', ):
  159. self.options.priority = None
  160. elif self.options.priority in ('invert', 'normal'):
  161. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  162. assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  163. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  164. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', )
  165. # Parse the grammar file and compose the grammars (TODO)
  166. self.grammar = load_grammar(grammar, self.source)
  167. # Compile the EBNF grammar into BNF
  168. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start)
  169. if self.options.edit_terminals:
  170. for t in self.terminals:
  171. self.options.edit_terminals(t)
  172. self._terminals_dict = {t.name:t for t in self.terminals}
  173. # If the user asked to invert the priorities, negate them all here.
  174. # This replaces the old 'resolve__antiscore_sum' option.
  175. if self.options.priority == 'invert':
  176. for rule in self.rules:
  177. if rule.options and rule.options.priority is not None:
  178. rule.options.priority = -rule.options.priority
  179. # Else, if the user asked to disable priorities, strip them from the
  180. # rules. This allows the Earley parsers to skip an extra forest walk
  181. # for improved performance, if you don't need them (or didn't specify any).
  182. elif self.options.priority == None:
  183. for rule in self.rules:
  184. if rule.options and rule.options.priority is not None:
  185. rule.options.priority = None
  186. self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, self.options.lexer_callbacks)
  187. if self.options.parser:
  188. self.parser = self._build_parser()
  189. elif lexer:
  190. self.lexer = self._build_lexer()
  191. if __init__.__doc__:
  192. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  193. __serialize_fields__ = 'parser', 'rules', 'options'
  194. def _build_lexer(self):
  195. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks)
  196. def _prepare_callbacks(self):
  197. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  198. self._parse_tree_builder = ParseTreeBuilder(self.rules, self.options.tree_class or Tree, self.options.propagate_positions, self.options.keep_all_tokens, self.options.parser!='lalr' and self.options.ambiguity=='explicit', self.options.maybe_placeholders)
  199. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  200. def _build_parser(self):
  201. self._prepare_callbacks()
  202. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  203. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  204. @classmethod
  205. def deserialize(cls, data, namespace, memo, transformer=None, postlex=None):
  206. if memo:
  207. memo = SerializeMemoizer.deserialize(memo, namespace, {})
  208. inst = cls.__new__(cls)
  209. options = dict(data['options'])
  210. options['transformer'] = transformer
  211. options['postlex'] = postlex
  212. inst.options = LarkOptions.deserialize(options, memo)
  213. inst.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  214. inst.source = '<deserialized>'
  215. inst._prepare_callbacks()
  216. inst.parser = inst.parser_class.deserialize(data['parser'], memo, inst._callbacks, inst.options.postlex)
  217. return inst
  218. @classmethod
  219. def open(cls, grammar_filename, rel_to=None, **options):
  220. """Create an instance of Lark with the grammar given by its filename
  221. If rel_to is provided, the function will find the grammar filename in relation to it.
  222. Example:
  223. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  224. Lark(...)
  225. """
  226. if rel_to:
  227. basepath = os.path.dirname(rel_to)
  228. grammar_filename = os.path.join(basepath, grammar_filename)
  229. with open(grammar_filename, encoding='utf8') as f:
  230. return cls(f, **options)
  231. def __repr__(self):
  232. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  233. def lex(self, text):
  234. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  235. if not hasattr(self, 'lexer'):
  236. self.lexer = self._build_lexer()
  237. stream = self.lexer.lex(text)
  238. if self.options.postlex:
  239. return self.options.postlex.process(stream)
  240. return stream
  241. def get_terminal(self, name):
  242. "Get information about a terminal"
  243. return self._terminals_dict[name]
  244. def parse(self, text, start=None):
  245. """Parse the given text, according to the options provided.
  246. The 'start' parameter is required if Lark was given multiple possible start symbols (using the start option).
  247. Returns a tree, unless specified otherwise.
  248. """
  249. return self.parser.parse(text, start=start)
  250. ###}