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.

122 lines
3.8 KiB

  1. """This module implements a LALR(1) Parser
  2. """
  3. # Author: Erez Shinan (2017)
  4. # Email : erezshin@gmail.com
  5. from ..exceptions import UnexpectedToken
  6. from ..lexer import Token
  7. from ..utils import Enumerator, Serialize
  8. from ..grammar import END
  9. from .lalr_analysis import LALR_Analyzer, Shift, Reduce, IntParseTable
  10. ###{standalone
  11. class LALR_Parser(object):
  12. def __init__(self, parser_conf, debug=False):
  13. assert all(r.options.priority is None for r in parser_conf.rules), "LALR doesn't yet support prioritization"
  14. analysis = LALR_Analyzer(parser_conf, debug=debug)
  15. analysis.compute_lalr()
  16. callbacks = parser_conf.callbacks
  17. self._parse_table = analysis.parse_table
  18. self.parser_conf = parser_conf
  19. self.parser = _Parser(analysis.parse_table, callbacks, debug)
  20. @classmethod
  21. def deserialize(cls, data, memo, callbacks):
  22. inst = cls.__new__(cls)
  23. inst._parse_table = IntParseTable.deserialize(data, memo)
  24. inst.parser = _Parser(inst._parse_table, callbacks)
  25. return inst
  26. def serialize(self, memo):
  27. return self._parse_table.serialize(memo)
  28. def parse(self, *args):
  29. return self.parser.parse(*args)
  30. class _Parser:
  31. def __init__(self, parse_table, callbacks, debug=False):
  32. self.states = parse_table.states
  33. self.start_states = parse_table.start_states
  34. self.end_states = parse_table.end_states
  35. self.callbacks = callbacks
  36. self.debug = debug
  37. def parse(self, seq, start, set_state=None):
  38. token = None
  39. stream = iter(seq)
  40. states = self.states
  41. start_state = self.start_states[start]
  42. end_state = self.end_states[start]
  43. state_stack = [start_state]
  44. value_stack = []
  45. if set_state: set_state(start_state)
  46. def get_action(token):
  47. state = state_stack[-1]
  48. try:
  49. return states[state][token.type]
  50. except KeyError:
  51. expected = [s for s in states[state].keys() if s.isupper()]
  52. raise UnexpectedToken(token, expected, state=state)
  53. def reduce(rule):
  54. size = len(rule.expansion)
  55. if size:
  56. s = value_stack[-size:]
  57. del state_stack[-size:]
  58. del value_stack[-size:]
  59. else:
  60. s = []
  61. value = self.callbacks[rule](s)
  62. _action, new_state = states[state_stack[-1]][rule.origin.name]
  63. assert _action is Shift
  64. state_stack.append(new_state)
  65. value_stack.append(value)
  66. # Main LALR-parser loop
  67. try:
  68. for token in stream:
  69. while True:
  70. action, arg = get_action(token)
  71. assert arg != end_state
  72. if action is Shift:
  73. state_stack.append(arg)
  74. value_stack.append(token)
  75. if set_state: set_state(arg)
  76. break # next token
  77. else:
  78. reduce(arg)
  79. except Exception as e:
  80. if self.debug:
  81. print("")
  82. print("STATE STACK DUMP")
  83. print("----------------")
  84. for i, s in enumerate(state_stack):
  85. print('%d)' % i , s)
  86. print("")
  87. raise
  88. token = Token.new_borrow_pos(END, None, token) if token else Token(END, None, 0, 1, 1)
  89. while True:
  90. _action, arg = get_action(token)
  91. if _action is Shift:
  92. state_stack.append(arg)
  93. value_stack.append(token)
  94. else:
  95. assert(_action is Reduce)
  96. reduce(arg)
  97. if state_stack[-1] == end_state:
  98. return value_stack[-1]
  99. ###}