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.

178 lines
5.5 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. self.tokens, rules, _extra = parser.grammar.compile(parser.options.start)
  61. self.rules_for_root = defaultdict(list)
  62. self.rules = list(self._build_recons_rules(rules))
  63. self.rules.reverse()
  64. # Choose the best rule from each group of {rule => [rule.alias]}, since we only really need one derivation.
  65. self.rules = _best_rules_from_group(self.rules)
  66. self.parser = parser
  67. self._parser_cache = {}
  68. def _build_recons_rules(self, rules):
  69. "Convert tree-parsing/construction rules to tree-matching rules"
  70. expand1s = {r.origin for r in rules if r.options.expand1}
  71. aliases = defaultdict(list)
  72. for r in rules:
  73. if r.alias:
  74. aliases[r.origin].append(r.alias)
  75. rule_names = {r.origin for r in rules}
  76. nonterminals = {sym for sym in rule_names
  77. if sym.name.startswith('_') or sym in expand1s or sym in aliases}
  78. seen = set()
  79. for r in rules:
  80. recons_exp = [sym if sym in nonterminals else Terminal(sym.name)
  81. for sym in r.expansion if not is_discarded_terminal(sym)]
  82. # Skip self-recursive constructs
  83. if recons_exp == [r.origin] and r.alias is None:
  84. continue
  85. sym = NonTerminal(r.alias) if r.alias else r.origin
  86. rule = make_recons_rule(sym, recons_exp, r.expansion)
  87. if sym in expand1s and len(recons_exp) != 1:
  88. self.rules_for_root[sym.name].append(rule)
  89. if sym.name not in seen:
  90. yield make_recons_rule_to_term(sym, sym)
  91. seen.add(sym.name)
  92. else:
  93. if sym.name.startswith('_') or sym in expand1s:
  94. yield rule
  95. else:
  96. self.rules_for_root[sym.name].append(rule)
  97. for origin, rule_aliases in aliases.items():
  98. for alias in rule_aliases:
  99. yield make_recons_rule_to_term(origin, NonTerminal(alias))
  100. yield make_recons_rule_to_term(origin, origin)
  101. def match_tree(self, tree, rulename):
  102. """Match the elements of `tree` to the symbols of rule `rulename`.
  103. Args:
  104. tree (Tree): the tree node to match
  105. rulename ([type]): [description]
  106. Returns:
  107. Tree: an unreduced tree that matches `rulename`
  108. Raises:
  109. UnexpectedToken: If no match was found.
  110. Note:
  111. It's the callers' responsibility match the tree recursively.
  112. """
  113. if rulename:
  114. # validate
  115. name, _args = parse_rulename(rulename)
  116. assert tree.data == name
  117. else:
  118. rulename = tree.data
  119. # TODO: ambiguity?
  120. try:
  121. parser = self._parser_cache[rulename]
  122. except KeyError:
  123. rules = self.rules + _best_rules_from_group(self.rules_for_root[rulename])
  124. # TODO pass callbacks through dict, instead of alias?
  125. callbacks = {rule: rule.alias for rule in rules}
  126. conf = ParserConf(rules, callbacks, [rulename])
  127. parser = earley.Parser(conf, _match, resolve_ambiguity=True)
  128. self._parser_cache[rulename] = parser
  129. # find a full derivation
  130. unreduced_tree = parser.parse(tree.children, rulename)
  131. assert unreduced_tree.data == rulename
  132. return unreduced_tree