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.

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