Guest User

Untitled

a guest
Jan 19th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. from rply import ParserGenerator
  2. from ast import Int, Sum, Sub, Say, String
  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. ['INTEGER', 'SAY', 'OPEN_PAREN', 'CLOSE_PAREN',
  10. 'SEMI_COLON', 'SUM', 'SUB', 'STRING']
  11. )
  12.  
  13. def parse(self):
  14. @self.pg.production('say : SAY OPEN_PAREN expression CLOSE_PAREN
  15. SEMI_COLON')
  16. def say(p):
  17. return Say(p[2])
  18.  
  19. @self.pg.production('expression : expression SUM expression')
  20. @self.pg.production('expression : expression SUB expression')
  21. def expression(p):
  22. left = p[0]
  23. right = p[2]
  24. operator = p[1]
  25. if operator.gettokentype() == 'SUM':
  26. return Sum(left, right)
  27. elif operator.gettokentype() == 'SUB':
  28. return Sub(left, right)
  29.  
  30. @self.pg.production('expression : INTEGER')
  31. def int(p):
  32. return Int(p[0].value)
  33.  
  34. @self.pg.production('expression : STRING')
  35. def string(p):
  36. return String(p[0].value)
  37.  
  38. @self.pg.error
  39. def error_handler(token):
  40. raise ValueError("Ran into a %s where it wasn't expected" % token.gettokentype())
  41.  
  42. def get_parser(self):
  43. return self.pg.build()
  44.  
  45. say("yo");
  46.  
  47. say("yo");
  48. say("yoyo");
  49.  
  50. C:Usersgdog1Desktopprojintparser.py:42: ParserGeneratorWarning: 4
  51. shift/reduce conflicts
  52. return self.pg.build()
  53. Traceback (most recent call last):
  54. File "<input>", line 1, in <module>
  55. File "C:Program FilesJetBrainsPyCharm Community Edition 2018.3.3helperspydev_pydev_bundlepydev_umd.py", line 197, in runfile
  56. pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
  57. File "C:/Users/gdog1/Desktop/proj/main.py", line 20, in <module>
  58. parser.parse(tokens).eval()
  59. File "C:Python27libsite-packagesrplyparser.py", line 60, in parse
  60. self.error_handler(lookahead)
  61. File "C:Usersgdog1Desktopprojintparser.py", line 39, in error_handler
  62. raise ValueError("Ran into a %s where it wasn't expected" %
  63. token.gettokentype())
  64. ValueError: Ran into a SAY where it wasn't expected
Add Comment
Please, Sign In to add comment