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.

487 lines
19 KiB

  1. from __future__ import absolute_import
  2. import sys, os, pickle, hashlib
  3. from io import open
  4. from .utils import STRING_TYPE, Serialize, SerializeMemoizer, FS, isascii, logger
  5. from .load_grammar import load_grammar, FromPackageLoader
  6. from .tree import Tree
  7. from .common import LexerConf, ParserConf
  8. from .lexer import Lexer, TraditionalLexer, TerminalDef, UnexpectedToken
  9. from .parse_tree_builder import ParseTreeBuilder
  10. from .parser_frontends import get_frontend, _get_lexer_callbacks
  11. from .grammar import Rule
  12. import re
  13. try:
  14. import regex
  15. except ImportError:
  16. regex = None
  17. ###{standalone
  18. class LarkOptions(Serialize):
  19. """Specifies the options for Lark
  20. """
  21. OPTIONS_DOC = """
  22. **=== General Options ===**
  23. start
  24. The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start")
  25. debug
  26. Display debug information, such as warnings (default: False)
  27. transformer
  28. Applies the transformer to every parse tree (equivlent to applying it after the parse, but faster)
  29. propagate_positions
  30. Propagates (line, column, end_line, end_column) attributes into all tree branches.
  31. maybe_placeholders
  32. When True, the ``[]`` operator returns ``None`` when not matched.
  33. When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all.
  34. (default= ``False``. Recommended to set to ``True``)
  35. cache
  36. Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now.
  37. - When ``False``, does nothing (default)
  38. - When ``True``, caches to a temporary file in the local directory
  39. - When given a string, caches to the path pointed by the string
  40. regex
  41. When True, uses the ``regex`` module instead of the stdlib ``re``.
  42. g_regex_flags
  43. Flags that are applied to all terminals (both regex and strings)
  44. keep_all_tokens
  45. Prevent the tree builder from automagically removing "punctuation" tokens (default: False)
  46. tree_class
  47. Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``.
  48. **=== Algorithm Options ===**
  49. parser
  50. Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley").
  51. (there is also a "cyk" option for legacy)
  52. lexer
  53. Decides whether or not to use a lexer stage
  54. - "auto" (default): Choose for me based on the parser
  55. - "standard": Use a standard lexer
  56. - "contextual": Stronger lexer (only works with parser="lalr")
  57. - "dynamic": Flexible and powerful (only with parser="earley")
  58. - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible.
  59. ambiguity
  60. Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
  61. - "resolve": The parser will automatically choose the simplest derivation
  62. (it chooses consistently: greedy for tokens, non-greedy for rules)
  63. - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
  64. - "forest": The parser will return the root of the shared packed parse forest.
  65. **=== Misc. / Domain Specific Options ===**
  66. postlex
  67. Lexer post-processing (Default: None) Only works with the standard and contextual lexers.
  68. priority
  69. How priorities should be evaluated - auto, none, normal, invert (Default: auto)
  70. lexer_callbacks
  71. Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
  72. use_bytes
  73. Accept an input of type ``bytes`` instead of ``str`` (Python 3 only).
  74. edit_terminals
  75. A callback for editing the terminals before parse.
  76. import_sources
  77. A List of either paths or loader functions to specify from where grammars are imported
  78. source
  79. Override the source of from where the grammar was loaded. Usefull for relative imports and unconventional grammar loading
  80. **=== End Options ===**
  81. """
  82. if __doc__:
  83. __doc__ += OPTIONS_DOC
  84. _defaults = {
  85. 'debug': False,
  86. 'keep_all_tokens': False,
  87. 'tree_class': None,
  88. 'cache': False,
  89. 'postlex': None,
  90. 'parser': 'earley',
  91. 'lexer': 'auto',
  92. 'transformer': None,
  93. 'start': 'start',
  94. 'priority': 'auto',
  95. 'ambiguity': 'auto',
  96. 'regex': False,
  97. 'propagate_positions': False,
  98. 'lexer_callbacks': {},
  99. 'maybe_placeholders': False,
  100. 'edit_terminals': None,
  101. 'g_regex_flags': 0,
  102. 'use_bytes': False,
  103. 'import_sources': [],
  104. 'source': None,
  105. }
  106. def __init__(self, options_dict):
  107. o = dict(options_dict)
  108. options = {}
  109. for name, default in self._defaults.items():
  110. if name in o:
  111. value = o.pop(name)
  112. if isinstance(default, bool) and name not in ('cache', 'use_bytes'):
  113. value = bool(value)
  114. else:
  115. value = default
  116. options[name] = value
  117. if isinstance(options['start'], STRING_TYPE):
  118. options['start'] = [options['start']]
  119. self.__dict__['options'] = options
  120. assert self.parser in ('earley', 'lalr', 'cyk', None)
  121. if self.parser == 'earley' and self.transformer:
  122. raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.'
  123. 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
  124. if o:
  125. raise ValueError("Unknown options: %s" % o.keys())
  126. def __getattr__(self, name):
  127. try:
  128. return self.options[name]
  129. except KeyError as e:
  130. raise AttributeError(e)
  131. def __setattr__(self, name, value):
  132. assert name in self.options
  133. self.options[name] = value
  134. def serialize(self, memo):
  135. return self.options
  136. @classmethod
  137. def deserialize(cls, data, memo):
  138. return cls(data)
  139. class Lark(Serialize):
  140. """Main interface for the library.
  141. It's mostly a thin wrapper for the many different parsers, and for the tree constructor.
  142. Parameters:
  143. grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  144. options: a dictionary controlling various aspects of Lark.
  145. Example:
  146. >>> Lark(r'''start: "foo" ''')
  147. Lark(...)
  148. """
  149. def __init__(self, grammar, **options):
  150. self.options = LarkOptions(options)
  151. # Set regex or re module
  152. use_regex = self.options.regex
  153. if use_regex:
  154. if regex:
  155. re_module = regex
  156. else:
  157. raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
  158. else:
  159. re_module = re
  160. # Some, but not all file-like objects have a 'name' attribute
  161. if self.options.source is None:
  162. try:
  163. self.source = grammar.name
  164. except AttributeError:
  165. self.source = '<string>'
  166. else:
  167. self.source = self.options.source
  168. # Drain file-like objects to get their contents
  169. try:
  170. read = grammar.read
  171. except AttributeError:
  172. pass
  173. else:
  174. grammar = read()
  175. assert isinstance(grammar, STRING_TYPE)
  176. self.grammar_source = grammar
  177. if self.options.use_bytes:
  178. if not isascii(grammar):
  179. raise ValueError("Grammar must be ascii only, when use_bytes=True")
  180. if sys.version_info[0] == 2 and self.options.use_bytes != 'force':
  181. raise NotImplementedError("`use_bytes=True` may have issues on python2."
  182. "Use `use_bytes='force'` to use it at your own risk.")
  183. cache_fn = None
  184. if self.options.cache:
  185. if self.options.parser != 'lalr':
  186. raise NotImplementedError("cache only works with parser='lalr' for now")
  187. if isinstance(self.options.cache, STRING_TYPE):
  188. cache_fn = self.options.cache
  189. else:
  190. if self.options.cache is not True:
  191. raise ValueError("cache argument must be bool or str")
  192. unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals')
  193. from . import __version__
  194. options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
  195. s = grammar + options_str + __version__
  196. md5 = hashlib.md5(s.encode()).hexdigest()
  197. cache_fn = '.lark_cache_%s.tmp' % md5
  198. if FS.exists(cache_fn):
  199. logger.debug('Loading grammar from cache: %s', cache_fn)
  200. with FS.open(cache_fn, 'rb') as f:
  201. self._load(f, self.options.transformer, self.options.postlex)
  202. return
  203. if self.options.lexer == 'auto':
  204. if self.options.parser == 'lalr':
  205. self.options.lexer = 'contextual'
  206. elif self.options.parser == 'earley':
  207. self.options.lexer = 'dynamic'
  208. elif self.options.parser == 'cyk':
  209. self.options.lexer = 'standard'
  210. else:
  211. assert False, self.options.parser
  212. lexer = self.options.lexer
  213. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  214. if self.options.ambiguity == 'auto':
  215. if self.options.parser == 'earley':
  216. self.options.ambiguity = 'resolve'
  217. else:
  218. disambig_parsers = ['earley', 'cyk']
  219. assert self.options.parser in disambig_parsers, (
  220. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  221. if self.options.priority == 'auto':
  222. if self.options.parser in ('earley', 'cyk', ):
  223. self.options.priority = 'normal'
  224. elif self.options.parser in ('lalr', ):
  225. self.options.priority = None
  226. elif self.options.priority in ('invert', 'normal'):
  227. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  228. assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  229. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  230. assert self.options.ambiguity in ('resolve', 'explicit', 'forest', 'auto', )
  231. # Parse the grammar file and compose the grammars (TODO)
  232. self.grammar = load_grammar(grammar, self.source, re_module, self.options.import_sources)
  233. # Compile the EBNF grammar into BNF
  234. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start)
  235. if self.options.edit_terminals:
  236. for t in self.terminals:
  237. self.options.edit_terminals(t)
  238. self._terminals_dict = {t.name: t for t in self.terminals}
  239. # If the user asked to invert the priorities, negate them all here.
  240. # This replaces the old 'resolve__antiscore_sum' option.
  241. if self.options.priority == 'invert':
  242. for rule in self.rules:
  243. if rule.options.priority is not None:
  244. rule.options.priority = -rule.options.priority
  245. # Else, if the user asked to disable priorities, strip them from the
  246. # rules. This allows the Earley parsers to skip an extra forest walk
  247. # for improved performance, if you don't need them (or didn't specify any).
  248. elif self.options.priority == None:
  249. for rule in self.rules:
  250. if rule.options.priority is not None:
  251. rule.options.priority = None
  252. # TODO Deprecate lexer_callbacks?
  253. lexer_callbacks = (_get_lexer_callbacks(self.options.transformer, self.terminals)
  254. if self.options.transformer
  255. else {})
  256. lexer_callbacks.update(self.options.lexer_callbacks)
  257. self.lexer_conf = LexerConf(self.terminals, re_module, self.ignore_tokens, self.options.postlex, lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes)
  258. if self.options.parser:
  259. self.parser = self._build_parser()
  260. elif lexer:
  261. self.lexer = self._build_lexer()
  262. if cache_fn:
  263. logger.debug('Saving grammar to cache: %s', cache_fn)
  264. with FS.open(cache_fn, 'wb') as f:
  265. self.save(f)
  266. __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
  267. __serialize_fields__ = 'parser', 'rules', 'options'
  268. def _build_lexer(self):
  269. return TraditionalLexer(self.lexer_conf)
  270. def _prepare_callbacks(self):
  271. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  272. self._callbacks = None
  273. # we don't need these callbacks if we aren't building a tree
  274. if self.options.ambiguity != 'forest':
  275. self._parse_tree_builder = ParseTreeBuilder(self.rules, self.options.tree_class or Tree, self.options.propagate_positions, self.options.keep_all_tokens, self.options.parser!='lalr' and self.options.ambiguity=='explicit', self.options.maybe_placeholders)
  276. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  277. def _build_parser(self):
  278. self._prepare_callbacks()
  279. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  280. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  281. def save(self, f):
  282. """Saves the instance into the given file object
  283. Useful for caching and multiprocessing.
  284. """
  285. data, m = self.memo_serialize([TerminalDef, Rule])
  286. pickle.dump({'data': data, 'memo': m}, f)
  287. @classmethod
  288. def load(cls, f):
  289. """Loads an instance from the given file object
  290. Useful for caching and multiprocessing.
  291. """
  292. inst = cls.__new__(cls)
  293. return inst._load(f)
  294. def _load(self, f, transformer=None, postlex=None):
  295. if isinstance(f, dict):
  296. d = f
  297. else:
  298. d = pickle.load(f)
  299. memo = d['memo']
  300. data = d['data']
  301. assert memo
  302. memo = SerializeMemoizer.deserialize(memo, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
  303. options = dict(data['options'])
  304. if transformer is not None:
  305. options['transformer'] = transformer
  306. if postlex is not None:
  307. options['postlex'] = postlex
  308. self.options = LarkOptions.deserialize(options, memo)
  309. re_module = regex if self.options.regex else re
  310. self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  311. self.source = '<deserialized>'
  312. self._prepare_callbacks()
  313. self.parser = self.parser_class.deserialize(
  314. data['parser'],
  315. memo,
  316. self._callbacks,
  317. self.options.postlex,
  318. self.options.transformer,
  319. re_module
  320. )
  321. self.terminals = self.parser.lexer_conf.tokens
  322. self._terminals_dict = {t.name: t for t in self.terminals}
  323. return self
  324. @classmethod
  325. def _load_from_dict(cls, data, memo, transformer=None, postlex=None):
  326. inst = cls.__new__(cls)
  327. return inst._load({'data': data, 'memo': memo}, transformer, postlex)
  328. @classmethod
  329. def open(cls, grammar_filename, rel_to=None, **options):
  330. """Create an instance of Lark with the grammar given by its filename
  331. If ``rel_to`` is provided, the function will find the grammar filename in relation to it.
  332. Example:
  333. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  334. Lark(...)
  335. """
  336. if rel_to:
  337. basepath = os.path.dirname(rel_to)
  338. grammar_filename = os.path.join(basepath, grammar_filename)
  339. with open(grammar_filename, encoding='utf8') as f:
  340. return cls(f, **options)
  341. @classmethod
  342. def open_from_package(cls, package, grammar_path, search_paths=("",), **options):
  343. """Create an instance of Lark with the grammar loaded from within the package `package`.
  344. This allows grammar loading from zipapps.
  345. Will also create a `FromPackageLoader` instance and add it to the `import_sources` to simplify importing
  346. ``search_paths`` is passed to `FromPackageLoader`
  347. Example:
  348. Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...)
  349. """
  350. package = FromPackageLoader(package, search_paths)
  351. full_path, text = package([], grammar_path)
  352. options.setdefault('source', full_path)
  353. if 'import_sources' in options:
  354. options['import_sources'].append(package)
  355. else:
  356. options['import_sources'] = [package]
  357. return cls(text, **options)
  358. def __repr__(self):
  359. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  360. def lex(self, text):
  361. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  362. if not hasattr(self, 'lexer'):
  363. self.lexer = self._build_lexer()
  364. stream = self.lexer.lex(text)
  365. if self.options.postlex:
  366. return self.options.postlex.process(stream)
  367. return stream
  368. def get_terminal(self, name):
  369. "Get information about a terminal"
  370. return self._terminals_dict[name]
  371. def parse(self, text, start=None, on_error=None):
  372. """Parse the given text, according to the options provided.
  373. Parameters:
  374. text (str): Text to be parsed.
  375. start (str, optional): Required if Lark was given multiple possible start symbols (using the start option).
  376. on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing.
  377. LALR only. See examples/error_puppet.py for an example of how to use on_error.
  378. Returns:
  379. If a transformer is supplied to ``__init__``, returns whatever is the
  380. result of the transformation. Otherwise, returns a Tree instance.
  381. """
  382. try:
  383. return self.parser.parse(text, start=start)
  384. except UnexpectedToken as e:
  385. if on_error is None:
  386. raise
  387. while True:
  388. if not on_error(e):
  389. raise e
  390. try:
  391. return e.puppet.resume_parse()
  392. except UnexpectedToken as e2:
  393. if e.token.type == e2.token.type == '$END' and e.puppet == e2.puppet:
  394. # Prevent infinite loop
  395. raise e2
  396. e = e2
  397. ###}