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.
 
 

220 lines
7.3 KiB

  1. from __future__ import absolute_import
  2. import functools
  3. import types
  4. from .utils import STRING_TYPE, inline_args
  5. from .load_grammar import load_grammar
  6. from .tree import Tree, Transformer
  7. from .lexer import Lexer
  8. from .grammar_analysis import GrammarAnalyzer, is_terminal
  9. from . import parser, earley
  10. class LarkOptions(object):
  11. """Specifies the options for Lark
  12. """
  13. OPTIONS_DOC = """
  14. parser - Which parser engine to use ("earley" or "lalr". Default: "earley")
  15. Note: Both will use Lark's lexer.
  16. transformer - Applies the transformer to every parse tree
  17. debug - Affects verbosity (default: False)
  18. only_lex - Don't build a parser. Useful for debugging (default: False)
  19. keep_all_tokens - Don't automagically remove "punctuation" tokens (default: True)
  20. cache_grammar - Cache the Lark grammar (Default: False)
  21. postlex - Lexer post-processing (Default: None)
  22. """
  23. __doc__ += OPTIONS_DOC
  24. def __init__(self, options_dict):
  25. o = dict(options_dict)
  26. self.debug = bool(o.pop('debug', False))
  27. self.only_lex = bool(o.pop('only_lex', False))
  28. self.keep_all_tokens = bool(o.pop('keep_all_tokens', False))
  29. self.tree_class = o.pop('tree_class', Tree)
  30. self.cache_grammar = o.pop('cache_grammar', False)
  31. self.postlex = o.pop('postlex', None)
  32. self.parser = o.pop('parser', 'earley')
  33. self.transformer = o.pop('transformer', None)
  34. assert self.parser in ENGINE_DICT
  35. if self.parser == 'earley' and self.transformer:
  36. raise ValueError('Cannot specify an auto-transformer when using the Earley algorithm. Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. lalr)')
  37. if self.keep_all_tokens:
  38. raise NotImplementedError("Not implemented yet!")
  39. if o:
  40. raise ValueError("Unknown options: %s" % o.keys())
  41. class Callback(object):
  42. pass
  43. class RuleTreeToText(Transformer):
  44. def expansions(self, x):
  45. return x
  46. def expansion(self, symbols):
  47. return [sym.value for sym in symbols], None
  48. def alias(self, ((expansion, _alias), alias)):
  49. assert _alias is None, (alias, expansion, '-', _alias)
  50. return expansion, alias.value
  51. def create_rule_handler(expansion, usermethod):
  52. to_include = [(i, sym.startswith('_')) for i, sym in enumerate(expansion)
  53. if not (is_terminal(sym) and sym.startswith('_'))]
  54. def _build_ast(match):
  55. children = []
  56. for i, to_expand in to_include:
  57. if to_expand:
  58. children += match[i].children
  59. else:
  60. children.append(match[i])
  61. return usermethod(children)
  62. return _build_ast
  63. def create_expand1_tree_builder_function(tree_builder):
  64. def f(children):
  65. if len(children) == 1:
  66. return children[0]
  67. else:
  68. return tree_builder(children)
  69. return f
  70. class LALR:
  71. def build_parser(self, rules, callback):
  72. ga = GrammarAnalyzer(rules)
  73. ga.analyze()
  74. return parser.Parser(ga, callback)
  75. class Earley:
  76. @staticmethod
  77. def _process_expansion(x):
  78. return [{'literal': s} if is_terminal(s) else s for s in x]
  79. def build_parser(self, rules, callback):
  80. rules = [{'name':n, 'symbols': self._process_expansion(x), 'postprocess':getattr(callback, a)} for n,x,a in rules]
  81. return EarleyParser(earley.Parser(rules, 'start'))
  82. class EarleyParser:
  83. def __init__(self, parser):
  84. self.parser = parser
  85. def parse(self, text):
  86. res = self.parser.parse(text)
  87. assert len(res) ==1 , 'Ambiguious Parse! Not handled yet'
  88. return res[0]
  89. ENGINE_DICT = { 'lalr': LALR, 'earley': Earley }
  90. class Lark:
  91. def __init__(self, grammar, **options):
  92. """
  93. grammar : a string or file-object containing the grammar spec (using Lark's ebnf syntax)
  94. options : a dictionary controlling various aspects of Lark.
  95. """
  96. self.options = LarkOptions(options)
  97. # Some, but not all file-like objects have a 'name' attribute
  98. try:
  99. source = grammar.name
  100. except AttributeError:
  101. source = '<string>'
  102. cache_file = "larkcache_%s" % str(hash(grammar)%(2**32))
  103. else:
  104. cache_file = "larkcache_%s" % os.path.basename(source)
  105. # Drain file-like objects to get their contents
  106. try:
  107. read = grammar.read
  108. except AttributeError:
  109. pass
  110. else:
  111. grammar = read()
  112. assert isinstance(grammar, STRING_TYPE)
  113. if self.options.cache_grammar:
  114. raise NotImplementedError("Not available yet")
  115. self.tokens, self.rules = load_grammar(grammar)
  116. self.lexer = self._build_lexer()
  117. if not self.options.only_lex:
  118. self.parser_engine = ENGINE_DICT[self.options.parser]()
  119. self.parser = self._build_parser()
  120. def _build_lexer(self):
  121. ignore_tokens = []
  122. tokens = []
  123. for name, (value, flags) in self.tokens:
  124. if 'ignore' in flags:
  125. ignore_tokens.append(name)
  126. tokens.append((name, value))
  127. return Lexer(tokens, {}, ignore=ignore_tokens)
  128. def _build_parser(self):
  129. transformer = self.options.transformer
  130. callback = Callback()
  131. rules = []
  132. rule_tree_to_text = RuleTreeToText()
  133. for origin, tree in self.rules.items():
  134. for expansion, alias in rule_tree_to_text.transform(tree):
  135. if alias and origin.startswith('_'):
  136. raise Exception("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases" % origin)
  137. expand1 = origin.startswith('?')
  138. _origin = origin.lstrip('?*')
  139. if alias:
  140. alias = alias.lstrip('*')
  141. _alias = 'autoalias_%s_%s' % (_origin, '_'.join(expansion))
  142. try:
  143. f = transformer._get_func(alias or _origin)
  144. # f = getattr(transformer, alias or _origin)
  145. except AttributeError:
  146. if alias:
  147. f = self._create_tree_builder_function(alias)
  148. else:
  149. f = self._create_tree_builder_function(_origin)
  150. if expand1:
  151. f = create_expand1_tree_builder_function(f)
  152. alias_handler = create_rule_handler(expansion, f)
  153. assert not hasattr(callback, _alias)
  154. setattr(callback, _alias, alias_handler)
  155. rules.append((_origin, expansion, _alias))
  156. return self.parser_engine.build_parser(rules, callback)
  157. __init__.__doc__ += "\nOPTIONS:" + LarkOptions.OPTIONS_DOC
  158. def _create_tree_builder_function(self, name):
  159. tree_class = self.options.tree_class
  160. def f(children):
  161. return tree_class(name, children)
  162. return f
  163. def lex(self, text):
  164. stream = self.lexer.lex(text)
  165. if self.options.postlex:
  166. return self.options.postlex.process(stream)
  167. else:
  168. return stream
  169. def parse(self, text):
  170. assert not self.options.only_lex
  171. l = list(self.lex(text))
  172. return self.parser.parse(l)