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.

294 lines
12 KiB

  1. from __future__ import absolute_import
  2. import os
  3. import time
  4. from collections import defaultdict
  5. from io import open
  6. from .utils import STRING_TYPE, Serialize, SerializeMemoizer
  7. from .load_grammar import load_grammar
  8. from .tree import Tree
  9. from .common import LexerConf, ParserConf
  10. from .lexer import Lexer, TraditionalLexer
  11. from .parse_tree_builder import ParseTreeBuilder
  12. from .parser_frontends import get_frontend
  13. from .grammar import Rule
  14. ###{standalone
  15. class LarkOptions(Serialize):
  16. """Specifies the options for Lark
  17. """
  18. OPTIONS_DOC = """
  19. parser - Decides which parser engine to use, "earley" or "lalr". (Default: "earley")
  20. Note: "lalr" requires a lexer
  21. lexer - Decides whether or not to use a lexer stage
  22. "standard": Use a standard lexer
  23. "contextual": Stronger lexer (only works with parser="lalr")
  24. "dynamic": Flexible and powerful (only with parser="earley")
  25. "dynamic_complete": Same as dynamic, but tries *every* variation
  26. of tokenizing possible. (only with parser="earley")
  27. "auto" (default): Choose for me based on grammar and parser
  28. ambiguity - Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
  29. "resolve": The parser will automatically choose the simplest derivation
  30. (it chooses consistently: greedy for tokens, non-greedy for rules)
  31. "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
  32. transformer - Applies the transformer to every parse tree
  33. debug - Affects verbosity (default: False)
  34. keep_all_tokens - Don't automagically remove "punctuation" tokens (default: False)
  35. cache_grammar - Cache the Lark grammar (Default: False)
  36. postlex - Lexer post-processing (Default: None) Only works with the standard and contextual lexers.
  37. start - The start symbol, either a string, or a list of strings for multiple possible starts (Default: "start")
  38. priority - How priorities should be evaluated - auto, none, normal, invert (Default: auto)
  39. propagate_positions - Propagates [line, column, end_line, end_column] attributes into all tree branches.
  40. lexer_callbacks - Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
  41. maybe_placeholders - Experimental feature. Instead of omitting optional rules (i.e. rule?), replace them with None
  42. """
  43. if __doc__:
  44. __doc__ += OPTIONS_DOC
  45. _defaults = {
  46. 'debug': False,
  47. 'keep_all_tokens': False,
  48. 'tree_class': None,
  49. 'cache_grammar': False,
  50. 'postlex': None,
  51. 'parser': 'earley',
  52. 'lexer': 'auto',
  53. 'transformer': None,
  54. 'start': 'start',
  55. 'priority': 'auto',
  56. 'ambiguity': 'auto',
  57. 'propagate_positions': True,
  58. 'lexer_callbacks': {},
  59. 'maybe_placeholders': True,
  60. 'edit_terminals': None,
  61. }
  62. def __init__(self, options_dict):
  63. o = dict(options_dict)
  64. options = {}
  65. for name, default in self._defaults.items():
  66. if name in o:
  67. value = o.pop(name)
  68. if isinstance(default, bool):
  69. value = bool(value)
  70. else:
  71. value = default
  72. options[name] = value
  73. if isinstance(options['start'], STRING_TYPE):
  74. options['start'] = [options['start']]
  75. self.__dict__['options'] = options
  76. assert self.parser in ('earley', 'lalr', 'cyk', None)
  77. if self.parser == 'earley' and self.transformer:
  78. raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.'
  79. 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
  80. if o:
  81. raise ValueError("Unknown options: %s" % o.keys())
  82. def __getattr__(self, name):
  83. return self.options[name]
  84. def __setattr__(self, name, value):
  85. assert name in self.options
  86. self.options[name] = value
  87. def serialize(self, memo):
  88. return self.options
  89. @classmethod
  90. def deserialize(cls, data, memo):
  91. return cls(data)
  92. class Lark(Serialize):
  93. def __init__(self, grammar, **options):
  94. """
  95. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  96. options : a dictionary controlling various aspects of Lark.
  97. """
  98. self.options = LarkOptions(options)
  99. # Some, but not all file-like objects have a 'name' attribute
  100. try:
  101. self.source = grammar.name
  102. except AttributeError:
  103. self.source = '<string>'
  104. # Drain file-like objects to get their contents
  105. try:
  106. read = grammar.read
  107. except AttributeError:
  108. pass
  109. else:
  110. grammar = read()
  111. assert isinstance(grammar, STRING_TYPE)
  112. if self.options.cache_grammar:
  113. raise NotImplementedError("Not available yet")
  114. if self.options.lexer == 'auto':
  115. if self.options.parser == 'lalr':
  116. self.options.lexer = 'contextual'
  117. elif self.options.parser == 'earley':
  118. self.options.lexer = 'dynamic'
  119. elif self.options.parser == 'cyk':
  120. self.options.lexer = 'standard'
  121. else:
  122. assert False, self.options.parser
  123. lexer = self.options.lexer
  124. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  125. if self.options.ambiguity == 'auto':
  126. if self.options.parser == 'earley':
  127. self.options.ambiguity = 'resolve'
  128. else:
  129. disambig_parsers = ['earley', 'cyk']
  130. assert self.options.parser in disambig_parsers, (
  131. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  132. if self.options.priority == 'auto':
  133. if self.options.parser in ('earley', 'cyk', ):
  134. self.options.priority = 'normal'
  135. elif self.options.parser in ('lalr', ):
  136. self.options.priority = None
  137. elif self.options.priority in ('invert', 'normal'):
  138. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  139. assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  140. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  141. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', )
  142. # Parse the grammar file and compose the grammars (TODO)
  143. self.grammar = load_grammar(grammar, self.source)
  144. # Compile the EBNF grammar into BNF
  145. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start)
  146. if self.options.edit_terminals:
  147. for t in self.terminals:
  148. self.options.edit_terminals(t)
  149. self._terminals_dict = {t.name:t for t in self.terminals}
  150. # If the user asked to invert the priorities, negate them all here.
  151. # This replaces the old 'resolve__antiscore_sum' option.
  152. if self.options.priority == 'invert':
  153. for rule in self.rules:
  154. if rule.options and rule.options.priority is not None:
  155. rule.options.priority = -rule.options.priority
  156. # Else, if the user asked to disable priorities, strip them from the
  157. # rules. This allows the Earley parsers to skip an extra forest walk
  158. # for improved performance, if you don't need them (or didn't specify any).
  159. elif self.options.priority == None:
  160. for rule in self.rules:
  161. if rule.options and rule.options.priority is not None:
  162. rule.options.priority = None
  163. # TODO Deprecate lexer_callbacks?
  164. lexer_callbacks = dict(self.options.lexer_callbacks)
  165. if self.options.transformer:
  166. t = self.options.transformer
  167. for term in self.terminals:
  168. if hasattr(t, term.name):
  169. lexer_callbacks[term.name] = getattr(t, term.name)
  170. self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, lexer_callbacks)
  171. if self.options.parser:
  172. self.parser = self._build_parser()
  173. elif lexer:
  174. self.lexer = self._build_lexer()
  175. if __init__.__doc__:
  176. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  177. __serialize_fields__ = 'parser', 'rules', 'options'
  178. def _build_lexer(self):
  179. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks)
  180. def _prepare_callbacks(self):
  181. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  182. 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)
  183. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  184. def _build_parser(self):
  185. self._prepare_callbacks()
  186. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  187. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  188. @classmethod
  189. def deserialize(cls, data, namespace, memo, transformer=None, postlex=None):
  190. if memo:
  191. memo = SerializeMemoizer.deserialize(memo, namespace, {})
  192. inst = cls.__new__(cls)
  193. options = dict(data['options'])
  194. options['transformer'] = transformer
  195. options['postlex'] = postlex
  196. inst.options = LarkOptions.deserialize(options, memo)
  197. inst.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  198. inst.source = '<deserialized>'
  199. inst._prepare_callbacks()
  200. inst.parser = inst.parser_class.deserialize(data['parser'], memo, inst._callbacks, inst.options.postlex)
  201. return inst
  202. @classmethod
  203. def open(cls, grammar_filename, rel_to=None, **options):
  204. """Create an instance of Lark with the grammar given by its filename
  205. If rel_to is provided, the function will find the grammar filename in relation to it.
  206. Example:
  207. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  208. Lark(...)
  209. """
  210. if rel_to:
  211. basepath = os.path.dirname(rel_to)
  212. grammar_filename = os.path.join(basepath, grammar_filename)
  213. with open(grammar_filename, encoding='utf8') as f:
  214. return cls(f, **options)
  215. def __repr__(self):
  216. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  217. def lex(self, text):
  218. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  219. if not hasattr(self, 'lexer'):
  220. self.lexer = self._build_lexer()
  221. stream = self.lexer.lex(text)
  222. if self.options.postlex:
  223. return self.options.postlex.process(stream)
  224. return stream
  225. def get_terminal(self, name):
  226. "Get information about a terminal"
  227. return self._terminals_dict[name]
  228. def parse(self, text, start=None):
  229. """Parse the given text, according to the options provided.
  230. The 'start' parameter is required if Lark was given multiple possible start symbols (using the start option).
  231. Returns a tree, unless specified otherwise.
  232. """
  233. return self.parser.parse(text, start=start)
  234. ###}