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

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 99 - (view) (download)

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

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