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.

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