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.

595 lines
24 KiB

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