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.

390 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
  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. self.re = regex
  137. else:
  138. raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
  139. else:
  140. self.re = 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. options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
  165. s = grammar + options_str
  166. md5 = hashlib.md5(s.encode()).hexdigest()
  167. cache_fn = '.lark_cache_%s.tmp' % md5
  168. if FS.exists(cache_fn):
  169. logging.debug('Loading grammar from cache: %s', cache_fn)
  170. with FS.open(cache_fn, 'rb') as f:
  171. self._load(f, self.options.transformer, self.options.postlex)
  172. return
  173. if self.options.lexer == 'auto':
  174. if self.options.parser == 'lalr':
  175. self.options.lexer = 'contextual'
  176. elif self.options.parser == 'earley':
  177. self.options.lexer = 'dynamic'
  178. elif self.options.parser == 'cyk':
  179. self.options.lexer = 'standard'
  180. else:
  181. assert False, self.options.parser
  182. lexer = self.options.lexer
  183. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  184. if self.options.ambiguity == 'auto':
  185. if self.options.parser == 'earley':
  186. self.options.ambiguity = 'resolve'
  187. else:
  188. disambig_parsers = ['earley', 'cyk']
  189. assert self.options.parser in disambig_parsers, (
  190. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  191. if self.options.priority == 'auto':
  192. if self.options.parser in ('earley', 'cyk', ):
  193. self.options.priority = 'normal'
  194. elif self.options.parser in ('lalr', ):
  195. self.options.priority = None
  196. elif self.options.priority in ('invert', 'normal'):
  197. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  198. assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  199. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  200. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', )
  201. # Parse the grammar file and compose the grammars (TODO)
  202. self.grammar = load_grammar(grammar, self.source, self.re)
  203. # Compile the EBNF grammar into BNF
  204. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start)
  205. if self.options.edit_terminals:
  206. for t in self.terminals:
  207. self.options.edit_terminals(t)
  208. self._terminals_dict = {t.name:t for t in self.terminals}
  209. # If the user asked to invert the priorities, negate them all here.
  210. # This replaces the old 'resolve__antiscore_sum' option.
  211. if self.options.priority == 'invert':
  212. for rule in self.rules:
  213. if rule.options.priority is not None:
  214. rule.options.priority = -rule.options.priority
  215. # Else, if the user asked to disable priorities, strip them from the
  216. # rules. This allows the Earley parsers to skip an extra forest walk
  217. # for improved performance, if you don't need them (or didn't specify any).
  218. elif self.options.priority == None:
  219. for rule in self.rules:
  220. if rule.options.priority is not None:
  221. rule.options.priority = None
  222. # TODO Deprecate lexer_callbacks?
  223. lexer_callbacks = dict(self.options.lexer_callbacks)
  224. if self.options.transformer:
  225. t = self.options.transformer
  226. for term in self.terminals:
  227. if hasattr(t, term.name):
  228. lexer_callbacks[term.name] = getattr(t, term.name)
  229. self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, lexer_callbacks, self.options.g_regex_flags)
  230. if self.options.parser:
  231. self.parser = self._build_parser()
  232. elif lexer:
  233. self.lexer = self._build_lexer()
  234. if cache_fn:
  235. logging.debug('Saving grammar to cache: %s', cache_fn)
  236. with FS.open(cache_fn, 'wb') as f:
  237. self.save(f)
  238. if __init__.__doc__:
  239. __init__.__doc__ += "\nOptions:\n" + LarkOptions.OPTIONS_DOC
  240. __serialize_fields__ = 'parser', 'rules', 'options'
  241. def _build_lexer(self):
  242. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks, g_regex_flags=self.lexer_conf.g_regex_flags)
  243. def _prepare_callbacks(self):
  244. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  245. 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)
  246. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  247. def _build_parser(self):
  248. self._prepare_callbacks()
  249. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  250. return self.parser_class(self.lexer_conf, parser_conf, self.re, options=self.options)
  251. def save(self, f):
  252. data, m = self.memo_serialize([TerminalDef, Rule])
  253. pickle.dump({'data': data, 'memo': m}, f)
  254. @classmethod
  255. def load(cls, f):
  256. inst = cls.__new__(cls)
  257. return inst._load(f)
  258. def _load(self, f, transformer=None, postlex=None):
  259. if isinstance(f, dict):
  260. d = f
  261. else:
  262. d = pickle.load(f)
  263. memo = d['memo']
  264. data = d['data']
  265. assert memo
  266. memo = SerializeMemoizer.deserialize(memo, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
  267. options = dict(data['options'])
  268. if transformer is not None:
  269. options['transformer'] = transformer
  270. if postlex is not None:
  271. options['postlex'] = postlex
  272. self.options = LarkOptions.deserialize(options, memo)
  273. self.re = regex if self.options.regex else re
  274. self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  275. self.source = '<deserialized>'
  276. self._prepare_callbacks()
  277. self.parser = self.parser_class.deserialize(data['parser'], memo, self._callbacks, self.options.postlex, self.re)
  278. return self
  279. @classmethod
  280. def _load_from_dict(cls, data, memo, transformer=None, postlex=None):
  281. inst = cls.__new__(cls)
  282. return inst._load({'data': data, 'memo': memo}, transformer, postlex)
  283. @classmethod
  284. def open(cls, grammar_filename, rel_to=None, **options):
  285. """Create an instance of Lark with the grammar given by its filename
  286. If rel_to is provided, the function will find the grammar filename in relation to it.
  287. Example:
  288. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  289. Lark(...)
  290. """
  291. if rel_to:
  292. basepath = os.path.dirname(rel_to)
  293. grammar_filename = os.path.join(basepath, grammar_filename)
  294. with open(grammar_filename, encoding='utf8') as f:
  295. return cls(f, **options)
  296. def __repr__(self):
  297. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  298. def lex(self, text):
  299. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  300. if not hasattr(self, 'lexer'):
  301. self.lexer = self._build_lexer()
  302. stream = self.lexer.lex(text)
  303. if self.options.postlex:
  304. return self.options.postlex.process(stream)
  305. return stream
  306. def get_terminal(self, name):
  307. "Get information about a terminal"
  308. return self._terminals_dict[name]
  309. def parse(self, text, start=None):
  310. """Parse the given text, according to the options provided.
  311. The 'start' parameter is required if Lark was given multiple possible start symbols (using the start option).
  312. Returns a tree, unless specified otherwise.
  313. """
  314. return self.parser.parse(text, start=start)
  315. ###}