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.

311 lines
12 KiB

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