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.

298 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. try:
  84. return self.options[name]
  85. except KeyError as e:
  86. raise AttributeError(e)
  87. def __setattr__(self, name, value):
  88. assert name in self.options
  89. self.options[name] = value
  90. def serialize(self, memo):
  91. return self.options
  92. @classmethod
  93. def deserialize(cls, data, memo):
  94. return cls(data)
  95. class Lark(Serialize):
  96. def __init__(self, grammar, **options):
  97. """
  98. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  99. options : a dictionary controlling various aspects of Lark.
  100. """
  101. self.options = LarkOptions(options)
  102. # Some, but not all file-like objects have a 'name' attribute
  103. try:
  104. self.source = grammar.name
  105. except AttributeError:
  106. self.source = '<string>'
  107. # Drain file-like objects to get their contents
  108. try:
  109. read = grammar.read
  110. except AttributeError:
  111. pass
  112. else:
  113. grammar = read()
  114. assert isinstance(grammar, STRING_TYPE)
  115. if self.options.cache_grammar:
  116. raise NotImplementedError("Not available yet")
  117. if self.options.lexer == 'auto':
  118. if self.options.parser == 'lalr':
  119. self.options.lexer = 'contextual'
  120. elif self.options.parser == 'earley':
  121. self.options.lexer = 'dynamic'
  122. elif self.options.parser == 'cyk':
  123. self.options.lexer = 'standard'
  124. else:
  125. assert False, self.options.parser
  126. lexer = self.options.lexer
  127. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  128. if self.options.ambiguity == 'auto':
  129. if self.options.parser == 'earley':
  130. self.options.ambiguity = 'resolve'
  131. else:
  132. disambig_parsers = ['earley', 'cyk']
  133. assert self.options.parser in disambig_parsers, (
  134. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  135. if self.options.priority == 'auto':
  136. if self.options.parser in ('earley', 'cyk', ):
  137. self.options.priority = 'normal'
  138. elif self.options.parser in ('lalr', ):
  139. self.options.priority = None
  140. elif self.options.priority in ('invert', 'normal'):
  141. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  142. assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  143. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  144. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', )
  145. # Parse the grammar file and compose the grammars (TODO)
  146. self.grammar = load_grammar(grammar, self.source)
  147. # Compile the EBNF grammar into BNF
  148. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start)
  149. if self.options.edit_terminals:
  150. for t in self.terminals:
  151. self.options.edit_terminals(t)
  152. self._terminals_dict = {t.name:t for t in self.terminals}
  153. # If the user asked to invert the priorities, negate them all here.
  154. # This replaces the old 'resolve__antiscore_sum' option.
  155. if self.options.priority == 'invert':
  156. for rule in self.rules:
  157. if rule.options.priority is not None:
  158. rule.options.priority = -rule.options.priority
  159. # Else, if the user asked to disable priorities, strip them from the
  160. # rules. This allows the Earley parsers to skip an extra forest walk
  161. # for improved performance, if you don't need them (or didn't specify any).
  162. elif self.options.priority == None:
  163. for rule in self.rules:
  164. if rule.options.priority is not None:
  165. rule.options.priority = None
  166. # TODO Deprecate lexer_callbacks?
  167. lexer_callbacks = dict(self.options.lexer_callbacks)
  168. if self.options.transformer:
  169. t = self.options.transformer
  170. for term in self.terminals:
  171. if hasattr(t, term.name):
  172. lexer_callbacks[term.name] = getattr(t, term.name)
  173. self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, lexer_callbacks)
  174. if self.options.parser:
  175. self.parser = self._build_parser()
  176. elif lexer:
  177. self.lexer = self._build_lexer()
  178. if __init__.__doc__:
  179. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  180. __serialize_fields__ = 'parser', 'rules', 'options'
  181. def _build_lexer(self):
  182. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks)
  183. def _prepare_callbacks(self):
  184. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  185. 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)
  186. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  187. def _build_parser(self):
  188. self._prepare_callbacks()
  189. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  190. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  191. @classmethod
  192. def deserialize(cls, data, namespace, memo, transformer=None, postlex=None):
  193. if memo:
  194. memo = SerializeMemoizer.deserialize(memo, namespace, {})
  195. inst = cls.__new__(cls)
  196. options = dict(data['options'])
  197. options['transformer'] = transformer
  198. options['postlex'] = postlex
  199. inst.options = LarkOptions.deserialize(options, memo)
  200. inst.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  201. inst.source = '<deserialized>'
  202. inst._prepare_callbacks()
  203. inst.parser = inst.parser_class.deserialize(data['parser'], memo, inst._callbacks, inst.options.postlex)
  204. return inst
  205. @classmethod
  206. def open(cls, grammar_filename, rel_to=None, **options):
  207. """Create an instance of Lark with the grammar given by its filename
  208. If rel_to is provided, the function will find the grammar filename in relation to it.
  209. Example:
  210. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  211. Lark(...)
  212. """
  213. if rel_to:
  214. basepath = os.path.dirname(rel_to)
  215. grammar_filename = os.path.join(basepath, grammar_filename)
  216. with open(grammar_filename, encoding='utf8') as f:
  217. return cls(f, **options)
  218. def __repr__(self):
  219. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  220. def lex(self, text):
  221. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  222. if not hasattr(self, 'lexer'):
  223. self.lexer = self._build_lexer()
  224. stream = self.lexer.lex(text)
  225. if self.options.postlex:
  226. return self.options.postlex.process(stream)
  227. return stream
  228. def get_terminal(self, name):
  229. "Get information about a terminal"
  230. return self._terminals_dict[name]
  231. def parse(self, text, start=None):
  232. """Parse the given text, according to the options provided.
  233. The 'start' parameter is required if Lark was given multiple possible start symbols (using the start option).
  234. Returns a tree, unless specified otherwise.
  235. """
  236. return self.parser.parse(text, start=start)
  237. ###}