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.

236 lines
9.4 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
  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. class LarkOptions(object):
  14. """Specifies the options for Lark
  15. """
  16. OPTIONS_DOC = """
  17. parser - Decides which parser engine to use, "earley" or "lalr". (Default: "earley")
  18. Note: "lalr" requires a lexer
  19. lexer - Decides whether or not to use a lexer stage
  20. "standard": Use a standard lexer
  21. "contextual": Stronger lexer (only works with parser="lalr")
  22. "dynamic": Flexible and powerful (only with parser="earley")
  23. "dynamic_complete": Same as dynamic, but tries *every* variation
  24. of tokenizing possible. (only with parser="earley")
  25. "auto" (default): Choose for me based on grammar and parser
  26. ambiguity - Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
  27. "resolve": The parser will automatically choose the simplest derivation
  28. (it chooses consistently: greedy for tokens, non-greedy for rules)
  29. "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
  30. transformer - Applies the transformer to every parse tree
  31. debug - Affects verbosity (default: False)
  32. keep_all_tokens - Don't automagically remove "punctuation" tokens (default: False)
  33. cache_grammar - Cache the Lark grammar (Default: False)
  34. postlex - Lexer post-processing (Requires standard lexer. Default: None)
  35. start - The start symbol (Default: start)
  36. profile - Measure run-time usage in Lark. Read results from the profiler proprety (Default: False)
  37. propagate_positions - Propagates [line, column, end_line, end_column] attributes into all tree branches.
  38. lexer_callbacks - Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
  39. """
  40. __doc__ += OPTIONS_DOC
  41. def __init__(self, options_dict):
  42. o = dict(options_dict)
  43. self.debug = bool(o.pop('debug', False))
  44. self.keep_all_tokens = bool(o.pop('keep_all_tokens', False))
  45. self.tree_class = o.pop('tree_class', Tree)
  46. self.cache_grammar = o.pop('cache_grammar', False)
  47. self.postlex = o.pop('postlex', None)
  48. self.parser = o.pop('parser', 'earley')
  49. self.lexer = o.pop('lexer', 'auto')
  50. self.transformer = o.pop('transformer', None)
  51. self.start = o.pop('start', 'start')
  52. self.profile = o.pop('profile', False)
  53. self.ambiguity = o.pop('ambiguity', 'auto')
  54. self.propagate_positions = o.pop('propagate_positions', False)
  55. self.earley__predict_all = o.pop('earley__predict_all', False)
  56. self.lexer_callbacks = o.pop('lexer_callbacks', {})
  57. assert self.parser in ('earley', 'lalr', 'cyk', None)
  58. if self.parser == 'earley' and self.transformer:
  59. raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.'
  60. 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. lalr)')
  61. if o:
  62. raise ValueError("Unknown options: %s" % o.keys())
  63. class Profiler:
  64. def __init__(self):
  65. self.total_time = defaultdict(float)
  66. self.cur_section = '__init__'
  67. self.last_enter_time = time.time()
  68. def enter_section(self, name):
  69. cur_time = time.time()
  70. self.total_time[self.cur_section] += cur_time - self.last_enter_time
  71. self.last_enter_time = cur_time
  72. self.cur_section = name
  73. def make_wrapper(self, name, f):
  74. def wrapper(*args, **kwargs):
  75. last_section = self.cur_section
  76. self.enter_section(name)
  77. try:
  78. return f(*args, **kwargs)
  79. finally:
  80. self.enter_section(last_section)
  81. return wrapper
  82. class Lark:
  83. def __init__(self, grammar, **options):
  84. """
  85. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  86. options : a dictionary controlling various aspects of Lark.
  87. """
  88. self.options = LarkOptions(options)
  89. # Some, but not all file-like objects have a 'name' attribute
  90. try:
  91. self.source = grammar.name
  92. except AttributeError:
  93. self.source = '<string>'
  94. cache_file = "larkcache_%s" % str(hash(grammar)%(2**32))
  95. else:
  96. cache_file = "larkcache_%s" % os.path.basename(self.source)
  97. # Drain file-like objects to get their contents
  98. try:
  99. read = grammar.read
  100. except AttributeError:
  101. pass
  102. else:
  103. grammar = read()
  104. assert isinstance(grammar, STRING_TYPE)
  105. if self.options.cache_grammar:
  106. raise NotImplementedError("Not available yet")
  107. assert not self.options.profile, "Feature temporarily disabled"
  108. self.profiler = Profiler() if self.options.profile else None
  109. if self.options.lexer == 'auto':
  110. if self.options.parser == 'lalr':
  111. self.options.lexer = 'contextual'
  112. elif self.options.parser == 'earley':
  113. self.options.lexer = 'dynamic'
  114. elif self.options.parser == 'cyk':
  115. self.options.lexer = 'standard'
  116. else:
  117. assert False, self.options.parser
  118. lexer = self.options.lexer
  119. assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer)
  120. if self.options.ambiguity == 'auto':
  121. if self.options.parser == 'earley':
  122. self.options.ambiguity = 'resolve'
  123. else:
  124. disambig_parsers = ['earley', 'cyk']
  125. assert self.options.parser in disambig_parsers, (
  126. 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers)
  127. assert self.options.ambiguity in ('resolve', 'explicit', 'auto', 'resolve__antiscore_sum')
  128. # Parse the grammar file and compose the grammars (TODO)
  129. self.grammar = load_grammar(grammar, self.source)
  130. # Compile the EBNF grammar into BNF
  131. tokens, self.rules, self.ignore_tokens = self.grammar.compile()
  132. self.lexer_conf = LexerConf(tokens, self.ignore_tokens, self.options.postlex, self.options.lexer_callbacks)
  133. if self.options.parser:
  134. self.parser = self._build_parser()
  135. elif lexer:
  136. self.lexer = self._build_lexer()
  137. if self.profiler: self.profiler.enter_section('outside_lark')
  138. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  139. def _build_lexer(self):
  140. return TraditionalLexer(self.lexer_conf.tokens, ignore=self.lexer_conf.ignore, user_callbacks=self.lexer_conf.callbacks)
  141. def _build_parser(self):
  142. self.parser_class = get_frontend(self.options.parser, self.options.lexer)
  143. self._parse_tree_builder = ParseTreeBuilder(self.rules, self.options.tree_class, self.options.propagate_positions, self.options.keep_all_tokens, self.options.parser!='lalr')
  144. callback = self._parse_tree_builder.create_callback(self.options.transformer)
  145. if self.profiler:
  146. for f in dir(callback):
  147. if not (f.startswith('__') and f.endswith('__')):
  148. setattr(callback, f, self.profiler.make_wrapper('transformer', getattr(callback, f)))
  149. parser_conf = ParserConf(self.rules, callback, self.options.start)
  150. return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  151. @classmethod
  152. def open(cls, grammar_filename, rel_to=None, **options):
  153. """Create an instance of Lark with the grammar given by its filename
  154. If rel_to is provided, the function will find the grammar filename in relation to it.
  155. Example:
  156. >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
  157. Lark(...)
  158. """
  159. if rel_to:
  160. basepath = os.path.dirname(rel_to)
  161. grammar_filename = os.path.join(basepath, grammar_filename)
  162. with open(grammar_filename, encoding='utf8') as f:
  163. return cls(f, **options)
  164. def __repr__(self):
  165. return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer)
  166. def lex(self, text):
  167. "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'"
  168. if not hasattr(self, 'lexer'):
  169. self.lexer = self._build_lexer()
  170. stream = self.lexer.lex(text)
  171. if self.options.postlex:
  172. return self.options.postlex.process(stream)
  173. return stream
  174. def parse(self, text):
  175. "Parse the given text, according to the options provided. Returns a tree, unless specified otherwise."
  176. return self.parser.parse(text)
  177. # if self.profiler:
  178. # self.profiler.enter_section('lex')
  179. # l = list(self.lex(text))
  180. # self.profiler.enter_section('parse')
  181. # try:
  182. # return self.parser.parse(l)
  183. # finally:
  184. # self.profiler.enter_section('outside_lark')
  185. # else:
  186. # l = list(self.lex(text))
  187. # return self.parser.parse(l)