-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.py
74 lines (50 loc) · 1.7 KB
/
parser.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/python
import scanner
import ply.yacc as yacc
from ast import *
tokens = scanner.tokens
precedence = (
# to fill ...
("left", '+', '-'),
("left", '*', '/')
# to fill ...
)
def p_error(p):
if p:
print("Syntax error at line {0}, column {1}: LexToken({2}, '{3}')".format(p.lineno, scanner.find_tok_column(p),
p.type, p.value))
else:
print("Unexpected end of input")
def p_program(p):
"""program : instructions_opt"""
def p_instructions_opt_1(p):
"""instructions_opt : instructions """
def p_instructions_opt_2(p):
"""instructions_opt : """
def p_instructions_1(p):
"""instructions : instructions instruction """
def p_instructions_2(p):
"""instructions : instruction """
def p_expression_binop(p):
'''expression : expression + expression
| expression - expression
| expression * expression
| expression / expression
| expression < expression
| expression > expression
| expression DOTADD expression
| expression DOTSUB expression
| expression DOTMUL expression
| expression DOTDIV expression
| expression EQ expression
| expression LTE expression
| expression GTE expression
| expression NE expression '''
p[0] = BinOp(p[1], p[2], p[3])
def p_expression_group(p):
'expression : LPAREN expression RPAREN'
p[0] = p[2]
def p_expression_number(p):
'expression : NUMBER'
p[0] = Number(p[1])
parser = yacc.yacc()