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.

406 lines
15 KiB

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