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.

142 lines
4.5 KiB

  1. """This module builds a LALR(1) transition-table for lalr_parser.py
  2. For now, shift/reduce conflicts are automatically resolved as shifts.
  3. """
  4. # Author: Erez Shinan (2017)
  5. # Email : erezshin@gmail.com
  6. import logging
  7. from collections import defaultdict
  8. from ..utils import classify, classify_bool, bfs, fzset, Serialize, Enumerator
  9. from ..exceptions import GrammarError
  10. from .grammar_analysis import GrammarAnalyzer, Terminal
  11. from ..grammar import Rule
  12. ###{standalone
  13. class Action:
  14. def __init__(self, name):
  15. self.name = name
  16. def __str__(self):
  17. return self.name
  18. def __repr__(self):
  19. return str(self)
  20. Shift = Action('Shift')
  21. Reduce = Action('Reduce')
  22. class ParseTable:
  23. def __init__(self, states, start_state, end_state):
  24. self.states = states
  25. self.start_state = start_state
  26. self.end_state = end_state
  27. def serialize(self, memo):
  28. tokens = Enumerator()
  29. rules = Enumerator()
  30. states = {
  31. state: {tokens.get(token): ((1, arg.serialize(memo)) if action is Reduce else (0, arg))
  32. for token, (action, arg) in actions.items()}
  33. for state, actions in self.states.items()
  34. }
  35. return {
  36. 'tokens': tokens.reversed(),
  37. 'states': states,
  38. 'start_state': self.start_state,
  39. 'end_state': self.end_state,
  40. }
  41. @classmethod
  42. def deserialize(cls, data, memo):
  43. tokens = data['tokens']
  44. states = {
  45. state: {tokens[token]: ((Reduce, Rule.deserialize(arg, memo)) if action==1 else (Shift, arg))
  46. for token, (action, arg) in actions.items()}
  47. for state, actions in data['states'].items()
  48. }
  49. return cls(states, data['start_state'], data['end_state'])
  50. class IntParseTable(ParseTable):
  51. @classmethod
  52. def from_ParseTable(cls, parse_table):
  53. enum = list(parse_table.states)
  54. state_to_idx = {s:i for i,s in enumerate(enum)}
  55. int_states = {}
  56. for s, la in parse_table.states.items():
  57. la = {k:(v[0], state_to_idx[v[1]]) if v[0] is Shift else v
  58. for k,v in la.items()}
  59. int_states[ state_to_idx[s] ] = la
  60. start_state = state_to_idx[parse_table.start_state]
  61. end_state = state_to_idx[parse_table.end_state]
  62. return cls(int_states, start_state, end_state)
  63. ###}
  64. class LALR_Analyzer(GrammarAnalyzer):
  65. def compute_lookahead(self):
  66. self.end_states = []
  67. self.states = {}
  68. def step(state):
  69. lookahead = defaultdict(list)
  70. sat, unsat = classify_bool(state, lambda rp: rp.is_satisfied)
  71. for rp in sat:
  72. for term in self.FOLLOW.get(rp.rule.origin, ()):
  73. lookahead[term].append((Reduce, rp.rule))
  74. d = classify(unsat, lambda rp: rp.next)
  75. for sym, rps in d.items():
  76. rps = {rp.advance(sym) for rp in rps}
  77. for rp in set(rps):
  78. if not rp.is_satisfied and not rp.next.is_term:
  79. rps |= self.expand_rule(rp.next)
  80. new_state = fzset(rps)
  81. lookahead[sym].append((Shift, new_state))
  82. if sym == Terminal('$END'):
  83. self.end_states.append( new_state )
  84. yield new_state
  85. for k, v in lookahead.items():
  86. if len(v) > 1:
  87. if self.debug:
  88. logging.warn("Shift/reduce conflict for terminal %s: (resolving as shift)", k.name)
  89. for act, arg in v:
  90. logging.warn(' * %s: %s', act, arg)
  91. for x in v:
  92. # XXX resolving shift/reduce into shift, like PLY
  93. # Give a proper warning
  94. if x[0] is Shift:
  95. lookahead[k] = [x]
  96. for k, v in lookahead.items():
  97. if not len(v) == 1:
  98. raise GrammarError("Collision in %s: %s" %(k, ', '.join(['\n * %s: %s' % x for x in v])))
  99. self.states[state] = {k.name:v[0] for k, v in lookahead.items()}
  100. for _ in bfs([self.start_state], step):
  101. pass
  102. self.end_state ,= self.end_states
  103. self._parse_table = ParseTable(self.states, self.start_state, self.end_state)
  104. if self.debug:
  105. self.parse_table = self._parse_table
  106. else:
  107. self.parse_table = IntParseTable.from_ParseTable(self._parse_table)