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.

309 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. profile - Measure run-time usage in Lark. Read results from the profiler proprety (Default: False)
  39. priority - How priorities should be evaluated - auto, none, normal, invert (Default: auto)
  40. propagate_positions - Propagates [line, column, end_line, end_column] attributes into all tree branches.
  41. lexer_callbacks - Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
  42. maybe_placeholders - Experimental feature. Instead of omitting optional rules (i.e. rule?), replace them with None
  43. """
  44. if __doc__:
  45. __doc__ += OPTIONS_DOC
  46. _defaults = {
  47. 'debug': False,
  48. 'keep_all_tokens': False,
  49. 'tree_class': None,
  50. 'cache_grammar': False,
  51. 'postlex': None,
  52. 'parser': 'earley',
  53. 'lexer': 'auto',
  54. 'transformer': None,
  55. 'start': 'start',
  56. 'profile': False,
  57. 'priority': 'auto',
  58. 'ambiguity': 'auto',
  59. 'propagate_positions': False,
  60. 'lexer_callbacks': {},
  61. 'maybe_placeholders': False,
  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'], str):
  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. return self.options[name]
  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 Profiler:
  94. def __init__(self):
  95. self.total_time = defaultdict(float)
  96. self.cur_section = '__init__'
  97. self.last_enter_time = time.time()
  98. def enter_section(self, name):
  99. cur_time = time.time()
  100. self.total_time[self.cur_section] += cur_time - self.last_enter_time
  101. self.last_enter_time = cur_time
  102. self.cur_section = name
  103. def make_wrapper(self, name, f):
  104. def wrapper(*args, **kwargs):
  105. last_section = self.cur_section
  106. self.enter_section(name)
  107. try:
  108. return f(*args, **kwargs)
  109. finally:
  110. self.enter_section(last_section)
  111. return wrapper
  112. class Lark(Serialize):
  113. def __init__(self, grammar, **options):
  114. """
  115. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  116. options : a dictionary controlling various aspects of Lark.
  117. """
  118. self.options = LarkOptions(options)
  119. # Some, but not all file-like objects have a 'name' attribute
  120. try:
  121. self.source = grammar.name
  122. except AttributeError:
  123. self.source = '<string>'
  124. # Drain file-like objects to get their contents
  125. try:
  126. read = grammar.read
  127. except AttributeError:
  128. pass
  129. else:
  130. grammar = read()
  131. assert isinstance(grammar, STRING_TYPE)
  132. if self.options.cache_grammar:
  133. raise NotImplementedError("Not available yet")
  134. assert not self.options.profile, "Feature temporarily disabled"
  135. # self.profiler = Profiler() if self.options.profile else None
  136. if self.options.lexer == 'auto':
  137. if self.options.parser == 'lalr':
  138. self.options.lexer = 'contextual'
  139. elif self.options.parser == 'earley':
  140. self.options.lexer = 'dynamic'
  141. elif self.options.parser == 'cyk':
  142. self.options.lexer = 'standard'
  143. else:
  144. assert False, self.options.parser
  145. lexer = self.options.lexer
  146. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  147. if self.options.ambiguity == 'auto':
  148. if self.options.parser == 'earley':
  149. self.options.ambiguity = 'resolve'
  150. else:
  151. disambig_parsers = ['earley', 'cyk']
  152. assert self.options.parser in disambig_parsers, (
  153. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  154. if self.options.priority == 'auto':
  155. if self.options.parser in ('earley', 'cyk', ):
  156. self.options.priority = 'normal'
  157. elif self.options.parser in ('lalr', ):
  158. self.options.priority = None
  159. elif self.options.priority in ('invert', 'normal'):
  160. assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time"
  161. assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority)
  162. assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"'
  163. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', )
  164. # Parse the grammar file and compose the grammars (TODO)
  165. self.grammar = load_grammar(grammar, self.source)
  166. # Compile the EBNF grammar into BNF
  167. self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start)
  168. self._terminals_dict = {t.name:t for t in self.terminals}
  169. # If the user asked to invert the priorities, negate them all here.
  170. # This replaces the old 'resolve__antiscore_sum' option.
  171. if self.options.priority == 'invert':
  172. for rule in self.rules:
  173. if rule.options and rule.options.priority is not None:
  174. rule.options.priority = -rule.options.priority
  175. # Else, if the user asked to disable priorities, strip them from the
  176. # rules. This allows the Earley parsers to skip an extra forest walk
  177. # for improved performance, if you don't need them (or didn't specify any).
  178. elif self.options.priority == None:
  179. for rule in self.rules:
  180. if rule.options and rule.options.priority is not None:
  181. rule.options.priority = None
  182. self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, self.options.lexer_callbacks)
  183. if self.options.parser:
  184. self.parser = self._build_parser()
  185. elif lexer:
  186. self.lexer = self._build_lexer()
  187. if __init__.__doc__:
  188. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  189. __serialize_fields__ = 'parser', 'rules', 'options'
  190. def _build_lexer(self):
  191. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks)
  192. def _prepare_callbacks(self):
  193. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  194. 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)
  195. self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
  196. def _build_parser(self):
  197. self._prepare_callbacks()
  198. parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
  199. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  200. @classmethod
  201. def deserialize(cls, data, namespace, memo, transformer=None, postlex=None):
  202. if memo:
  203. memo = SerializeMemoizer.deserialize(memo, namespace, {})
  204. inst = cls.__new__(cls)
  205. options = dict(data['options'])
  206. options['transformer'] = transformer
  207. options['postlex'] = postlex
  208. inst.options = LarkOptions.deserialize(options, memo)
  209. inst.rules = [Rule.deserialize(r, memo) for r in data['rules']]
  210. inst.source = '<deserialized>'
  211. inst._prepare_callbacks()
  212. inst.parser = inst.parser_class.deserialize(data['parser'], memo, inst._callbacks, inst.options.postlex)
  213. return inst
  214. @classmethod
  215. def open(cls, grammar_filename, rel_to=None, **options):
  216. """Create an instance of Lark with the grammar given by its filename
  217. If rel_to is provided, the function will find the grammar filename in relation to it.
  218. Example:
  219. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  220. Lark(...)
  221. """
  222. if rel_to:
  223. basepath = os.path.dirname(rel_to)
  224. grammar_filename = os.path.join(basepath, grammar_filename)
  225. with open(grammar_filename, encoding='utf8') as f:
  226. return cls(f, **options)
  227. def __repr__(self):
  228. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  229. def lex(self, text):
  230. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  231. if not hasattr(self, 'lexer'):
  232. self.lexer = self._build_lexer()
  233. stream = self.lexer.lex(text)
  234. if self.options.postlex:
  235. return self.options.postlex.process(stream)
  236. return stream
  237. def get_terminal(self, name):
  238. "Get information about a terminal"
  239. return self._terminals_dict[name]
  240. def parse(self, text, start=None):
  241. """Parse the given text, according to the options provided.
  242. The 'start' parameter is required if Lark was given multiple possible start symbols (using the start option).
  243. Returns a tree, unless specified otherwise.
  244. """
  245. return self.parser.parse(text, start=start)
  246. ###}