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