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.

585 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
  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()).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. cache_fn = tempfile.gettempdir() + '/.lark_cache_%s_%s_%s.tmp' % (cache_md5, *sys.version_info[:2])
  234. if FS.exists(cache_fn):
  235. logger.debug('Loading grammar from cache: %s', cache_fn)
  236. # Remove options that aren't relevant for loading from cache
  237. for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
  238. del options[name]
  239. with FS.open(cache_fn, 'rb') as f:
  240. file_md5 = f.readline().rstrip(b'\n')
  241. if file_md5 == cache_md5.encode():
  242. try:
  243. self._load(f, **options)
  244. except Exception:
  245. raise RuntimeError("Failed to load Lark from cache: %r. Try to delete the file and run again." % cache_fn)
  246. return
  247. # Parse the grammar file and compose the grammars
  248. self.grammar = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens)
  249. else:
  250. assert isinstance(grammar, Grammar)
  251. self.grammar = grammar
  252. if self.options.lexer == 'auto':
  253. if self.options.parser == 'lalr':
  254. self.options.lexer = 'contextual'
  255. elif self.options.parser == 'earley':
  256. if self.options.postlex is not None:
  257. logger.info("postlex can't be used with the dynamic lexer, so we use standard instead. "
  258. "Consider using lalr with contextual instead of earley")
  259. self.options.lexer = 'standard'
  260. else:
  261. self.options.lexer = 'dynamic'
  262. elif self.options.parser == 'cyk':
  263. self.options.lexer = 'standard'
  264. else:
  265. assert False, self.options.parser
  266. lexer = self.options.lexer
  267. if isinstance(lexer, type):
  268. assert issubclass(lexer, Lexer) # XXX Is this really important? Maybe just ensure interface compliance
  269. else:
  270. assert_config(lexer, ('standard', 'contextual', 'dynamic', 'dynamic_complete'))
  271. if self.options.postlex is not None and 'dynamic' in lexer:
  272. raise ConfigurationError("Can't use postlex with a dynamic lexer. Use standard or contextual instead")
  273. if self.options.ambiguity == 'auto':
  274. if self.options.parser == 'earley':
  275. self.options.ambiguity = 'resolve'
  276. else:
  277. assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s")
  278. if self.options.priority == 'auto':
  279. self.options.priority = 'normal'
  280. if self.options.priority not in _VALID_PRIORITY_OPTIONS:
  281. raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
  282. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  283. if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
  284. raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
  285. if self.options.postlex is not None:
  286. terminals_to_keep = set(self.options.postlex.always_accept)
  287. else:
  288. terminals_to_keep = set()
  289. # Compile the EBNF grammar into BNF
  290. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
  291. if self.options.edit_terminals:
  292. for t in self.terminals:
  293. self.options.edit_terminals(t)
  294. self._terminals_dict = {t.name: t for t in self.terminals}
  295. # If the user asked to invert the priorities, negate them all here.
  296. # This replaces the old 'resolve__antiscore_sum' option.
  297. if self.options.priority == 'invert':
  298. for rule in self.rules:
  299. if rule.options.priority is not None:
  300. rule.options.priority = -rule.options.priority
  301. # Else, if the user asked to disable priorities, strip them from the
  302. # rules. This allows the Earley parsers to skip an extra forest walk
  303. # for improved performance, if you don't need them (or didn't specify any).
  304. elif self.options.priority is None:
  305. for rule in self.rules:
  306. if rule.options.priority is not None:
  307. rule.options.priority = None
  308. # TODO Deprecate lexer_callbacks?
  309. self.lexer_conf = LexerConf(
  310. self.terminals, re_module, self.ignore_tokens, self.options.postlex,
  311. self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes
  312. )
  313. if self.options.parser:
  314. self.parser = self._build_parser()
  315. elif lexer:
  316. self.lexer = self._build_lexer()
  317. if cache_fn:
  318. logger.debug('Saving grammar to cache: %s', cache_fn)
  319. with FS.open(cache_fn, 'wb') as f:
  320. f.write(b'%s\n' % cache_md5.encode())
  321. self.save(f)
  322. if __doc__:
  323. __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
  324. __serialize_fields__ = 'parser', 'rules', 'options'
  325. def _build_lexer(self, dont_ignore=False):
  326. lexer_conf = self.lexer_conf
  327. if dont_ignore:
  328. from copy import copy
  329. lexer_conf = copy(lexer_conf)
  330. lexer_conf.ignore = ()
  331. return TraditionalLexer(lexer_conf)
  332. def _prepare_callbacks(self):
  333. self._callbacks = {}
  334. # we don't need these callbacks if we aren't building a tree
  335. if self.options.ambiguity != 'forest':
  336. self._parse_tree_builder = ParseTreeBuilder(
  337. self.rules,
  338. self.options.tree_class or Tree,
  339. self.options.propagate_positions,
  340. self.options.parser != 'lalr' and self.options.ambiguity == 'explicit',
  341. self.options.maybe_placeholders
  342. )
  343. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  344. self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals))
  345. def _build_parser(self):
  346. self._prepare_callbacks()
  347. parser_class = get_frontend(self.options.parser, self.options.lexer)
  348. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  349. return parser_class(self.lexer_conf, parser_conf, options=self.options)
  350. def save(self, f):
  351. """Saves the instance into the given file object
  352. Useful for caching and multiprocessing.
  353. """
  354. data, m = self.memo_serialize([TerminalDef, Rule])
  355. pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
  356. @classmethod
  357. def load(cls, f):
  358. """Loads an instance from the given file object
  359. Useful for caching and multiprocessing.
  360. """
  361. inst = cls.__new__(cls)
  362. return inst._load(f)
  363. def _deserialize_lexer_conf(self, data, memo, options):
  364. lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
  365. lexer_conf.callbacks = options.lexer_callbacks or {}
  366. lexer_conf.re_module = regex if options.regex else re
  367. lexer_conf.use_bytes = options.use_bytes
  368. lexer_conf.g_regex_flags = options.g_regex_flags
  369. lexer_conf.skip_validation = True
  370. lexer_conf.postlex = options.postlex
  371. return lexer_conf
  372. def _load(self, f, **kwargs):
  373. if isinstance(f, dict):
  374. d = f
  375. else:
  376. d = pickle.load(f)
  377. memo = d['memo']
  378. data = d['data']
  379. assert memo
  380. memo = SerializeMemoizer.deserialize(memo, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
  381. options = dict(data['options'])
  382. if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
  383. raise ConfigurationError("Some options are not allowed when loading a Parser: {}"
  384. .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
  385. options.update(kwargs)
  386. self.options = LarkOptions.deserialize(options, memo)
  387. self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  388. self.source_path = '<deserialized>'
  389. parser_class = get_frontend(self.options.parser, self.options.lexer)
  390. self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options)
  391. self.terminals = self.lexer_conf.terminals
  392. self._prepare_callbacks()
  393. self._terminals_dict = {t.name: t for t in self.terminals}
  394. self.parser = parser_class.deserialize(
  395. data['parser'],
  396. memo,
  397. self.lexer_conf,
  398. self._callbacks,
  399. self.options, # Not all, but multiple attributes are used
  400. )
  401. return self
  402. @classmethod
  403. def _load_from_dict(cls, data, memo, **kwargs):
  404. inst = cls.__new__(cls)
  405. return inst._load({'data': data, 'memo': memo}, **kwargs)
  406. @classmethod
  407. def open(cls, grammar_filename, rel_to=None, **options):
  408. """Create an instance of Lark with the grammar given by its filename
  409. If ``rel_to`` is provided, the function will find the grammar filename in relation to it.
  410. Example:
  411. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  412. Lark(...)
  413. """
  414. if rel_to:
  415. basepath = os.path.dirname(rel_to)
  416. grammar_filename = os.path.join(basepath, grammar_filename)
  417. with open(grammar_filename, encoding='utf8') as f:
  418. return cls(f, **options)
  419. @classmethod
  420. def open_from_package(cls, package, grammar_path, search_paths=("",), **options):
  421. """Create an instance of Lark with the grammar loaded from within the package `package`.
  422. This allows grammar loading from zipapps.
  423. Imports in the grammar will use the `package` and `search_paths` provided, through `FromPackageLoader`
  424. Example:
  425. Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...)
  426. """
  427. package = FromPackageLoader(package, search_paths)
  428. full_path, text = package(None, grammar_path)
  429. options.setdefault('source_path', full_path)
  430. options.setdefault('import_paths', [])
  431. options['import_paths'].append(package)
  432. return cls(text, **options)
  433. def __repr__(self):
  434. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer)
  435. def lex(self, text, dont_ignore=False):
  436. """Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'
  437. When dont_ignore=True, the lexer will return all tokens, even those marked for %ignore.
  438. """
  439. if not hasattr(self, 'lexer') or dont_ignore:
  440. lexer = self._build_lexer(dont_ignore)
  441. else:
  442. lexer = self.lexer
  443. lexer_thread = LexerThread(lexer, text)
  444. stream = lexer_thread.lex(None)
  445. if self.options.postlex:
  446. return self.options.postlex.process(stream)
  447. return stream
  448. def get_terminal(self, name):
  449. "Get information about a terminal"
  450. return self._terminals_dict[name]
  451. def parse(self, text, start=None, on_error=None):
  452. """Parse the given text, according to the options provided.
  453. Parameters:
  454. text (str): Text to be parsed.
  455. start (str, optional): Required if Lark was given multiple possible start symbols (using the start option).
  456. on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing.
  457. LALR only. See examples/advanced/error_puppet.py for an example of how to use on_error.
  458. Returns:
  459. If a transformer is supplied to ``__init__``, returns whatever is the
  460. result of the transformation. Otherwise, returns a Tree instance.
  461. """
  462. return self.parser.parse(text, start=start, on_error=on_error)
  463. @property
  464. def source(self):
  465. warn("Lark.source attribute has been renamed to Lark.source_path", DeprecationWarning)
  466. return self.source_path
  467. @source.setter
  468. def source(self, value):
  469. self.source_path = value
  470. @property
  471. def grammar_source(self):
  472. warn("Lark.grammar_source attribute has been renamed to Lark.source_grammar", DeprecationWarning)
  473. return self.source_grammar
  474. @grammar_source.setter
  475. def grammar_source(self, value):
  476. self.source_grammar = value
  477. ###}