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.

179 lines
5.7 KiB

  1. """Tree matcher based on Lark grammar"""
  2. import re
  3. from collections import defaultdict
  4. from . import Tree, Token
  5. from .common import ParserConf
  6. from .parsers import earley
  7. from .grammar import Rule, Terminal, NonTerminal
  8. def is_discarded_terminal(t):
  9. return t.is_term and t.filter_out
  10. class _MakeTreeMatch:
  11. def __init__(self, name, expansion):
  12. self.name = name
  13. self.expansion = expansion
  14. def __call__(self, args):
  15. t = Tree(self.name, args)
  16. t.meta.match_tree = True
  17. t.meta.orig_expansion = self.expansion
  18. return t
  19. def _best_from_group(seq, group_key, cmp_key):
  20. d = {}
  21. for item in seq:
  22. key = group_key(item)
  23. if key in d:
  24. v1 = cmp_key(item)
  25. v2 = cmp_key(d[key])
  26. if v2 > v1:
  27. d[key] = item
  28. else:
  29. d[key] = item
  30. return list(d.values())
  31. def _best_rules_from_group(rules):
  32. rules = _best_from_group(rules, lambda r: r, lambda r: -len(r.expansion))
  33. rules.sort(key=lambda r: len(r.expansion))
  34. return rules
  35. def _match(term, token):
  36. if isinstance(token, Tree):
  37. name, _args = parse_rulename(term.name)
  38. return token.data == name
  39. elif isinstance(token, Token):
  40. return term == Terminal(token.type)
  41. assert False
  42. def make_recons_rule(origin, expansion, old_expansion):
  43. return Rule(origin, expansion, alias=_MakeTreeMatch(origin.name, old_expansion))
  44. def make_recons_rule_to_term(origin, term):
  45. return make_recons_rule(origin, [Terminal(term.name)], [term])
  46. def parse_rulename(s):
  47. "Parse rule names that may contain a template syntax (like rule{a, b, ...})"
  48. name, args_str = re.match(r'(\w+)(?:{(.+)})?', s).groups()
  49. args = args_str and [a.strip() for a in args_str.split(',')]
  50. return name, args
  51. class TreeMatcher:
  52. """Match the elements of a tree node, based on an ontology
  53. provided by a Lark grammar.
  54. Supports templates and inlined rules (`rule{a, b,..}` and `_rule`)
  55. Initiialize with an instance of Lark.
  56. """
  57. def __init__(self, parser):
  58. # XXX TODO calling compile twice returns different results!
  59. assert parser.options.maybe_placeholders == False
  60. # XXX TODO: we just ignore the potential existence of a postlexer
  61. self.tokens, rules, _extra = parser.grammar.compile(parser.options.start, set())
  62. self.rules_for_root = defaultdict(list)
  63. self.rules = list(self._build_recons_rules(rules))
  64. self.rules.reverse()
  65. # Choose the best rule from each group of {rule => [rule.alias]}, since we only really need one derivation.
  66. self.rules = _best_rules_from_group(self.rules)
  67. self.parser = parser
  68. self._parser_cache = {}
  69. def _build_recons_rules(self, rules):
  70. "Convert tree-parsing/construction rules to tree-matching rules"
  71. expand1s = {r.origin for r in rules if r.options.expand1}
  72. aliases = defaultdict(list)
  73. for r in rules:
  74. if r.alias:
  75. aliases[r.origin].append(r.alias)
  76. rule_names = {r.origin for r in rules}
  77. nonterminals = {sym for sym in rule_names
  78. if sym.name.startswith('_') or sym in expand1s or sym in aliases}
  79. seen = set()
  80. for r in rules:
  81. recons_exp = [sym if sym in nonterminals else Terminal(sym.name)
  82. for sym in r.expansion if not is_discarded_terminal(sym)]
  83. # Skip self-recursive constructs
  84. if recons_exp == [r.origin] and r.alias is None:
  85. continue
  86. sym = NonTerminal(r.alias) if r.alias else r.origin
  87. rule = make_recons_rule(sym, recons_exp, r.expansion)
  88. if sym in expand1s and len(recons_exp) != 1:
  89. self.rules_for_root[sym.name].append(rule)
  90. if sym.name not in seen:
  91. yield make_recons_rule_to_term(sym, sym)
  92. seen.add(sym.name)
  93. else:
  94. if sym.name.startswith('_') or sym in expand1s:
  95. yield rule
  96. else:
  97. self.rules_for_root[sym.name].append(rule)
  98. for origin, rule_aliases in aliases.items():
  99. for alias in rule_aliases:
  100. yield make_recons_rule_to_term(origin, NonTerminal(alias))
  101. yield make_recons_rule_to_term(origin, origin)
  102. def match_tree(self, tree, rulename):
  103. """Match the elements of `tree` to the symbols of rule `rulename`.
  104. Parameters:
  105. tree (Tree): the tree node to match
  106. rulename (str): The expected full rule name (including template args)
  107. Returns:
  108. Tree: an unreduced tree that matches `rulename`
  109. Raises:
  110. UnexpectedToken: If no match was found.
  111. Note:
  112. It's the callers' responsibility match the tree recursively.
  113. """
  114. if rulename:
  115. # validate
  116. name, _args = parse_rulename(rulename)
  117. assert tree.data == name
  118. else:
  119. rulename = tree.data
  120. # TODO: ambiguity?
  121. try:
  122. parser = self._parser_cache[rulename]
  123. except KeyError:
  124. rules = self.rules + _best_rules_from_group(self.rules_for_root[rulename])
  125. # TODO pass callbacks through dict, instead of alias?
  126. callbacks = {rule: rule.alias for rule in rules}
  127. conf = ParserConf(rules, callbacks, [rulename])
  128. parser = earley.Parser(conf, _match, resolve_ambiguity=True)
  129. self._parser_cache[rulename] = parser
  130. # find a full derivation
  131. unreduced_tree = parser.parse(tree.children, rulename)
  132. assert unreduced_tree.data == rulename
  133. return unreduced_tree