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.

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