Guest User

Untitled

a guest
Jun 22nd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. from rply import ParserGenerator
  2. from ast import Number, Sum, Sub, Print
  3.  
  4.  
  5. class Parser():
  6. def __init__(self):
  7. self.pg = ParserGenerator(
  8. # A list of all token names accepted by the parser.
  9. ['NUMBER', 'PRINT', 'OPEN_PAREN', 'CLOSE_PAREN',
  10. 'SEMI_COLON', 'SUM', 'SUB']
  11. )
  12.  
  13. def parse(self):
  14. @self.pg.production('program : PRINT OPEN_PAREN expression CLOSE_PAREN SEMI_COLON')
  15. def program(p):
  16. return Print(p[2])
  17.  
  18. @self.pg.production('expression : expression SUM expression')
  19. @self.pg.production('expression : expression SUB expression')
  20. def expression(p):
  21. left = p[0]
  22. right = p[2]
  23. operator = p[1]
  24. if operator.gettokentype() == 'SUM':
  25. return Sum(left, right)
  26. elif operator.gettokentype() == 'SUB':
  27. return Sub(left, right)
  28.  
  29. @self.pg.production('expression : NUMBER')
  30. def number(p):
  31. return Number(p[0].value)
  32.  
  33. @self.pg.error
  34. def error_handle(token):
  35. raise ValueError(token)
  36.  
  37. def get_parser(self):
  38. return self.pg.build()
Add Comment
Please, Sign In to add comment