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.

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