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.

545 lines
22 KiB

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