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.

496 lines
19 KiB

  1. from __future__ import absolute_import
  2. from lark.exceptions import UnexpectedCharacters, UnexpectedInput, UnexpectedToken
  3. import sys, os, pickle, hashlib
  4. from io import open
  5. import tempfile
  6. from .utils import STRING_TYPE, Serialize, SerializeMemoizer, FS, isascii, logger
  7. from .load_grammar import load_grammar
  8. from .tree import Tree
  9. from .common import LexerConf, ParserConf
  10. from .lexer import Lexer, TraditionalLexer, TerminalDef
  11. from .parse_tree_builder import ParseTreeBuilder
  12. from .parser_frontends import get_frontend, _get_lexer_callbacks
  13. from .grammar import Rule
  14. import re
  15. try:
  16. import regex
  17. except ImportError:
  18. regex = None
  19. ###{standalone
  20. class LarkOptions(Serialize):
  21. """Specifies the options for Lark
  22. """
  23. OPTIONS_DOC = """
  24. **=== General Options ===**
  25. start
  26. The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start")
  27. debug
  28. Display debug information, such as warnings (default: False)
  29. transformer
  30. Applies the transformer to every parse tree (equivlent to applying it after the parse, but faster)
  31. propagate_positions
  32. Propagates (line, column, end_line, end_column) attributes into all tree branches.
  33. maybe_placeholders
  34. When True, the ``[]`` operator returns ``None`` when not matched.
  35. When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all.
  36. (default= ``False``. Recommended to set to ``True``)
  37. cache
  38. Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now.
  39. - When ``False``, does nothing (default)
  40. - When ``True``, caches to a temporary file in the local directory
  41. - When given a string, caches to the path pointed by the string
  42. regex
  43. When True, uses the ``regex`` module instead of the stdlib ``re``.
  44. g_regex_flags
  45. Flags that are applied to all terminals (both regex and strings)
  46. keep_all_tokens
  47. Prevent the tree builder from automagically removing "punctuation" tokens (default: False)
  48. tree_class
  49. Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``.
  50. **=== Algorithm Options ===**
  51. parser
  52. Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley").
  53. (there is also a "cyk" option for legacy)
  54. lexer
  55. Decides whether or not to use a lexer stage
  56. - "auto" (default): Choose for me based on the parser
  57. - "standard": Use a standard lexer
  58. - "contextual": Stronger lexer (only works with parser="lalr")
  59. - "dynamic": Flexible and powerful (only with parser="earley")
  60. - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible.
  61. ambiguity
  62. Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
  63. - "resolve": The parser will automatically choose the simplest derivation
  64. (it chooses consistently: greedy for tokens, non-greedy for rules)
  65. - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
  66. - "forest": The parser will return the root of the shared packed parse forest.
  67. **=== Misc. / Domain Specific Options ===**
  68. postlex
  69. Lexer post-processing (Default: None) Only works with the standard and contextual lexers.
  70. priority
  71. How priorities should be evaluated - auto, none, normal, invert (Default: auto)
  72. lexer_callbacks
  73. Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
  74. use_bytes
  75. Accept an input of type ``bytes`` instead of ``str`` (Python 3 only).
  76. edit_terminals
  77. A callback for editing the terminals before parse.
  78. **=== End Options ===**
  79. """
  80. if __doc__:
  81. __doc__ += OPTIONS_DOC
  82. # Adding a new option needs to be done in multiple places:
  83. # - In the dictionary below. This is the primary truth of which options `Lark.__init__` accepts
  84. # - In the docstring above. It is used both for the docstring of `LarkOptions` and `Lark`, and in readthedocs
  85. # - In `lark-stubs/lark.pyi`:
  86. # - As attribute to `LarkOptions`
  87. # - As parameter to `Lark.__init__`
  88. # - Potentially in `_LOAD_ALLOWED_OPTIONS` below this class, when the option doesn't change how the grammar is loaded
  89. # - Potentially in `lark.tools.__init__`, if it makes sense, and it can easily be passed as a cmd argument
  90. _defaults = {
  91. 'debug': False,
  92. 'keep_all_tokens': False,
  93. 'tree_class': None,
  94. 'cache': False,
  95. 'postlex': None,
  96. 'parser': 'earley',
  97. 'lexer': 'auto',
  98. 'transformer': None,
  99. 'start': 'start',
  100. 'priority': 'auto',
  101. 'ambiguity': 'auto',
  102. 'regex': False,
  103. 'propagate_positions': False,
  104. 'lexer_callbacks': {},
  105. 'maybe_placeholders': False,
  106. 'edit_terminals': None,
  107. 'g_regex_flags': 0,
  108. 'use_bytes': False,
  109. }
  110. def __init__(self, options_dict):
  111. o = dict(options_dict)
  112. options = {}
  113. for name, default in self._defaults.items():
  114. if name in o:
  115. value = o.pop(name)
  116. if isinstance(default, bool) and name not in ('cache', 'use_bytes'):
  117. value = bool(value)
  118. else:
  119. value = default
  120. options[name] = value
  121. if isinstance(options['start'], STRING_TYPE):
  122. options['start'] = [options['start']]
  123. self.__dict__['options'] = options
  124. assert self.parser in ('earley', 'lalr', 'cyk', None)
  125. if self.parser == 'earley' and self.transformer:
  126. raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.'
  127. 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
  128. if o:
  129. raise ValueError("Unknown options: %s" % o.keys())
  130. def __getattr__(self, name):
  131. try:
  132. return self.options[name]
  133. except KeyError as e:
  134. raise AttributeError(e)
  135. def __setattr__(self, name, value):
  136. assert name in self.options
  137. self.options[name] = value
  138. def serialize(self, memo):
  139. return self.options
  140. @classmethod
  141. def deserialize(cls, data, memo):
  142. return cls(data)
  143. # Options that can be passed to the Lark parser, even when it was loaded from cache/standalone.
  144. # These option are only used outside of `load_grammar`.
  145. _LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'use_bytes', 'debug', 'g_regex_flags', 'regex', 'propagate_positions', 'tree_class'}
  146. _VALID_PRIORITY_OPTIONS = ('auto', 'normal', 'invert', None)
  147. _VALID_AMBIGUITY_OPTIONS = ('auto', 'resolve', 'explicit', 'forest')
  148. class Lark(Serialize):
  149. """Main interface for the library.
  150. It's mostly a thin wrapper for the many different parsers, and for the tree constructor.
  151. Parameters:
  152. grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  153. options: a dictionary controlling various aspects of Lark.
  154. Example:
  155. >>> Lark(r'''start: "foo" ''')
  156. Lark(...)
  157. """
  158. def __init__(self, grammar, **options):
  159. self.options = LarkOptions(options)
  160. # Set regex or re module
  161. use_regex = self.options.regex
  162. if use_regex:
  163. if regex:
  164. re_module = regex
  165. else:
  166. raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
  167. else:
  168. re_module = re
  169. # Some, but not all file-like objects have a 'name' attribute
  170. try:
  171. self.source = grammar.name
  172. except AttributeError:
  173. self.source = '<string>'
  174. # Drain file-like objects to get their contents
  175. try:
  176. read = grammar.read
  177. except AttributeError:
  178. pass
  179. else:
  180. grammar = read()
  181. assert isinstance(grammar, STRING_TYPE)
  182. self.grammar_source = grammar
  183. if self.options.use_bytes:
  184. if not isascii(grammar):
  185. raise ValueError("Grammar must be ascii only, when use_bytes=True")
  186. if sys.version_info[0] == 2 and self.options.use_bytes != 'force':
  187. raise NotImplementedError("`use_bytes=True` may have issues on python2."
  188. "Use `use_bytes='force'` to use it at your own risk.")
  189. cache_fn = None
  190. if self.options.cache:
  191. if self.options.parser != 'lalr':
  192. raise NotImplementedError("cache only works with parser='lalr' for now")
  193. if isinstance(self.options.cache, STRING_TYPE):
  194. cache_fn = self.options.cache
  195. else:
  196. if self.options.cache is not True:
  197. raise ValueError("cache argument must be bool or str")
  198. unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals')
  199. from . import __version__
  200. options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
  201. s = grammar + options_str + __version__
  202. md5 = hashlib.md5(s.encode()).hexdigest()
  203. cache_fn = tempfile.gettempdir() + '/.lark_cache_%s.tmp' % md5
  204. if FS.exists(cache_fn):
  205. logger.debug('Loading grammar from cache: %s', cache_fn)
  206. # Remove options that aren't relevant for loading from cache
  207. for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
  208. del options[name]
  209. with FS.open(cache_fn, 'rb') as f:
  210. self._load(f, **options)
  211. return
  212. if self.options.lexer == 'auto':
  213. if self.options.parser == 'lalr':
  214. self.options.lexer = 'contextual'
  215. elif self.options.parser == 'earley':
  216. self.options.lexer = 'dynamic'
  217. elif self.options.parser == 'cyk':
  218. self.options.lexer = 'standard'
  219. else:
  220. assert False, self.options.parser
  221. lexer = self.options.lexer
  222. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  223. if self.options.ambiguity == 'auto':
  224. if self.options.parser == 'earley':
  225. self.options.ambiguity = 'resolve'
  226. else:
  227. disambig_parsers = ['earley', 'cyk']
  228. assert self.options.parser in disambig_parsers, (
  229. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  230. if self.options.priority == 'auto':
  231. self.options.priority = 'normal'
  232. if self.options.priority not in _VALID_PRIORITY_OPTIONS:
  233. raise ValueError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
  234. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  235. if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
  236. raise ValueError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
  237. # Parse the grammar file and compose the grammars (TODO)
  238. self.grammar = load_grammar(grammar, self.source, re_module, self.options.keep_all_tokens)
  239. if self.options.postlex is not None:
  240. terminals_to_keep = set(self.options.postlex.always_accept)
  241. else:
  242. terminals_to_keep = set()
  243. # Compile the EBNF grammar into BNF
  244. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
  245. if self.options.edit_terminals:
  246. for t in self.terminals:
  247. self.options.edit_terminals(t)
  248. self._terminals_dict = {t.name: t for t in self.terminals}
  249. # If the user asked to invert the priorities, negate them all here.
  250. # This replaces the old 'resolve__antiscore_sum' option.
  251. if self.options.priority == 'invert':
  252. for rule in self.rules:
  253. if rule.options.priority is not None:
  254. rule.options.priority = -rule.options.priority
  255. # Else, if the user asked to disable priorities, strip them from the
  256. # rules. This allows the Earley parsers to skip an extra forest walk
  257. # for improved performance, if you don't need them (or didn't specify any).
  258. elif self.options.priority == None:
  259. for rule in self.rules:
  260. if rule.options.priority is not None:
  261. rule.options.priority = None
  262. # TODO Deprecate lexer_callbacks?
  263. lexer_callbacks = (_get_lexer_callbacks(self.options.transformer, self.terminals)
  264. if self.options.transformer
  265. else {})
  266. lexer_callbacks.update(self.options.lexer_callbacks)
  267. self.lexer_conf = LexerConf(self.terminals, re_module, self.ignore_tokens, self.options.postlex, lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes)
  268. if self.options.parser:
  269. self.parser = self._build_parser()
  270. elif lexer:
  271. self.lexer = self._build_lexer()
  272. if cache_fn:
  273. logger.debug('Saving grammar to cache: %s', cache_fn)
  274. with FS.open(cache_fn, 'wb') as f:
  275. self.save(f)
  276. if __doc__:
  277. __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
  278. __serialize_fields__ = 'parser', 'rules', 'options'
  279. def _build_lexer(self):
  280. return TraditionalLexer(self.lexer_conf)
  281. def _prepare_callbacks(self):
  282. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  283. self._callbacks = None
  284. # we don't need these callbacks if we aren't building a tree
  285. if self.options.ambiguity != 'forest':
  286. self._parse_tree_builder = ParseTreeBuilder(
  287. self.rules,
  288. self.options.tree_class or Tree,
  289. self.options.propagate_positions,
  290. self.options.parser!='lalr' and self.options.ambiguity=='explicit',
  291. self.options.maybe_placeholders
  292. )
  293. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  294. def _build_parser(self):
  295. self._prepare_callbacks()
  296. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  297. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  298. def save(self, f):
  299. """Saves the instance into the given file object
  300. Useful for caching and multiprocessing.
  301. """
  302. data, m = self.memo_serialize([TerminalDef, Rule])
  303. pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
  304. @classmethod
  305. def load(cls, f):
  306. """Loads an instance from the given file object
  307. Useful for caching and multiprocessing.
  308. """
  309. inst = cls.__new__(cls)
  310. return inst._load(f)
  311. def _load(self, f, **kwargs):
  312. if isinstance(f, dict):
  313. d = f
  314. else:
  315. d = pickle.load(f)
  316. memo = d['memo']
  317. data = d['data']
  318. assert memo
  319. memo = SerializeMemoizer.deserialize(memo, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
  320. options = dict(data['options'])
  321. if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
  322. raise ValueError("Some options are not allowed when loading a Parser: {}"
  323. .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
  324. options.update(kwargs)
  325. self.options = LarkOptions.deserialize(options, memo)
  326. self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  327. self.source = '<deserialized>'
  328. self._prepare_callbacks()
  329. self.parser = self.parser_class.deserialize(
  330. data['parser'],
  331. memo,
  332. self._callbacks,
  333. self.options, # Not all, but multiple attributes are used
  334. )
  335. self.terminals = self.parser.lexer_conf.tokens
  336. self._terminals_dict = {t.name: t for t in self.terminals}
  337. return self
  338. @classmethod
  339. def _load_from_dict(cls, data, memo, **kwargs):
  340. inst = cls.__new__(cls)
  341. return inst._load({'data': data, 'memo': memo}, **kwargs)
  342. @classmethod
  343. def open(cls, grammar_filename, rel_to=None, **options):
  344. """Create an instance of Lark with the grammar given by its filename
  345. If ``rel_to`` is provided, the function will find the grammar filename in relation to it.
  346. Example:
  347. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  348. Lark(...)
  349. """
  350. if rel_to:
  351. basepath = os.path.dirname(rel_to)
  352. grammar_filename = os.path.join(basepath, grammar_filename)
  353. with open(grammar_filename, encoding='utf8') as f:
  354. return cls(f, **options)
  355. def __repr__(self):
  356. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  357. def lex(self, text):
  358. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  359. if not hasattr(self, 'lexer'):
  360. self.lexer = self._build_lexer()
  361. stream = self.lexer.lex(text)
  362. if self.options.postlex:
  363. return self.options.postlex.process(stream)
  364. return stream
  365. def get_terminal(self, name):
  366. "Get information about a terminal"
  367. return self._terminals_dict[name]
  368. def parse(self, text, start=None, on_error=None):
  369. """Parse the given text, according to the options provided.
  370. Parameters:
  371. text (str): Text to be parsed.
  372. start (str, optional): Required if Lark was given multiple possible start symbols (using the start option).
  373. on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing.
  374. LALR only. See examples/error_puppet.py for an example of how to use on_error.
  375. Returns:
  376. If a transformer is supplied to ``__init__``, returns whatever is the
  377. result of the transformation. Otherwise, returns a Tree instance.
  378. """
  379. try:
  380. return self.parser.parse(text, start=start)
  381. except UnexpectedInput as e:
  382. if on_error is None:
  383. raise
  384. while True:
  385. if isinstance(e, UnexpectedCharacters):
  386. s = e.puppet.lexer_state.state
  387. p = s.line_ctr.char_pos
  388. if not on_error(e):
  389. raise e
  390. if isinstance(e, UnexpectedCharacters):
  391. # If user didn't change the character position, then we should
  392. if p == s.line_ctr.char_pos:
  393. s.line_ctr.feed(s.text[p:p+1])
  394. try:
  395. return e.puppet.resume_parse()
  396. except UnexpectedToken as e2:
  397. if isinstance(e, UnexpectedToken) and e.token.type == e2.token.type == '$END' and e.puppet == e2.puppet:
  398. # Prevent infinite loop
  399. raise e2
  400. e = e2
  401. except UnexpectedCharacters as e2:
  402. e = e2
  403. ###}