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.

193 lines
6.4 KiB

  1. """This module implements a LALR(1) Parser
  2. """
  3. # Author: Erez Shinan (2017)
  4. # Email : erezshin@gmail.com
  5. from copy import deepcopy, copy
  6. from ..exceptions import UnexpectedInput, UnexpectedToken
  7. from ..lexer import Token
  8. from ..utils import Serialize
  9. from .lalr_analysis import LALR_Analyzer, Shift, Reduce, IntParseTable
  10. from .lalr_puppet import ParserPuppet
  11. from lark.exceptions import UnexpectedCharacters, UnexpectedInput, UnexpectedToken
  12. ###{standalone
  13. class LALR_Parser(Serialize):
  14. def __init__(self, parser_conf, debug=False):
  15. analysis = LALR_Analyzer(parser_conf, debug=debug)
  16. analysis.compute_lalr()
  17. callbacks = parser_conf.callbacks
  18. self._parse_table = analysis.parse_table
  19. self.parser_conf = parser_conf
  20. self.parser = _Parser(analysis.parse_table, callbacks, debug)
  21. @classmethod
  22. def deserialize(cls, data, memo, callbacks, debug=False):
  23. inst = cls.__new__(cls)
  24. inst._parse_table = IntParseTable.deserialize(data, memo)
  25. inst.parser = _Parser(inst._parse_table, callbacks, debug)
  26. return inst
  27. def serialize(self, memo):
  28. return self._parse_table.serialize(memo)
  29. def parse(self, lexer, start, on_error=None):
  30. try:
  31. return self.parser.parse(lexer, start)
  32. except UnexpectedInput as e:
  33. if on_error is None:
  34. raise
  35. while True:
  36. if isinstance(e, UnexpectedCharacters):
  37. s = e.puppet.lexer_state.state
  38. p = s.line_ctr.char_pos
  39. if not on_error(e):
  40. raise e
  41. if isinstance(e, UnexpectedCharacters):
  42. # If user didn't change the character position, then we should
  43. if p == s.line_ctr.char_pos:
  44. s.line_ctr.feed(s.text[p:p+1])
  45. try:
  46. return e.puppet.resume_parse()
  47. except UnexpectedToken as e2:
  48. if isinstance(e, UnexpectedToken) and e.token.type == e2.token.type == '$END' and e.puppet == e2.puppet:
  49. # Prevent infinite loop
  50. raise e2
  51. e = e2
  52. except UnexpectedCharacters as e2:
  53. e = e2
  54. class ParseConf(object):
  55. __slots__ = 'parse_table', 'callbacks', 'start', 'start_state', 'end_state', 'states'
  56. def __init__(self, parse_table, callbacks, start):
  57. self.parse_table = parse_table
  58. self.start_state = self.parse_table.start_states[start]
  59. self.end_state = self.parse_table.end_states[start]
  60. self.states = self.parse_table.states
  61. self.callbacks = callbacks
  62. self.start = start
  63. class ParserState(object):
  64. __slots__ = 'parse_conf', 'lexer', 'state_stack', 'value_stack'
  65. def __init__(self, parse_conf, lexer, state_stack=None, value_stack=None):
  66. self.parse_conf = parse_conf
  67. self.lexer = lexer
  68. self.state_stack = state_stack or [self.parse_conf.start_state]
  69. self.value_stack = value_stack or []
  70. @property
  71. def position(self):
  72. return self.state_stack[-1]
  73. # Necessary for match_examples() to work
  74. def __eq__(self, other):
  75. if not isinstance(other, ParserState):
  76. return NotImplemented
  77. return len(self.state_stack) == len(other.state_stack) and self.position == other.position
  78. def __copy__(self):
  79. return type(self)(
  80. self.parse_conf,
  81. self.lexer, # XXX copy
  82. copy(self.state_stack),
  83. deepcopy(self.value_stack),
  84. )
  85. def copy(self):
  86. return copy(self)
  87. def feed_token(self, token, is_end=False):
  88. state_stack = self.state_stack
  89. value_stack = self.value_stack
  90. states = self.parse_conf.states
  91. end_state = self.parse_conf.end_state
  92. callbacks = self.parse_conf.callbacks
  93. while True:
  94. state = state_stack[-1]
  95. try:
  96. action, arg = states[state][token.type]
  97. except KeyError:
  98. expected = {s for s in states[state].keys() if s.isupper()}
  99. raise UnexpectedToken(token, expected, state=self, puppet=None)
  100. assert arg != end_state
  101. if action is Shift:
  102. # shift once and return
  103. assert not is_end
  104. state_stack.append(arg)
  105. value_stack.append(token if token.type not in callbacks else callbacks[token.type](token))
  106. return
  107. else:
  108. # reduce+shift as many times as necessary
  109. rule = arg
  110. size = len(rule.expansion)
  111. if size:
  112. s = value_stack[-size:]
  113. del state_stack[-size:]
  114. del value_stack[-size:]
  115. else:
  116. s = []
  117. value = callbacks[rule](s)
  118. _action, new_state = states[state_stack[-1]][rule.origin.name]
  119. assert _action is Shift
  120. state_stack.append(new_state)
  121. value_stack.append(value)
  122. if is_end and state_stack[-1] == end_state:
  123. return value_stack[-1]
  124. class _Parser(object):
  125. def __init__(self, parse_table, callbacks, debug=False):
  126. self.parse_table = parse_table
  127. self.callbacks = callbacks
  128. self.debug = debug
  129. def parse(self, lexer, start, value_stack=None, state_stack=None):
  130. parse_conf = ParseConf(self.parse_table, self.callbacks, start)
  131. parser_state = ParserState(parse_conf, lexer, state_stack, value_stack)
  132. return self.parse_from_state(parser_state)
  133. def parse_from_state(self, state):
  134. # Main LALR-parser loop
  135. try:
  136. token = None
  137. for token in state.lexer.lex(state):
  138. state.feed_token(token)
  139. token = Token.new_borrow_pos('$END', '', token) if token else Token('$END', '', 0, 1, 1)
  140. return state.feed_token(token, True)
  141. except UnexpectedInput as e:
  142. try:
  143. e.puppet = ParserPuppet(self, state, state.lexer)
  144. except NameError:
  145. pass
  146. raise e
  147. except Exception as e:
  148. if self.debug:
  149. print("")
  150. print("STATE STACK DUMP")
  151. print("----------------")
  152. for i, s in enumerate(state.state_stack):
  153. print('%d)' % i , s)
  154. print("")
  155. raise
  156. ###}