-
Notifications
You must be signed in to change notification settings - Fork 2
/
type_check_Lvar.py
55 lines (50 loc) · 1.66 KB
/
type_check_Lvar.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
from ast import *
class TypeCheckLvar:
def check_type_equal(self, t1, t2, e):
if t1 != t2:
raise Exception('error: ' + repr(t1) + ' != ' + repr(t2) \
+ ' in ' + repr(e))
def type_check_exp(self, e, env):
match e:
case BinOp(left, Add(), right):
l = self.type_check_exp(left, env)
self.check_type_equal(l, int, left)
r = self.type_check_exp(right, env)
self.check_type_equal(r, int, right)
return int
case UnaryOp(USub(), v):
t = self.type_check_exp(v, env)
self.check_type_equal(t, int, v)
return int
case Name(id):
return env[id]
case Constant(value) if isinstance(value, int):
return int
case Call(Name('input_int'), []):
return int
case _:
raise Exception('type_check_exp: unexpected ' + repr(e))
def type_check_stmts(self, ss, env):
if len(ss) == 0:
return
match ss[0]:
case Assign([Name(id)], value):
t = self.type_check_exp(value, env)
if id in env:
self.check_type_equal(env[id], t, value)
else:
env[id] = t
return self.type_check_stmts(ss[1:], env)
case Expr(Call(Name('print'), [arg])):
t = self.type_check_exp(arg, env)
self.check_type_equal(t, int, arg)
return self.type_check_stmts(ss[1:], env)
case Expr(value):
self.type_check_exp(value, env)
return self.type_check_stmts(ss[1:], env)
case _:
raise Exception('type_check_stmts: unexpected ' + repr(ss))
def type_check(self, p):
match p:
case Module(body):
self.type_check_stmts(body, {})