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.

569 lines
23 KiB

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