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.

591 lines
24 KiB

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