-
Notifications
You must be signed in to change notification settings - Fork 0
/
postfix_translator.py
46 lines (35 loc) · 1.26 KB
/
postfix_translator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from spi import Lexer, Parser, NodeVisitor
INTEGER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF = \
"INTEGER", "PLUS", "MINUS", "MULTIPLY", "DIVIDE", "LPAREN", "RPAREN", "EOF"
class Interpreter(NodeVisitor):
def __init__(self, parser):
self.parser = parser
def visit_BinOp(self, node):
if node.op.type == PLUS:
return "%s %s +" % (self.visit(node.left), self.visit(node.right))
elif node.op.type == MINUS:
return "%s %s -" % (self.visit(node.left), self.visit(node.right))
elif node.op.type == MULTIPLY:
return "%s %s *" % (self.visit(node.left), self.visit(node.right))
elif node.op.type == DIVIDE:
return "%s %s /" % (self.visit(node.left), self.visit(node.right))
def visit_Num(self, node):
return node.value
def interpret(self):
tree = self.parser.parse()
return self.visit(tree)
def main():
while True:
try:
text = input('spi> ')
except EOFError:
break
if not text:
continue
lexer = Lexer(text)
parser = Parser(lexer)
interpreter = Interpreter(parser)
result = interpreter.interpret()
print(result)
if __name__ == '__main__':
main()