-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.py
97 lines (75 loc) · 1.64 KB
/
parse.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import ply.yacc as yacc
from compiler.ast import *
from lexer import tokens
precedence = (
('left', 'ADD'),
('right', 'UNEG'),
('nonassoc', 'LPAREN')
)
def p_module(t):
'module : mnls stmt_list'
t[0] = Module(None, Stmt(t[2]))
def p_stmt_list_multi(t):
'stmt_list : stmt nls stmt_list'
t[0] = [t[1]] + t[3]
def p_stmt_list_single(t):
'stmt_list : stmt'
t[0] = [t[1]]
def p_stmt_list_none(t):
'stmt_list : empty'
t[0] = []
def p_print(t):
'stmt : PRINT expr'
t[0] = Printnl([t[2]], None)
def p_assign(t):
'stmt : assignee EQ expr'
t[0] = Assign(t[1], t[3])
def p_discard(t):
'stmt : expr'
t[0] = Discard(t[1])
def p_assignee(t):
'assignee : NAME'
t[0] = [AssName(t[1], 'OP_ASSIGN')]
def p_int(t):
'expr : INT'
t[0] = Const(t[1])
def p_add(t):
'expr : expr ADD expr'
t[0] = Add((t[1], t[3]))
def p_name(t):
'expr : NAME'
t[0] = Name(t[1])
def p_call(t):
'expr : expr LPAREN args RPAREN'
t[0] = CallFunc(t[1], t[3], None, None)
def p_neg(t):
'expr : SUB expr %prec UNEG'
t[0] = UnarySub(t[2])
def p_paren(t):
'expr : LPAREN expr RPAREN'
t[0] = t[2]
def p_args_none(t):
'args : empty'
t[0] = []
def p_empty(t):
'empty :'
pass
def p_nls(t):
'nls : NL mnls'
pass
def p_mnls_more(t):
'mnls : nls'
pass
def p_mnls_none(t):
'mnls : empty'
pass
# Error rule for syntax errors
def p_error(p):
print "Syntax error in input! "+ str(p) + " " + str(yacc.token())
parser = None
def parse(s):
global parser
if parser == None:
parser = yacc.yacc()
ast = parser.parse(s)
return ast