Skip to content

Commit 3be29c5

Browse files
committed
new file
1 parent dfb77a5 commit 3be29c5

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

type_check_Pif.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
from ast import *
2+
from type_check_Pvar import TypeCheckPvar, check_type_equal
3+
from utils import *
4+
5+
class TypeCheckPif(TypeCheckPvar):
6+
7+
def type_check_exp(self, e, env):
8+
match e:
9+
case Constant(value) if isinstance(value, bool):
10+
return bool
11+
case IfExp(test, body, orelse):
12+
test_t = self.type_check_exp(test, env)
13+
check_type_equal(bool, test_t, test)
14+
body_t = self.type_check_exp(body, env)
15+
orelse_t = self.type_check_exp(orelse, env)
16+
check_type_equal(body_t, orelse_t, e)
17+
return body_t
18+
case BinOp(left, Sub(), right):
19+
l = self.type_check_exp(left, env)
20+
check_type_equal(l, int, left)
21+
r = self.type_check_exp(right, env)
22+
check_type_equal(r, int, right)
23+
return int
24+
case UnaryOp(Not(), v):
25+
t = self.type_check_exp(v, env)
26+
check_type_equal(t, bool, v)
27+
return bool
28+
case BoolOp(op, values):
29+
left = values[0]; right = values[1]
30+
l = self.type_check_exp(left, env)
31+
check_type_equal(l, bool, left)
32+
r = self.type_check_exp(right, env)
33+
check_type_equal(r, bool, right)
34+
return bool
35+
case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) or isinstance(cmp, NotEq):
36+
l = self.type_check_exp(left, env)
37+
r = self.type_check_exp(right, env)
38+
check_type_equal(l, r, e)
39+
return bool
40+
case Compare(left, [cmp], [right]):
41+
l = self.type_check_exp(left, env)
42+
check_type_equal(l, int, left)
43+
r = self.type_check_exp(right, env)
44+
check_type_equal(r, int, right)
45+
return bool
46+
case Let(Name(x), rhs, body):
47+
t = self.type_check_exp(rhs, env)
48+
new_env = dict(env); new_env[x] = t
49+
return self.type_check_exp(body, new_env)
50+
case _:
51+
return super().type_check_exp(e, env)
52+
53+
def type_check_stmts(self, ss, env):
54+
if len(ss) == 0:
55+
return
56+
match ss[0]:
57+
case If(test, body, orelse):
58+
test_t = self.type_check_exp(test, env)
59+
check_type_equal(bool, test_t, test)
60+
body_t = self.type_check_stmts(body, env)
61+
orelse_t = self.type_check_stmts(orelse, env)
62+
check_type_equal(body_t, orelse_t, ss[0])
63+
return self.type_check_stmts(ss[1:], env)
64+
case _:
65+
return super().type_check_stmts(ss, env)

0 commit comments

Comments
 (0)