Home My Page Projects Code Snippets Project Openings diderot
Summary Activity Tracker Tasks SCM

SCM Repository

[diderot] Annotation of /trunk/src/compiler/typechecker/typechecker.sml
ViewVC logotype

Annotation of /trunk/src/compiler/typechecker/typechecker.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 91 - (view) (download)
Original Path: trunk/src/typechecker/typechecker.sml

1 : jhr 69 (* typechecker.sml
2 :     *
3 :     * COPYRIGHT (c) 2010 The Diderot Project (http://diderot.cs.uchicago.edu)
4 :     * All rights reserved.
5 :     *)
6 :    
7 :     structure Typechecker : sig
8 :    
9 : jhr 88 exception Error
10 :    
11 : jhr 86 val check : Error.err_stream -> ParseTree.program -> AST.program
12 : jhr 69
13 :     end = struct
14 :    
15 : jhr 70 structure PT = ParseTree
16 : jhr 69 structure Ty = Types
17 : jhr 81 structure U = Util
18 : jhr 69
19 : jhr 88 exception Error
20 :    
21 : jhr 86 type context = Error.err_stream * Error.span
22 :    
23 :     fun withContext ((errStrm, _), {span, tree}) =
24 :     ((errStrm, span), tree)
25 :     fun withEnvAndContext (env, (errStrm, _), {span, tree}) =
26 :     (env, (errStrm, span), tree)
27 :    
28 : jhr 88 fun error ((errStrm, span), msg) = (
29 :     Error.errorAt(errStrm, span, msg);
30 :     raise Error)
31 : jhr 86
32 : jhr 88 datatype token
33 :     = S of string | A of Atom.atom
34 :     | V of AST.var | TY of Types.ty | TYS of Types.ty list
35 :    
36 :     fun err (cxt, toks) = let
37 :     fun tok2str (S s) = s
38 :     | tok2str (A a) = Atom.toString a
39 :     | tok2str (V x) = Var.nameOf x
40 :     | tok2str (TY ty) = TypeUtil.toString ty
41 :     | tok2str (TYS []) = "()"
42 :     | tok2str (TYS[ty]) = TypeUtil.toString ty
43 :     | tok2str (TYS tys) = String.concat[
44 :     "(", String.concatWith " * " (List.map TypeUtil.toString tys), ")"
45 :     ]
46 :     in
47 :     error(cxt, List.map tok2str toks)
48 :     end
49 :    
50 : jhr 83 val realZero = AST.E_Lit(Literal.Float(FloatLit.zero true))
51 :    
52 : jhr 70 (* check a differentiation level, which muse be >= 0 *)
53 :     fun checkDiff (cxt, k) =
54 :     if (k < 0)
55 :     then raise Fail "differentiation must be >= 0"
56 : jhr 75 else Ty.DiffConst(IntInf.toInt k)
57 : jhr 70
58 :     (* check a dimension, which must be 2 or 3 *)
59 :     fun checkDim (cxt, d) =
60 : jhr 82 if (d <= 0)
61 :     then raise Fail "invalid dimension; must be > 0"
62 : jhr 75 else Ty.DimConst(IntInf.toInt d)
63 : jhr 70
64 :     (* check a shape *)
65 :     fun checkShape (cxt, shape) = let
66 :     fun chkDim d = if (d < 1)
67 :     then raise Fail "invalid shape dimension; must be >= 1"
68 : jhr 75 else Ty.DimConst(IntInf.toInt d)
69 : jhr 70 in
70 :     Ty.Shape(List.map chkDim shape)
71 :     end
72 :    
73 : jhr 69 (* check the well-formedness of a type and translate it to an AST type *)
74 : jhr 70 fun checkTy (cxt, ty) = (case ty
75 : jhr 86 of PT.T_Mark m => checkTy(withContext(cxt, m))
76 : jhr 70 | PT.T_Bool => Ty.T_Bool
77 :     | PT.T_Int => Ty.T_Int
78 :     | PT.T_Real => Ty.realTy
79 :     | PT.T_String => Ty.T_String
80 :     | PT.T_Vec n => (* NOTE: the parser guarantees that 2 <= n <= 4 *)
81 :     Ty.vecTy(IntInf.toInt n)
82 :     | PT.T_Kernel k => Ty.T_Kernel(checkDiff(cxt, k))
83 :     | PT.T_Field{diff, dim, shape} => Ty.T_Field{
84 :     diff = checkDiff (cxt, diff),
85 :     dim = checkDim (cxt, dim),
86 :     shape = checkShape (cxt, shape)
87 :     }
88 :     | PT.T_Tensor shape => Ty.T_Tensor(checkShape(cxt, shape))
89 :     | PT.T_Image{dim, shape} => Ty.T_Image{
90 :     dim = checkDim (cxt, dim),
91 :     shape = checkShape (cxt, shape)
92 :     }
93 :     | PT.T_Array(ty, dims) => raise Fail "Array type"
94 : jhr 69 (* end case *))
95 :    
96 : jhr 71 fun checkLit lit = (case lit
97 :     of (Literal.Int _) => (AST.E_Lit lit, Ty.T_Int)
98 :     | (Literal.Float _) => (AST.E_Lit lit, Ty.realTy)
99 :     | (Literal.String s) => (AST.E_Lit lit, Ty.T_String)
100 :     | (Literal.Bool _) => (AST.E_Lit lit, Ty.T_Bool)
101 :     (* end case *))
102 :    
103 : jhr 85 (* resolve overloading: we use a simple scheme that selects the first operator in the
104 :     * list that matches the argument types.
105 :     *)
106 : jhr 91 fun resolveOverload (cxt, rator, argTys, args, candidates) = let
107 :     fun tryCandidates [] = err(cxt, [
108 :     S "unable to resolve overloaded operator \"", A rator, S "\"\n",
109 :     S " argument type is: ", TYS argTys, S "\n"
110 : jhr 85 ])
111 :     | tryCandidates (x::xs) = let
112 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
113 :     in
114 :     if U.tryMatchTypes(domTy, argTys)
115 :     then (AST.E_Apply(x, tyArgs, args, rngTy), rngTy)
116 :     else tryCandidates xs
117 :     end
118 :     in
119 :     tryCandidates candidates
120 :     end
121 :    
122 : jhr 70 (* typecheck an expression and translate it to AST *)
123 : jhr 71 fun checkExpr (env, cxt, e) = (case e
124 : jhr 86 of PT.E_Mark m => checkExpr (withEnvAndContext (env, cxt, m))
125 : jhr 71 | PT.E_Var x => (case Env.findVar (env, x)
126 : jhr 81 of SOME x' => let
127 :     val (args, ty) = Util.instantiate(Var.typeOf x')
128 :     in
129 :     (AST.E_Var(x', args, ty), ty)
130 :     end
131 : jhr 88 | NONE => err(cxt, [S "undeclared variable ", A x])
132 : jhr 71 (* end case *))
133 :     | PT.E_Lit lit => checkLit lit
134 : jhr 81 | PT.E_OrElse(e1, e2) => let
135 :     val (e1', ty1) = checkExpr(env, cxt, e1)
136 :     val (e2', ty2) = checkExpr(env, cxt, e2)
137 :     in
138 :     case (ty1, ty2)
139 :     of (Ty.T_Bool, Ty.T_Bool) =>
140 :     (AST.E_Cond(e1', AST.E_Lit(Literal.Bool true), e2'), Ty.T_Bool)
141 :     | _ => raise Fail "arguments to \"||\" must have bool type"
142 :     (* end case *)
143 :     end
144 :     | PT.E_AndAlso(e1, e2) => let
145 :     val (e1', ty1) = checkExpr(env, cxt, e1)
146 :     val (e2', ty2) = checkExpr(env, cxt, e2)
147 :     in
148 :     case (ty1, ty2)
149 :     of (Ty.T_Bool, Ty.T_Bool) =>
150 :     (AST.E_Cond(e1', e2', AST.E_Lit(Literal.Bool false)), Ty.T_Bool)
151 :     | _ => raise Fail "arguments to \"||\" must have bool type"
152 :     (* end case *)
153 :     end
154 :     | PT.E_BinOp(e1, rator, e2) => let
155 :     val (e1', ty1) = checkExpr(env, cxt, e1)
156 :     val (e2', ty2) = checkExpr(env, cxt, e2)
157 :     in
158 :     case Basis.findOp rator
159 :     of [rator] => let
160 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
161 :     in
162 :     if U.matchTypes(domTy, [ty1, ty2])
163 :     then (AST.E_Apply(rator, tyArgs, [e1', e2'], rngTy), rngTy)
164 : jhr 89 else err (cxt, [
165 :     S "type error for binary operator \"", V rator, S "\"\n",
166 :     S " expected: ", TYS domTy, S "\n",
167 :     S " but found: ", TYS[ty1, ty2], S "\n"
168 : jhr 85 ])
169 : jhr 81 end
170 : jhr 91 | ovldList => resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
171 : jhr 81 (* end case *)
172 :     end
173 :     | PT.E_UnaryOp(rator, e) => let
174 :     val (e', ty) = checkExpr(env, cxt, e)
175 :     in
176 :     case Basis.findOp rator
177 :     of [rator] => let
178 :     val (tyArgs, Ty.T_Fun([domTy], rngTy)) = Util.instantiate(Var.typeOf rator)
179 :     in
180 :     if U.matchType(domTy, ty)
181 :     then (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
182 : jhr 89 else err (cxt, [
183 :     S "type error for unary operator \"", V rator, S "\"\n",
184 :     S " expected: ", TY domTy, S "\n",
185 :     S " but found: ", TY ty, S "\n"
186 : jhr 85 ])
187 : jhr 81 end
188 : jhr 91 | ovldList => resolveOverload (cxt, rator, [ty], [e'], ovldList)
189 : jhr 81 (* end case *)
190 :     end
191 :     | PT.E_Tuple args => let
192 :     val (args, tys) = checkExprList (env, cxt, args)
193 :     in
194 :     raise Fail "E_Tuple not yet implemented"
195 :     end
196 :     | PT.E_Apply(f, args) => let
197 :     val (args, tys) = checkExprList (env, cxt, args)
198 :     in
199 :     case Env.findVar (env, f)
200 :     of SOME f => (case Util.instantiate(Var.typeOf f)
201 :     of (tyArgs, Ty.T_Fun(domTy, rngTy)) =>
202 :     if U.matchTypes(domTy, tys)
203 :     then (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
204 : jhr 88 else err(cxt, [
205 :     S "type error in application of ", V f, S "\n",
206 :     S " expected: ", TYS domTy, S "\n",
207 :     S " but found: ", TYS tys, S "\n"
208 :     ])
209 : jhr 81 | _ => raise Fail "application of non-function"
210 :     (* end case *))
211 :     | NONE => raise Fail "unknown function"
212 :     (* end case *)
213 :     end
214 : jhr 86 | PT.E_Cons args => let
215 :     val (args, ty::tys) = checkExprList (env, cxt, args)
216 : jhr 81 in
217 : jhr 86 case Util.prune ty
218 :     of Ty.T_Tensor shape => let
219 :     fun chkTy ty' = U.matchType(ty, ty')
220 :     val resTy = Ty.T_Tensor(Ty.shapeExt(shape, Ty.DimConst(List.length args)))
221 : jhr 83 in
222 : jhr 86 if List.all chkTy tys
223 :     then (AST.E_Cons args, resTy)
224 :     else raise Fail "arguments of tensor construction must have same type"
225 : jhr 83 end
226 : jhr 86 | _ => raise Fail "Invalid argument type for tensor construction"
227 : jhr 83 (* end case *)
228 : jhr 81 end
229 : jhr 86 | PT.E_Real e => (case checkExpr (env, cxt, e)
230 :     of (e', Ty.T_Int) =>
231 :     (AST.E_Apply(BasisVars.i2r, [], [e'], Ty.realTy), Ty.realTy)
232 :     | _ => raise Fail "argument of real conversion must be int"
233 :     (* end case *))
234 : jhr 70 (* end case *))
235 :    
236 : jhr 81 (* typecheck a list of expressions returning a list of AST expressions and a list
237 :     * of types of the expressions.
238 :     *)
239 :     and checkExprList (env, cxt, exprs) = let
240 :     fun chk (e, (es, tys)) = let
241 :     val (e, ty) = checkExpr (env, cxt, e)
242 :     in
243 :     (e::es, ty::tys)
244 :     end
245 :     in
246 :     List.foldr chk ([], []) exprs
247 :     end
248 :    
249 : jhr 72 fun checkVarDecl (env, cxt, kind, d) = (case d
250 : jhr 86 of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
251 : jhr 72 | PT.VD_Decl(ty, x, e) => let
252 : jhr 81 val ty = checkTy (cxt, ty)
253 : jhr 72 val x' = Var.new (x, kind, ty)
254 :     val (e', ty') = checkExpr (env, cxt, e)
255 :     in
256 :     (* FIXME: check types *)
257 : jhr 81 (x, x', e')
258 : jhr 72 end
259 :     (* end case *))
260 :    
261 : jhr 70 (* typecheck a statement and translate it to AST *)
262 : jhr 71 fun checkStmt (env, cxt, s) = (case s
263 : jhr 86 of PT.S_Mark m => checkStmt (withEnvAndContext (env, cxt, m))
264 : jhr 72 | PT.S_Block stms => let
265 :     fun chk (_, [], stms) = AST.S_Block(List.rev stms)
266 :     | chk (env, s::ss, stms) = let
267 :     val (s', env') = checkStmt (env, cxt, s)
268 :     in
269 : jhr 81 chk (env', ss, s'::stms)
270 : jhr 72 end
271 :     in
272 :     (chk (env, stms, []), env)
273 :     end
274 :     | PT.S_Decl vd => let
275 : jhr 81 val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
276 : jhr 72 in
277 : jhr 81 (AST.S_Decl(AST.VD_Decl(x', e)), Env.insertLocal(env, x, x'))
278 : jhr 72 end
279 :     | PT.S_IfThen(e, s) => let
280 :     val (e', ty) = checkExpr (env, cxt, e)
281 : jhr 81 val (s', _) = checkStmt (env, cxt, s)
282 : jhr 72 in
283 :     (* check that condition has bool type *)
284 :     case ty
285 :     of Ty.T_Bool => ()
286 :     | _ => raise Fail "condition not boolean type"
287 :     (* end case *);
288 :     (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
289 :     end
290 :     | PT.S_IfThenElse(e, s1, s2) => let
291 :     val (e', ty) = checkExpr (env, cxt, e)
292 : jhr 81 val (s1', _) = checkStmt (env, cxt, s1)
293 :     val (s2', _) = checkStmt (env, cxt, s2)
294 : jhr 72 in
295 :     (* check that condition has bool type *)
296 :     case ty
297 :     of Ty.T_Bool => ()
298 :     | _ => raise Fail "condition not boolean type"
299 :     (* end case *);
300 :     (AST.S_IfThenElse(e', s1', s2'), env)
301 :     end
302 :     | PT.S_Assign(x, e) => (case Env.findVar (env, x)
303 :     of NONE => raise Fail "undefined variable"
304 :     | SOME x' => let
305 :     val (e', ty) = checkExpr (env, cxt, e)
306 :     in
307 :     (* FIXME: check types *)
308 :     (* check that x' is mutable *)
309 :     case Var.kindOf x'
310 :     of Var.ActorStateVar => ()
311 :     | Var.LocalVar => ()
312 :     | _ => raise Fail "assignment to immutable variable"
313 :     (* end case *);
314 :     (AST.S_Assign(x', e'), env)
315 :     end
316 :     (* end case *))
317 :     | PT.S_New(actor, args) => let
318 : jhr 81 val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
319 :     val (args', tys') = ListPair.unzip argsAndTys'
320 : jhr 72 in
321 :     (* FIXME: check that actor is defined and has the argument types match *)
322 : jhr 81 (AST.S_New(actor, args'), env)
323 : jhr 72 end
324 :     | PT.S_Die => (AST.S_Die, env)
325 :     | PT.S_Stabilize => (AST.S_Stabilize, env)
326 : jhr 70 (* end case *))
327 :    
328 : jhr 82 fun checkParams (env, cxt, params) = let
329 :     fun chkParam (env, cxt, param) = (case param
330 : jhr 86 of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
331 : jhr 82 | PT.P_Param(ty, x) => let
332 :     val x' = Var.new(x, AST.ActorParam, checkTy (cxt, ty))
333 :     in
334 :     (x', Env.insertLocal(env, x, x'))
335 :     end
336 :     (* end case *))
337 :     fun chk (param, (xs, env)) = let
338 :     val (x, env) = chkParam (env, cxt, param)
339 :     in
340 :     (x::xs, env)
341 :     end
342 :     in
343 :     (* FIXME: need to check for multiple occurences of the same parameter name! *)
344 :     List.foldr chk ([], env) params
345 :     end
346 :    
347 :     fun checkMethod (env, cxt, meth) = (case meth
348 : jhr 86 of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
349 : jhr 82 | PT.M_Method(name, body) => let
350 :     val (body, _) = checkStmt(env, cxt, body)
351 :     in
352 :     AST.M_Method(name, body)
353 :     end
354 :     (* end case *))
355 :    
356 :     fun checkActor (env, cxt, {name, params, state, methods}) = let
357 :     (* check the actor parameters *)
358 :     val (params, env) = checkParams (env, cxt, params)
359 :     (* check the actor state variable definitions *)
360 :     val (vds, env) = let
361 :     fun checkStateVar (vd, (vds, env)) = let
362 :     val (x, x', e') = checkVarDecl (env, cxt, AST.ActorStateVar, vd)
363 :     in
364 :     (AST.VD_Decl(x', e')::vds, Env.insertLocal(env, x, x'))
365 :     end
366 :     val (vds, env) = List.foldl checkStateVar ([], env) state
367 :     in
368 :     (List.rev vds, env)
369 :     end
370 :     (* check the actor methods *)
371 :     val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
372 :     in
373 :     AST.D_Actor{name = name, params = params, state = vds, methods = methods}
374 :     end
375 :    
376 : jhr 89 fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
377 :     | checkCreate (env, cxt, PT.C_Create(actor, args)) = let
378 :     val (args, tys) = checkExprList (env, cxt, args)
379 :     in
380 :     (* FIXME: check against actor definition *)
381 :     AST.C_Create(actor, args)
382 :     end
383 :    
384 :     fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
385 :     | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
386 :     val (e1', ty1) = checkExpr (env, cxt, e1)
387 :     val (e2', ty2) = checkExpr (env, cxt, e2)
388 :     val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
389 :     val env' = Env.insertLocal(env, x, x')
390 :     in
391 :     case (ty1, ty2)
392 :     of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), env')
393 :     | _ => err(cxt, [
394 :     S "range expressions must have integer type\n",
395 :     S " but found: ", TY ty1, S " .. ", TY ty2, S "\n"
396 :     ])
397 :     (* end case *)
398 :     end
399 :    
400 :     fun checkIters (env, cxt, iters) = let
401 :     fun chk (env, [], iters) = (List.rev iters, env)
402 :     | chk (env, iter::rest, iters) = let
403 :     val (iter, env) = checkIter (env, cxt, iter)
404 :     in
405 :     chk (env, rest, iter::iters)
406 :     end
407 :     in
408 :     chk (env, iters, [])
409 :     end
410 :    
411 : jhr 71 fun checkDecl (env, cxt, d) = (case d
412 : jhr 86 of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
413 : jhr 72 | PT.D_Input(ty, x, optExp) => let
414 : jhr 71 val ty = checkTy(cxt, ty)
415 :     val x' = Var.new(x, Var.InputVar, ty)
416 :     val dcl = (case optExp
417 :     of NONE => AST.D_Input(x', NONE)
418 :     | SOME e => let
419 :     val (e', ty') = checkExpr (env, cxt, e)
420 :     in
421 : jhr 89 if U.matchType (ty, ty')
422 :     then AST.D_Input(x', SOME e')
423 :     else err(cxt, [
424 :     S "definition of ", V x', S " has wrong type\n",
425 :     S " expected: ", TY ty, S "\n",
426 :     S " but found: ", TY ty', S "\n"
427 :     ])
428 : jhr 71 end
429 :     (* end case *))
430 :     in
431 :     (dcl, Env.insertGlobal(env, x, x'))
432 :     end
433 : jhr 72 | PT.D_Var vd => let
434 : jhr 81 val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
435 : jhr 72 in
436 : jhr 81 (AST.D_Var(AST.VD_Decl(x', e')), Env.insertGlobal(env, x, x'))
437 : jhr 72 end
438 : jhr 82 | PT.D_Actor arg => (checkActor(env, cxt, arg), env)
439 : jhr 89 | PT.D_InitialArray(create, iterators) => let
440 :     val (iterators, env') = checkIters (env, cxt, iterators)
441 :     val create = checkCreate (env', cxt, create)
442 :     in
443 :     (AST.D_InitialArray(create, iterators), env)
444 :     end
445 :     | PT.D_InitialCollection(create, iterators) => let
446 :     val (iterators, env') = checkIters (env, cxt, iterators)
447 :     val create = checkCreate (env', cxt, create)
448 :     in
449 :     (AST.D_InitialCollection(create, iterators), env)
450 :     end
451 : jhr 70 (* end case *))
452 :    
453 : jhr 86 fun check errStrm (PT.Program{span, tree}) = let
454 :     val cxt = (errStrm, span)
455 : jhr 81 fun chk (env, [], dcls') = AST.Program(List.rev dcls')
456 :     | chk (env, dcl::dcls, dcls') = let
457 : jhr 86 val (dcl', env) = checkDecl (env, cxt, dcl)
458 : jhr 81 in
459 :     chk (env, dcls, dcl'::dcls')
460 :     end
461 :     in
462 :     chk (Basis.env, tree, [])
463 :     end
464 : jhr 70
465 : jhr 69 end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0