Repository navigation
Expand file tree
/
Copy pathtype_check_Lcast.py
More file actions
92 lines (85 loc) · 2.94 KB
/
Copy pathtype_check_Lcast.py
File metadata and controls
92 lines (85 loc) · 2.94 KB
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
import ast
from ast import *
from type_check_Llambda import TypeCheckLlambda
from type_check_Lgrad import TypeCheckLgrad
from utils import *
import typing
class TypeCheckLcast(TypeCheckLlambda):
def type_check_stmts(self, ss, env):
if len(ss) == 0:
return IntType()
match ss[0]:
case ImportFrom():
return self.type_check_stmts(ss[1:], env)
case AnnAssign(v, ty, value, simple) if isinstance(v, Name):
ty_annot = self.parse_type_annot(ty)
env[v.id] = ty_annot
self.check_exp(value, ty_annot, env)
return self.type_check_stmts(ss[1:], env)
case _:
return super().type_check_stmts(ss, env)
def check_type_equal(self, t1, t2, e):
if t1 == Bottom() or t2 == Bottom():
return
match t1:
case AnyType():
return
case _:
match t2:
case AnyType():
return
case _:
return super().check_type_equal(t1, t2, e)
def parse_type_annot(self, annot):
match annot:
case None:
return AnyType()
case AnyType():
return AnyType()
case Name('Any'):
return AnyType()
case _:
return super().parse_type_annot(annot)
def type_check_exp(self, e, env):
#trace('*** type_check_exp: ' + str(e) + '\nenv: ' + str(env))
match e:
case Cast(value, source, target):
self.check_exp(value, source, env)
TypeCheckLgrad().check_consistent(source, target, e)
return target
case AnnLambda(params, returns, body):
new_env = {x:t for (x,t) in env.items()}
for (x,t) in params:
new_env[x] = t
return_t = self.type_check_exp(body, new_env)
self.check_type_equal(returns, return_t, e)
return FunctionType([t for (x,t) in params], return_t)
case Call(func, args):
func_t = self.type_check_exp(func, env)
match func_t:
case FunctionType(params_t, return_t):
for (arg, param_t) in zip(args, params_t):
self.check_exp(arg, param_t, env)
return return_t
case AnyType():
# dynamically-typed function: check args, result is Any
for arg in args:
self.type_check_exp(arg, env)
return AnyType()
case _:
raise Exception('type_check_exp: in call, unexpected ' + \
repr(func_t))
case Call(Name('any_load'), [tup, index]):
self.check_exp(tup, AnyType(), env)
self.check_exp(index, IntType(), env)
return AnyType()
case Call(Name('any_store'), [tup, index, value]):
self.check_exp(tup, AnyType(), env)
self.type_check_exp(value, env)
self.check_exp(index, IntType(), env)
return VoidType()
case Call(Name('any_len'), [tup]):
self.check_exp(tup, AnyType(), env)
return IntType()
case _:
return super().type_check_exp(e, env)