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.

296 lines
12 KiB

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