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.

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