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.

549 lines
22 KiB

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