-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
195 lines (161 loc) · 4.93 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python
import re
from contextlib import contextmanager
from tokenizer import T_IDENT, T_COMPARE, T_OP, T_STRING, T_NUMBER, T_CHAR
class ExpectedException(BaseException):
def __init__(self, tokens, expected):
self.expected = expected
self.token = tokens[0]
self.remaining = ''.join([x.getString() for x in tokens])[:50]
def __str__(self):
return "Expected %s, got %s(%s) near %s" % (self.expected, self.token.__class__.__name__, self.token.getString(), self.remaining)
class Parser(object):
opcodes = []
tokens = []
def __init__(self, tokens):
self.tokens = list(tokens)
def pop(self):
return self.tokens.pop(0)
def expect(self ,cls, val=None):
if not isinstance(self.tokens[0], cls):
raise ExpectedException(self.tokens, "%s(%s)" % (cls.__name__, val))
if val is not None:
if self.tokens[0].getString() != val:
raise ExpectedException(self.tokens, val)
self.pop()
def isa(self ,cls, val=None):
if not isinstance(self.tokens[0], cls): return False
if val is None: return True
return self.tokens[0].getString() == val
def do(self ,op, *params):
self.opcodes.append((op, params))
def value(self):
token = self.tokens[0]
if self.isa(T_NUMBER):
self.do("PUSH", token.getValue())
self.pop()
elif self.isa(T_CHAR):
self.do("PUSH", ord(token.getChar()))
self.pop()
elif self.isa(T_IDENT):
self.pop()
if self.isa(T_OP, '('):
self.pop()
args = 0
if not self.isa(T_OP, ')'):
self.expression()
args += 1
while self.isa(T_OP, ','):
self.pop()
self.expression()
args += 1
self.do("CALL", token.getString(), args)
self.expect(T_OP, ')')
else:
self.do("GET", token.getString())
else:
raise ExpectedException(self.tokens, "value")
def factor(self):
self.value()
token = self.tokens[0]
if self.isa(T_OP, '%'):
self.pop()
self.expression()
self.do("MOD")
def expression(self):
self.factor()
token = self.tokens[0]
if self.isa(T_COMPARE):
self.pop()
self.expression()
self.do("COMPARE", token.getString())
elif self.isa(T_OP, '+'):
self.pop()
self.expression()
self.do("ADD")
elif self.isa(T_OP, '-'):
self.pop()
self.expression()
self.do("SUB")
def statement(self):
token = self.tokens[0]
if self.isa(T_IDENT, "for"):
self.pop()
self.expect(T_OP, '(')
self.statement()
self.expect(T_OP, ';')
# Capture expression opcodes
oldOpcodes, self.opcodes = self.opcodes, []
self.expression()
expressionOpcodes, self.opcodes = self.opcodes, oldOpcodes
self.expect(T_OP, ';')
# Capture any opcodes
oldOpcodes, self.opcodes = self.opcodes, []
self.statement()
statementOpcodes, self.opcodes = self.opcodes, oldOpcodes
self.expect(T_OP, ')')
self.expect(T_OP, '{')
self.opcodes.extend(expressionOpcodes)
self.do("FOR_OPEN")
self.block()
self.opcodes.extend(statementOpcodes)
self.expect(T_OP, '}')
self.do("FOR_CLOSE")
self.opcodes.extend(expressionOpcodes)
self.do("FOR_END")
elif self.isa(T_IDENT, "if"):
self.pop()
self.expect(T_OP, '(')
self.expression()
self.expect(T_OP, ')')
self.expect(T_OP, '{')
self.do("IF_BEGIN")
self.block()
self.expect(T_OP, '}')
self.do("IF_ELSE")
if self.isa(T_IDENT, "else"):
self.pop();
self.expect(T_OP, '{')
self.block()
self.expect(T_OP, '}')
self.do("IF_END")
elif self.isa(T_IDENT):
self.pop()
if self.isa(T_OP, '--') or self.isa(T_OP, '++'):
incrToken = self.pop()
self.do("GET", token.getString())
self.do("PUSH", 1)
self.do("SUB" if incrToken.getString() == '--' else "ADD")
self.do("SET", token.getString())
elif self.isa(T_OP, '='):
self.pop()
self.expression()
self.do("SET", token.getString())
elif self.isa(T_OP, '('):
self.pop()
if token.getString() in ('print', 'println') and self.isa(T_STRING):
self.do(token.getString().upper(), self.pop().getValue())
else:
args = 0
if not self.isa(T_OP, ')'):
self.expression()
args += 1
while self.isa(T_OP, ','):
self.pop()
self.expression()
args += 1
self.do("CALL", token.getString(), args)
self.expect(T_OP, ')')
else:
raise ExpectedException(self.tokens, "=, (, or comparison")
else:
raise ExpectedException(self.tokens, "identifier")
def block(self):
while self.tokens and not self.isa(T_OP, '}'):
if self.isa(T_OP, ';'):
self.pop()
continue
self.statement()
def parse(self):
self.block()
return self.opcodes