Repository navigation
Expand file tree
/
Copy pathcompiler_generic.py
More file actions
263 lines (243 loc) · 11.3 KB
/
Copy pathcompiler_generic.py
File metadata and controls
263 lines (243 loc) · 11.3 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
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
import ast
from ast import *
import compiler_lambda
from utils import *
import type_check_Lgeneric
import copy
class Compiler(compiler_lambda.Compiler):
############################################################################
# Shrink
############################################################################
def convert_type(self, t):
match t:
case Subscript(Name('All'), Tuple([List(ps), ty]), Load()):
return AllType([p.id for p in ps], self.convert_type(ty))
case Name(id) if id not in ('int', 'bool'):
return GenericVar(id)
case _:
return super().convert_type(t)
def is_generic_type(self, t) -> bool:
match t:
case GenericVar(id):
return True
case AllType(ps, ty):
return self.is_generic_type(ty)
case TupleType(ts):
return any(self.is_generic_type(x) for x in ts)
case ListType(t2):
return self.is_generic_type(t2)
case FunctionType(ps, rt):
return any(self.is_generic_type(x) for x in ps) \
or self.is_generic_type(rt)
case _:
return False
def shrink_stmt(self, s: stmt):
match s:
case ImportFrom():
# from typing import TypeVar, All
return None
case Assign([Name(id)], Call(Name('TypeVar'), args)):
# T = TypeVar('T')
return None
case Pass():
return None
case _:
return super().shrink_stmt(s)
def shrink(self, p: Module) -> Module:
result = []
main_stmts = []
match p:
case Module(body):
for s in body:
match s:
case FunctionDef(name, args, stmts, dl, returns, comment):
if isinstance(args, ast.arguments):
args = [(arg.arg, self.convert_type(arg.annotation)) for arg in args.args]
else:
args = [(x, self.convert_type(t)) for (x, t) in args]
new_stmts = []
for s2 in stmts:
ss = self.shrink_stmt(s2)
if ss is not None:
new_stmts.append(ss)
result.append(
FunctionDef(name, args, new_stmts, dl,
self.convert_type(returns), comment))
case _:
ss = self.shrink_stmt(s)
if ss is not None:
main_stmts.append(ss)
case _:
raise Exception('interp: unexpected ' + repr(p))
main_stmts.append(Return(Constant(0)))
main_def = FunctionDef("main", [], main_stmts, [], IntType(), None)
result.append(main_def)
return Module(result)
def uniquify(self, p: Module) -> Module:
# run the normal uniquify pass, then monomorphize the
# generic functions at each call site
p = super().uniquify(p)
return self.monomorphize(p)
############################################################################
# Monomorphization
############################################################################
def type_to_suffix(self, t) -> str:
match t:
case IntType():
return 'int'
case BoolType():
return 'bool'
case GenericVar(id):
return id
case TupleType(ts):
return 'tuple' + ''.join([self.type_to_suffix(x) for x in ts])
case ListType(t):
return 'list' + self.type_to_suffix(t)
case FunctionType(ps, rt):
return 'fun' + ''.join([self.type_to_suffix(x) for x in ps]) + self.type_to_suffix(rt)
case AnyType():
return 'any'
case _:
return str(t)
def substitute_type(self, t, mapping):
match t:
case GenericVar(id):
return mapping.get(id, t)
case AllType(ps, ty):
# if all quantified variables are bound, collapse
remaining = [p for p in ps if p not in mapping]
new_ty = self.substitute_type(ty, mapping)
if not remaining:
return new_ty
return AllType(remaining, new_ty)
case TupleType(ts):
return TupleType([self.substitute_type(x, mapping) for x in ts])
case ListType(t2):
return ListType(self.substitute_type(t2, mapping))
case FunctionType(ps, rt):
return FunctionType([self.substitute_type(x, mapping) for x in ps],
self.substitute_type(rt, mapping))
case _:
return t
def monomorphize(self, p: Module) -> Module:
# 1. collect generic functions: params/return contain GenericVar
tc = type_check_Lgeneric.TypeCheckLgeneric()
generic = {} # name -> (params, ret, stmts)
specs = {} # (name, suffix) -> FunctionDef
for s in p.body:
if isinstance(s, FunctionDef) and s.name != 'main':
params = [(x, t) for (x, t) in s.args]
ret = s.returns
if any(self.is_generic_type(t) for _, t in params) \
or self.is_generic_type(ret):
generic[s.name] = (params, ret, s.body)
def instantiate(name, deduced):
(params, ret, body) = generic[name]
suffix = ''.join([self.type_to_suffix(deduced[t.id]) for (x, t) in params if isinstance(t, GenericVar)])
key = (name, suffix)
if key not in specs:
new_params = []
for (x, t) in params:
new_params.append((x, self.substitute_type(t, deduced)))
new_ret = self.substitute_type(ret, deduced)
new_fun = FunctionDef(name + '_' + suffix, new_params,
copy.deepcopy(body),
[], new_ret, None)
specs[key] = new_fun
return name + '_' + suffix
# 2. rewrite call sites
def rewrite_exp(e, env_types):
match e:
case Inst(gen, type_args):
# explicit instantiation: type_args maps GenericVar -> Type
new_gen = rewrite_exp(gen, env_types)
match new_gen:
case Name(f) if f in generic:
# deduce from the type args map (GenericVar keys)
deduced = {}
for k, v in type_args.items():
if isinstance(k, GenericVar):
deduced[k.id] = v
return Name(instantiate(f, deduced))
case _:
return new_gen
case Call(Name(f), args) if f in generic:
new_args = [rewrite_exp(a, env_types) for a in args]
# infer the type arguments from the actual arguments
deduced = {}
(params, ret, body) = generic[f]
for ((x, pt), arg) in zip(params, new_args):
arg_t = tc.type_check_exp(arg, env_types)
tc.match_types(pt, arg_t, deduced, arg)
return Call(Name(instantiate(f, deduced)), new_args)
case Call(func, args):
return Call(rewrite_exp(func, env_types),
[rewrite_exp(a, env_types) for a in args])
case Name(id):
return e
case Constant(v):
return e
case BinOp(left, op, right):
return BinOp(rewrite_exp(left, env_types), op,
rewrite_exp(right, env_types))
case UnaryOp(op, v):
return UnaryOp(op, rewrite_exp(v, env_types))
case Compare(left, [cmp], [right]):
return Compare(rewrite_exp(left, env_types), [cmp],
rewrite_exp(right, env_types))
case IfExp(test, body, orelse):
return IfExp(rewrite_exp(test, env_types),
rewrite_exp(body, env_types),
rewrite_exp(orelse, env_types))
case Tuple(es, ctx):
return Tuple([rewrite_exp(x, env_types) for x in es], ctx)
case Subscript(v, s, ctx):
return Subscript(rewrite_exp(v, env_types),
rewrite_exp(s, env_types), ctx)
case Lambda(params, body):
return Lambda(params, rewrite_exp(body, env_types))
case _:
return e
def rewrite_stmt(s, env_types):
match s:
case Expr(value):
return Expr(rewrite_exp(value, env_types))
case Assign([lhs], value):
return Assign([lhs], rewrite_exp(value, env_types))
case If(test, body, orelse):
return If(rewrite_exp(test, env_types),
[rewrite_stmt(x, env_types) for x in body],
[rewrite_stmt(x, env_types) for x in orelse])
case While(test, body, []):
return While(rewrite_exp(test, env_types),
[rewrite_stmt(x, env_types) for x in body], [])
case Return(value):
return Return(rewrite_exp(value, env_types))
case _:
return s
# 3. rebuild the program: keep concrete functions, add specializations
result = []
for s in p.body:
if isinstance(s, FunctionDef):
if s.name in generic:
# drop the generic template; keep its specializations
continue
env_types = {x: t for (x, t) in s.args}
new_fun = FunctionDef(s.name, s.args,
[rewrite_stmt(x, env_types) for x in s.body],
s.decorator_list, s.returns, s.type_comment)
result.append(new_fun)
else:
result.append(rewrite_stmt(s, {}))
for key, fun in specs.items():
result.append(fun)
return Module(result)
############################################################################
# remove_complex_operands: type-check with the generic checker
############################################################################
def remove_complex_operands(self, p: Module) -> Module:
type_check_Lgeneric.TypeCheckLgeneric().type_check(p)
return super().remove_complex_operands(p)
def expose_allocation(self, p):
type_check_Lgeneric.TypeCheckLgeneric().type_check(p)
return super().expose_allocation(p)