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