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.

83 lines
2.4 KiB

  1. """This module implements a LALR(1) Parser
  2. """
  3. # Author: Erez Shinan (2017)
  4. # Email : erezshin@gmail.com
  5. from ..common import ParseError, UnexpectedToken
  6. from .lalr_analysis import LALR_Analyzer, ACTION_SHIFT
  7. class Parser(object):
  8. def __init__(self, parser_conf):
  9. self.analysis = LALR_Analyzer(parser_conf.rules, parser_conf.start)
  10. self.analysis.compute_lookahead()
  11. self.callbacks = {rule: getattr(parser_conf.callback, rule.alias or rule.origin, None)
  12. for rule in self.analysis.rules}
  13. def parse(self, seq, set_state=None):
  14. i = 0
  15. token = None
  16. stream = iter(seq)
  17. states_idx = self.analysis.states_idx
  18. state_stack = [self.analysis.init_state_idx]
  19. value_stack = []
  20. if set_state: set_state(self.analysis.init_state_idx)
  21. def get_action(key):
  22. state = state_stack[-1]
  23. try:
  24. return states_idx[state][key]
  25. except KeyError:
  26. expected = states_idx[state].keys()
  27. raise UnexpectedToken(token, expected, seq, i)
  28. def reduce(rule, size):
  29. if size:
  30. s = value_stack[-size:]
  31. del state_stack[-size:]
  32. del value_stack[-size:]
  33. else:
  34. s = []
  35. res = self.callbacks[rule](s)
  36. if len(state_stack) == 1 and rule.origin == self.analysis.start_symbol:
  37. return res
  38. _action, new_state = get_action(rule.origin)
  39. assert _action == ACTION_SHIFT
  40. state_stack.append(new_state)
  41. value_stack.append(res)
  42. # Main LALR-parser loop
  43. try:
  44. token = next(stream)
  45. i += 1
  46. while True:
  47. action, arg = get_action(token.type)
  48. if action == ACTION_SHIFT:
  49. state_stack.append(arg)
  50. value_stack.append(token)
  51. if set_state: set_state(arg)
  52. token = next(stream)
  53. i += 1
  54. else:
  55. reduce(*arg)
  56. except StopIteration:
  57. pass
  58. while True:
  59. _action, rule = get_action('$end')
  60. assert _action == 'reduce'
  61. res = reduce(*rule)
  62. if res:
  63. assert state_stack == [self.analysis.init_state_idx] and not value_stack, len(state_stack)
  64. return res