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.

194 lines
6.4 KiB

  1. from collections import defaultdict
  2. from .tree import Tree
  3. from .visitors import Transformer_InPlace
  4. from .common import ParserConf
  5. from .lexer import Token, PatternStr
  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. def is_iter_empty(i):
  11. try:
  12. _ = next(i)
  13. return False
  14. except StopIteration:
  15. return True
  16. class WriteTokensTransformer(Transformer_InPlace):
  17. "Inserts discarded tokens into their correct place, according to the rules of grammar"
  18. def __init__(self, tokens, term_subs):
  19. self.tokens = tokens
  20. self.term_subs = term_subs
  21. def __default__(self, data, children, meta):
  22. if not getattr(meta, 'match_tree', False):
  23. return Tree(data, children)
  24. iter_args = iter(children)
  25. to_write = []
  26. for sym in meta.orig_expansion:
  27. if is_discarded_terminal(sym):
  28. try:
  29. v = self.term_subs[sym.name](sym)
  30. except KeyError:
  31. t = self.tokens[sym.name]
  32. if not isinstance(t.pattern, PatternStr):
  33. raise NotImplementedError("Reconstructing regexps not supported yet: %s" % t)
  34. v = t.pattern.value
  35. to_write.append(v)
  36. else:
  37. x = next(iter_args)
  38. if isinstance(x, list):
  39. to_write += x
  40. else:
  41. if isinstance(x, Token):
  42. assert Terminal(x.type) == sym, x
  43. else:
  44. assert NonTerminal(x.data) == sym, (sym, x)
  45. to_write.append(x)
  46. assert is_iter_empty(iter_args)
  47. return to_write
  48. class MatchTree(Tree):
  49. pass
  50. class MakeMatchTree:
  51. def __init__(self, name, expansion):
  52. self.name = name
  53. self.expansion = expansion
  54. def __call__(self, args):
  55. t = MatchTree(self.name, args)
  56. t.meta.match_tree = True
  57. t.meta.orig_expansion = self.expansion
  58. return t
  59. def best_from_group(seq, group_key, cmp_key):
  60. d = {}
  61. for item in seq:
  62. key = group_key(item)
  63. if key in d:
  64. v1 = cmp_key(item)
  65. v2 = cmp_key(d[key])
  66. if v2 > v1:
  67. d[key] = item
  68. else:
  69. d[key] = item
  70. return list(d.values())
  71. def make_recons_rule(origin, expansion, old_expansion):
  72. return Rule(origin, expansion, alias=MakeMatchTree(origin.name, old_expansion))
  73. def make_recons_rule_to_term(origin, term):
  74. return make_recons_rule(origin, [Terminal(term.name)], [term])
  75. class Reconstructor:
  76. def __init__(self, parser, term_subs={}):
  77. # XXX TODO calling compile twice returns different results!
  78. assert parser.options.maybe_placeholders == False
  79. tokens, rules, _grammar_extra = parser.grammar.compile(parser.options.start)
  80. self.write_tokens = WriteTokensTransformer({t.name:t for t in tokens}, term_subs)
  81. self.rules_for_root = defaultdict(list)
  82. self.rules = list(self._build_recons_rules(rules))
  83. self.rules.reverse()
  84. # Choose the best rule from each group of {rule => [rule.alias]}, since we only really need one derivation.
  85. self.rules = best_from_group(self.rules, lambda r: r, lambda r: -len(r.expansion))
  86. self.rules.sort(key=lambda r: len(r.expansion))
  87. self.parser = parser
  88. self._parser_cache = {}
  89. def _build_recons_rules(self, rules):
  90. expand1s = {r.origin for r in rules if r.options.expand1}
  91. aliases = defaultdict(list)
  92. for r in rules:
  93. if r.alias:
  94. aliases[r.origin].append( r.alias )
  95. rule_names = {r.origin for r in rules}
  96. nonterminals = {sym for sym in rule_names
  97. if sym.name.startswith('_') or sym in expand1s or sym in aliases }
  98. seen = set()
  99. for r in rules:
  100. recons_exp = [sym if sym in nonterminals else Terminal(sym.name)
  101. for sym in r.expansion if not is_discarded_terminal(sym)]
  102. # Skip self-recursive constructs
  103. if recons_exp == [r.origin] and r.alias is None:
  104. continue
  105. sym = NonTerminal(r.alias) if r.alias else r.origin
  106. rule = make_recons_rule(sym, recons_exp, r.expansion)
  107. if sym in expand1s and len(recons_exp) != 1:
  108. self.rules_for_root[sym.name].append(rule)
  109. if sym.name not in seen:
  110. yield make_recons_rule_to_term(sym, sym)
  111. seen.add(sym.name)
  112. else:
  113. if sym.name.startswith('_') or sym in expand1s:
  114. yield rule
  115. else:
  116. self.rules_for_root[sym.name].append(rule)
  117. for origin, rule_aliases in aliases.items():
  118. for alias in rule_aliases:
  119. yield make_recons_rule_to_term(origin, NonTerminal(alias))
  120. yield make_recons_rule_to_term(origin, origin)
  121. def _match(self, term, token):
  122. if isinstance(token, Tree):
  123. return Terminal(token.data) == term
  124. elif isinstance(token, Token):
  125. return term == Terminal(token.type)
  126. assert False
  127. def _reconstruct(self, tree):
  128. # TODO: ambiguity?
  129. try:
  130. parser = self._parser_cache[tree.data]
  131. except KeyError:
  132. rules = self.rules + self.rules_for_root[tree.data]
  133. callbacks = {rule: rule.alias for rule in rules} # TODO pass callbacks through dict, instead of alias?
  134. parser = earley.Parser(ParserConf(rules, callbacks, [tree.data]), self._match, resolve_ambiguity=True)
  135. self._parser_cache[tree.data] = parser
  136. unreduced_tree = parser.parse(tree.children, tree.data) # find a full derivation
  137. assert unreduced_tree.data == tree.data
  138. res = self.write_tokens.transform(unreduced_tree)
  139. for item in res:
  140. if isinstance(item, Tree):
  141. for x in self._reconstruct(item):
  142. yield x
  143. else:
  144. yield item
  145. def reconstruct(self, tree):
  146. x = self._reconstruct(tree)
  147. y = []
  148. prev_item = ''
  149. for item in x:
  150. if prev_item and item and prev_item[-1].isalnum() and item[0].isalnum():
  151. y.append(' ')
  152. y.append(item)
  153. prev_item = item
  154. return ''.join(y)