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.

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