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.

165 lines
5.5 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. class Reconstructor:
  72. def __init__(self, parser, term_subs={}):
  73. # XXX TODO calling compile twice returns different results!
  74. assert parser.options.maybe_placeholders == False
  75. tokens, rules, _grammar_extra = parser.grammar.compile(parser.options.start)
  76. self.write_tokens = WriteTokensTransformer({t.name:t for t in tokens}, term_subs)
  77. self.rules = list(self._build_recons_rules(rules))
  78. self.rules.reverse()
  79. # Choose the best rule from each group of {rule => [rule.alias]}, since we only really need one derivation.
  80. self.rules = best_from_group(self.rules, lambda r: r, lambda r: -len(r.expansion))
  81. self.rules.sort(key=lambda r: len(r.expansion))
  82. callbacks = {rule: rule.alias for rule in self.rules} # TODO pass callbacks through dict, instead of alias?
  83. self.parser = earley.Parser(ParserConf(self.rules, callbacks, parser.options.start),
  84. self._match, resolve_ambiguity=True)
  85. def _build_recons_rules(self, rules):
  86. expand1s = {r.origin for r in rules if r.options.expand1}
  87. aliases = defaultdict(list)
  88. for r in rules:
  89. if r.alias:
  90. aliases[r.origin].append( r.alias )
  91. rule_names = {r.origin for r in rules}
  92. nonterminals = {sym for sym in rule_names
  93. if sym.name.startswith('_') or sym in expand1s or sym in aliases }
  94. for r in rules:
  95. recons_exp = [sym if sym in nonterminals else Terminal(sym.name)
  96. for sym in r.expansion if not is_discarded_terminal(sym)]
  97. # Skip self-recursive constructs
  98. if recons_exp == [r.origin]:
  99. continue
  100. sym = NonTerminal(r.alias) if r.alias else r.origin
  101. yield Rule(sym, recons_exp, alias=MakeMatchTree(sym.name, r.expansion))
  102. for origin, rule_aliases in aliases.items():
  103. for alias in rule_aliases:
  104. yield Rule(origin, [Terminal(alias)], alias=MakeMatchTree(origin.name, [NonTerminal(alias)]))
  105. yield Rule(origin, [Terminal(origin.name)], alias=MakeMatchTree(origin.name, [origin]))
  106. def _match(self, term, token):
  107. if isinstance(token, Tree):
  108. return Terminal(token.data) == term
  109. elif isinstance(token, Token):
  110. return term == Terminal(token.type)
  111. assert False
  112. def _reconstruct(self, tree):
  113. # TODO: ambiguity?
  114. unreduced_tree = self.parser.parse(tree.children, tree.data) # find a full derivation
  115. assert unreduced_tree.data == tree.data
  116. res = self.write_tokens.transform(unreduced_tree)
  117. for item in res:
  118. if isinstance(item, Tree):
  119. for x in self._reconstruct(item):
  120. yield x
  121. else:
  122. yield item
  123. def reconstruct(self, tree):
  124. x = self._reconstruct(tree)
  125. y = []
  126. prev_item = ''
  127. for item in x:
  128. if prev_item and item and prev_item[-1].isalnum() and item[0].isalnum():
  129. y.append(' ')
  130. y.append(item)
  131. prev_item = item
  132. return ''.join(y)