-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc_snapshot_3.py
412 lines (325 loc) · 10.3 KB
/
calc_snapshot_3.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import sys
import math
import ply.lex as lex
sys.path.insert(0, "../..")
reserved = {
'if': 'IF',
'while': 'WHILE',
'for': 'FOR',
'define': 'DEFINE',
'int': 'INT',
'float': 'FLOAT',
'boolean': 'BOOLEAN',
'string': 'STRING'
}
tokens = [
'NAME', 'NATURAL_NUMBER', 'REAL_NUMBER', 'BOOL', 'STR',
'sin', 'cos', 'exp', 'sqrt', 'log', 'power', 'intToFloat', 'floatToInt',
'EQ', 'NOTEQ', 'LT', 'GT', 'LTEQ', 'GTEQ',
] + list(reserved.values())
literals = ['=', '+', '-', '*', '/', '(', ')', ',']
# Tokens
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_REAL_NUMBER(t):
r'[-+]?[0-9]+(\.([0-9]+)?([eE][-+]?[0-9]+)?|[eE][-+]?[0-9]+)'
t.value = float(t.value)
return t
def t_NATURAL_NUMBER(t):
r'[-]?\d+'
t.value = int(t.value)
return t
def t_BOOL(t):
r'(True|False)'
return t
def t_STR(t):
r'"([^"\n]|(\\"))*"'
return t
def t_sin(t):
r'sin(?=[0-9() ])'
return t
def t_cos(t):
r'cos(?=[0-9() ])'
return t
def t_exp(t):
r'exp(?=[0-9() ])'
return t
def t_sqrt(t):
r'sqrt(?=[0-9() ])'
return t
def t_log(t):
r'log(?=[0-9() ])'
return t
def t_power(t):
r'\*\*'
return t
def t_intToFloat(t):
r'intToFloat(?=[0-9() ])'
return t
def t_floatToInt(t):
r'floatToInt(?=[0-9() ])'
return t
t_ignore = " \t"
t_EQ = r'=='
t_NOTEQ = r'!='
t_LT = r'<'
t_GT = r'>'
t_LTEQ = r'<='
t_GTEQ = r'>='
def t_IF(t):
r'if'
return t
def t_WHILE(t):
r'while'
return t
def t_FOR(t):
r'for'
return t
def t_DEFINE(t):
r'define'
return t
def t_INT(t):
r'int'
return t
def t_FLOAT(t):
r'float'
return t
def t_BOOLEAN(t):
r'boolean'
return t
def t_STRING(t):
r'string'
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
lexer = lex.lex()
# Parsing rules
precedence = (
('left', '+', '-', 'sin', 'cos', 'log', 'exp', 'sqrt', 'intToFloat', 'floatToInt'),
('left', '*', '/'),
('right', 'UMINUS'),
)
# dictionary of names
globals = {}
functions = {}
def names(local, name):
return local[name](local) if name in local.keys() else globals[name]
def p_start(p):
"""start : if_statement
| for_statement
| while_statement
| define
| statement"""
p[0] = p[1]
res = p[0]({}) if p[0] is not None else None
if p[0] is not None and res is not None:
print(res)
def p_for_statement(p):
"for_statement : FOR '(' statement ',' expression ',' statement ')' statement"
cond = p[5]
initial = p[3]
update = p[7]
action = p[9]
def loop(local):
initial(local)
if cond({})[0] != 'boolean':
return "Error on if condition, boolean required"
while cond(local)[1]:
print(action(local))
update(local)
p[0] = loop
def p_if_statement(p):
"if_statement : IF '(' expression ')' statement"
res = p[3]({})
if res[0] != 'boolean':
p[0] = "Error on if condition, boolean required"
elif res[1]:
p[0] = p[5]
def p_while_statement(p):
"""while_statement : WHILE '(' expression ')' statement"""
cond = p[3]
statement = p[5]
def res(local):
if cond({})[0] != 'boolean':
return "Error on if condition, boolean required"
while cond(local)[1] if callable(cond) else cond:
print(statement(local))
p[0] = res
def p_define(p):
"""define : DEFINE NAME '(' params ')' '=' statement"""
fun_name = p[2]
params = p[4]
statement = p[7]
def apply(args, local):
m = dict(zip(params, args))
return statement(dict(m, **local))
functions[fun_name] = apply
print(functions)
def p_statement_assign(p):
"""statement : INT NAME "=" statement
| FLOAT NAME "=" statement
| BOOLEAN NAME "=" statement
| STRING NAME "=" statement """
typ = p[1]
name = p[2]
expr = p[4]
def assign(local):
if name not in globals:
if (typ == expr(local)[0]):
globals[name] = expr(local)
return globals[name]
else:
return "Incompatible types!"
else:
return "Name already exists!"
p[0] = assign
def p_statement_reassign(p):
"""statement : NAME "=" statement"""
name = p[1]
expr = p[3]
def reassign(local):
if name in globals:
if (globals[name][0] == expr(local)[0]):
globals[name] = expr(local)
return globals[name]
else:
return "Incompatible types!"
else:
return "Name doesn't exist!"
p[0] = reassign
def p_params(p):
"""params : NAME
| NAME ',' params"""
if(len(p) > 3):
p[0] = [p[1]] + p[3]
else:
p[0] = [p[1]]
def p_call_function(p):
"""statement : NAME '(' statements ')' """
func = functions[p[1]]
params = p[3]
p[0] = lambda local: func(params, local)
def p_statements(p):
"""statements : statement
| statement ',' statements"""
if(len(p) > 3):
p[0] = [p[1]] + p[3]
else:
p[0] = [p[1]]
def p_statement_expr(p):
'statement : expression'
expr = p[1]
p[0] = lambda local: expr(local)
def p_expression_binop(p):
'''expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression
| expression EQ expression
| expression NOTEQ expression
| expression LTEQ expression
| expression GTEQ expression
| expression LT expression
| expression GT expression
| expression power expression'''
expr1 = p[1]
op = p[2]
expr2 = p[3]
if op == '+':
p[0] = lambda local: (expr1(local)[0], expr1(local)[1] + expr2(local)[1]) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == '-':
p[0] = lambda local: (expr1(local)[0], expr1(local)[1] - expr2(local)[1]) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == '*':
p[0] = lambda local: (expr1(local)[0], expr1(local)[1] * expr2(local)[1]) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == '/':
p[0] = lambda local: (expr1(local)[0], expr1(local)[1] / expr2(local)[1]) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == "==":
p[0] = lambda local: ('boolean', True if expr1(local)[1] == expr2(local)[1] else False) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == "!=":
p[0] = lambda local: ('boolean', True if expr1(local)[1] != expr2(local)[1] else False) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == ">=":
p[0] = lambda local: ('boolean', True if expr1(local)[1] >= expr2(local)[1] else False) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == "<=":
p[0] = lambda local: ('boolean', True if expr1(local)[1] <= expr2(local)[1] else False) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == ">":
p[0] = lambda local: ('boolean', True if expr1(local)[1] > expr2(local)[1] else False) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == "<":
p[0] = lambda local: ('boolean', True if expr1(local)[1] < expr2(local)[1] else False) if expr1(local)[0] == expr2(local)[0] else 'Error, incomatbile types'
elif op == "**":
p[0] = lambda local: (str(type(expr1(local)[1] ** expr2(local)[1]))[8:-2], expr1(local)[1] ** expr2(local)[1])
def p_expression_unop(p):
'''expression : sin expression
| cos expression
| exp expression
| sqrt expression
| log expression
| intToFloat expression
| floatToInt expression'''
op = p[1]
expr = p[2]
if op == 'sin':
p[0] = lambda local: ('float', math.sin(expr(local)[1]))
elif op == 'cos':
p[0] = lambda local: ('float', math.cos(expr(local)[1]))
elif op == 'exp':
p[0] = lambda local: ('float', math.exp(expr(local)[1]))
elif op == 'sqrt':
p[0] = lambda local: ('float', math.sqrt(expr(local)[1]))
elif op == 'log':
p[0] = lambda local: ('float', math.log(expr(local)[1]))
elif op == 'intToFloat':
p[0] = lambda local: ('float', float(expr(local)[1])) if expr(local)[0] == 'int' else "Error, int required"
elif op == 'floatToInt':
p[0] = lambda local: ('int', int(expr(local)[1])) if expr(local)[0] == 'float' else "Error, float required"
def p_expression_uminus(p):
"expression : '-' expression %prec UMINUS"
uminus = -p[2]
p[0] = lambda local: uminus(local)
def p_expression_group(p):
"expression : '(' expression ')'"
group = p[2]
p[0] = lambda local: group(local)
def p_expression_number(p):
'''expression : REAL_NUMBER
| NATURAL_NUMBER
| BOOL
| STR'''
number = p[1]
if (isinstance(number, int)):
p[0] = lambda local: ('int', number)
elif (isinstance(number, float)):
p[0] = lambda local: ('float', number)
elif (number == "True"):
p[0] = lambda local: ('boolean', True)
elif (number == "False"):
p[0] = lambda local: ('boolean', False)
else:
p[0] = lambda local: ('string', number[1:-1])
def p_expression_name(p):
"""expression : NAME"""
name = p[1]
def do_nothing(local):
print("Undefined name '%s'" % name)
pass
def parseName(local):
try:
if name in list(globals.keys()) + list(local.keys()):
return names(local, name)
else:
return do_nothing(local)
except LookupError:
return do_nothing(local)
p[0] = parseName
def p_error(p):
if p:
print("Syntax error at '%s'" % p.value)
else:
print("Syntax error at EOF")
import ply.yacc as yacc
parser = yacc.yacc()
def parse(input_str):
return yacc.parse(input_str)