forked from QThuet/ParserProject.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupPrintListener.py
More file actions
49 lines (42 loc) · 1.25 KB
/
GroupPrintListener.py
File metadata and controls
49 lines (42 loc) · 1.25 KB
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
47
48
49
import sys
from antlr4 import *
from dist.GroupLexer import GroupLexer
from dist.GroupParser import GroupParser
from dist.GroupVisitor import GroupVisitor
from antlr4.tree.Trees import Trees
class MyVisitor(GroupVisitor):
def visitNumberExpr(self, ctx):
value = ctx.getText()
return int(value)
def visitParenExpr(self, ctx):
return self.visit(ctx.expr())
def visitInfixExpr(self, ctx):
l = self.visit(ctx.left)
r = self.visit(ctx.right)
op = ctx.op.text
operation = {
'+': lambda: l + r,
'-': lambda: l - r,
'*': lambda: l * r,
'/': lambda: l / r,
'%': lambda: l % r,
}
return operation.get(op, lambda: None)()
def visitByeExpr(self, ctx):
print(f"goodbye")
sys.exit(0)
if __name__ == "__main__":
while 1:
data = InputStream(input(">>> "))
# lexer
lexer = GroupLexer(data)
stream = CommonTokenStream(lexer)
# parser
parser = GroupParser(stream)
tree = parser.expr()
# evaluator
visitor = MyVisitor()
#Trees.inspect(tree,parser)
print(Trees.toStringTree(tree, None, parser))
output = visitor.visit(tree)
print(output)