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.

131 lines
4.2 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, resolve_ambig
  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. def __init__(self, tokens):
  18. self.tokens = tokens
  19. def __default__(self, data, children, meta):
  20. # if not isinstance(t, MatchTree):
  21. # return t
  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. t = self.tokens[sym.name]
  29. assert isinstance(t.pattern, PatternStr)
  30. to_write.append(t.pattern.value)
  31. else:
  32. x = next(iter_args)
  33. if isinstance(x, list):
  34. to_write += x
  35. else:
  36. if isinstance(x, Token):
  37. assert Terminal(x.type) == sym, x
  38. else:
  39. assert NonTerminal(x.data) == sym, (sym, x)
  40. to_write.append(x)
  41. assert is_iter_empty(iter_args)
  42. return to_write
  43. class MatchTree(Tree):
  44. pass
  45. class MakeMatchTree:
  46. def __init__(self, name, expansion):
  47. self.name = name
  48. self.expansion = expansion
  49. def __call__(self, args):
  50. t = MatchTree(self.name, args)
  51. t.meta.match_tree = True
  52. t.meta.orig_expansion = self.expansion
  53. return t
  54. class Reconstructor:
  55. def __init__(self, parser):
  56. # XXX TODO calling compile twice returns different results!
  57. tokens, rules, _grammar_extra = parser.grammar.compile()
  58. self.write_tokens = WriteTokensTransformer({t.name:t for t in tokens})
  59. self.rules = list(self._build_recons_rules(rules))
  60. def _build_recons_rules(self, rules):
  61. expand1s = {r.origin for r in rules if r.options and r.options.expand1}
  62. aliases = defaultdict(list)
  63. for r in rules:
  64. if r.alias:
  65. aliases[r.origin].append( r.alias )
  66. rule_names = {r.origin for r in rules}
  67. nonterminals = {sym for sym in rule_names
  68. if sym.name.startswith('_') or sym in expand1s or sym in aliases }
  69. for r in rules:
  70. recons_exp = [sym if sym in nonterminals else Terminal(sym.name)
  71. for sym in r.expansion if not is_discarded_terminal(sym)]
  72. # Skip self-recursive constructs
  73. if recons_exp == [r.origin]:
  74. continue
  75. sym = NonTerminal(r.alias) if r.alias else r.origin
  76. yield Rule(sym, recons_exp, MakeMatchTree(sym.name, r.expansion))
  77. for origin, rule_aliases in aliases.items():
  78. for alias in rule_aliases:
  79. yield Rule(origin, [Terminal(alias)], MakeMatchTree(origin.name, [NonTerminal(alias)]))
  80. yield Rule(origin, [Terminal(origin.name)], MakeMatchTree(origin.name, [origin]))
  81. def _match(self, term, token):
  82. if isinstance(token, Tree):
  83. return Terminal(token.data) == term
  84. elif isinstance(token, Token):
  85. return term == Terminal(token.type)
  86. assert False
  87. def _reconstruct(self, tree):
  88. # TODO: ambiguity?
  89. parser = earley.Parser(ParserConf(self.rules, None, tree.data), self._match, resolve_ambiguity=resolve_ambig.standard_resolve_ambig)
  90. unreduced_tree = parser.parse(tree.children) # find a full derivation
  91. assert unreduced_tree.data == tree.data
  92. res = self.write_tokens.transform(unreduced_tree)
  93. for item in res:
  94. if isinstance(item, Tree):
  95. for x in self._reconstruct(item):
  96. yield x
  97. else:
  98. yield item
  99. def reconstruct(self, tree):
  100. return ''.join(self._reconstruct(tree))