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 89 - (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 :     fun resolveOverload (rator, argTys, args, candidates) = let
107 :     fun tryCandidates [] = raise Fail(concat[
108 :     "unable to resolve overloaded operator \"", Atom.toString rator, "\""
109 :     ])
110 :     | tryCandidates (x::xs) = let
111 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
112 :     in
113 :     if U.tryMatchTypes(domTy, argTys)
114 :     then (AST.E_Apply(x, tyArgs, args, rngTy), rngTy)
115 :     else tryCandidates xs
116 :     end
117 :     in
118 :     tryCandidates candidates
119 :     end
120 :    
121 : jhr 70 (* typecheck an expression and translate it to AST *)
122 : jhr 71 fun checkExpr (env, cxt, e) = (case e
123 : jhr 86 of PT.E_Mark m => checkExpr (withEnvAndContext (env, cxt, m))
124 : jhr 71 | PT.E_Var x => (case Env.findVar (env, x)
125 : jhr 81 of SOME x' => let
126 :     val (args, ty) = Util.instantiate(Var.typeOf x')
127 :     in
128 :     (AST.E_Var(x', args, ty), ty)
129 :     end
130 : jhr 88 | NONE => err(cxt, [S "undeclared variable ", A x])
131 : jhr 71 (* end case *))
132 :     | PT.E_Lit lit => checkLit lit
133 : jhr 81 | PT.E_OrElse(e1, e2) => let
134 :     val (e1', ty1) = checkExpr(env, cxt, e1)
135 :     val (e2', ty2) = checkExpr(env, cxt, e2)
136 :     in
137 :     case (ty1, ty2)
138 :     of (Ty.T_Bool, Ty.T_Bool) =>
139 :     (AST.E_Cond(e1', AST.E_Lit(Literal.Bool true), e2'), Ty.T_Bool)
140 :     | _ => raise Fail "arguments to \"||\" must have bool type"
141 :     (* end case *)
142 :     end
143 :     | PT.E_AndAlso(e1, e2) => let
144 :     val (e1', ty1) = checkExpr(env, cxt, e1)
145 :     val (e2', ty2) = checkExpr(env, cxt, e2)
146 :     in
147 :     case (ty1, ty2)
148 :     of (Ty.T_Bool, Ty.T_Bool) =>
149 :     (AST.E_Cond(e1', e2', AST.E_Lit(Literal.Bool false)), Ty.T_Bool)
150 :     | _ => raise Fail "arguments to \"||\" must have bool type"
151 :     (* end case *)
152 :     end
153 :     | PT.E_BinOp(e1, rator, e2) => let
154 :     val (e1', ty1) = checkExpr(env, cxt, e1)
155 :     val (e2', ty2) = checkExpr(env, cxt, e2)
156 :     in
157 :     case Basis.findOp rator
158 :     of [rator] => let
159 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
160 :     in
161 :     if U.matchTypes(domTy, [ty1, ty2])
162 :     then (AST.E_Apply(rator, tyArgs, [e1', e2'], rngTy), rngTy)
163 : jhr 89 else err (cxt, [
164 :     S "type error for binary operator \"", V rator, S "\"\n",
165 :     S " expected: ", TYS domTy, S "\n",
166 :     S " but found: ", TYS[ty1, ty2], S "\n"
167 : jhr 85 ])
168 : jhr 81 end
169 : jhr 85 | ovldList => resolveOverload (rator, [ty1, ty2], [e1', e2'], ovldList)
170 : jhr 81 (* end case *)
171 :     end
172 :     | PT.E_UnaryOp(rator, e) => let
173 :     val (e', ty) = checkExpr(env, cxt, e)
174 :     in
175 :     case Basis.findOp rator
176 :     of [rator] => let
177 :     val (tyArgs, Ty.T_Fun([domTy], rngTy)) = Util.instantiate(Var.typeOf rator)
178 :     in
179 :     if U.matchType(domTy, ty)
180 :     then (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
181 : jhr 89 else err (cxt, [
182 :     S "type error for unary operator \"", V rator, S "\"\n",
183 :     S " expected: ", TY domTy, S "\n",
184 :     S " but found: ", TY ty, S "\n"
185 : jhr 85 ])
186 : jhr 81 end
187 : jhr 85 | ovldList => resolveOverload (rator, [ty], [e'], ovldList)
188 : jhr 81 (* end case *)
189 :     end
190 :     | PT.E_Tuple args => let
191 :     val (args, tys) = checkExprList (env, cxt, args)
192 :     in
193 :     raise Fail "E_Tuple not yet implemented"
194 :     end
195 :     | PT.E_Apply(f, args) => let
196 :     val (args, tys) = checkExprList (env, cxt, args)
197 :     in
198 :     case Env.findVar (env, f)
199 :     of SOME f => (case Util.instantiate(Var.typeOf f)
200 :     of (tyArgs, Ty.T_Fun(domTy, rngTy)) =>
201 :     if U.matchTypes(domTy, tys)
202 :     then (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
203 : jhr 88 else err(cxt, [
204 :     S "type error in application of ", V f, S "\n",
205 :     S " expected: ", TYS domTy, S "\n",
206 :     S " but found: ", TYS tys, S "\n"
207 :     ])
208 : jhr 81 | _ => raise Fail "application of non-function"
209 :     (* end case *))
210 :     | NONE => raise Fail "unknown function"
211 :     (* end case *)
212 :     end
213 : jhr 86 | PT.E_Cons args => let
214 :     val (args, ty::tys) = checkExprList (env, cxt, args)
215 : jhr 81 in
216 : jhr 86 case Util.prune ty
217 :     of Ty.T_Tensor shape => let
218 :     fun chkTy ty' = U.matchType(ty, ty')
219 :     val resTy = Ty.T_Tensor(Ty.shapeExt(shape, Ty.DimConst(List.length args)))
220 : jhr 83 in
221 : jhr 86 if List.all chkTy tys
222 :     then (AST.E_Cons args, resTy)
223 :     else raise Fail "arguments of tensor construction must have same type"
224 : jhr 83 end
225 : jhr 86 | _ => raise Fail "Invalid argument type for tensor construction"
226 : jhr 83 (* end case *)
227 : jhr 81 end
228 : jhr 86 | PT.E_Real e => (case checkExpr (env, cxt, e)
229 :     of (e', Ty.T_Int) =>
230 :     (AST.E_Apply(BasisVars.i2r, [], [e'], Ty.realTy), Ty.realTy)
231 :     | _ => raise Fail "argument of real conversion must be int"
232 :     (* end case *))
233 : jhr 70 (* end case *))
234 :    
235 : jhr 81 (* typecheck a list of expressions returning a list of AST expressions and a list
236 :     * of types of the expressions.
237 :     *)
238 :     and checkExprList (env, cxt, exprs) = let
239 :     fun chk (e, (es, tys)) = let
240 :     val (e, ty) = checkExpr (env, cxt, e)
241 :     in
242 :     (e::es, ty::tys)
243 :     end
244 :     in
245 :     List.foldr chk ([], []) exprs
246 :     end
247 :    
248 : jhr 72 fun checkVarDecl (env, cxt, kind, d) = (case d
249 : jhr 86 of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
250 : jhr 72 | PT.VD_Decl(ty, x, e) => let
251 : jhr 81 val ty = checkTy (cxt, ty)
252 : jhr 72 val x' = Var.new (x, kind, ty)
253 :     val (e', ty') = checkExpr (env, cxt, e)
254 :     in
255 :     (* FIXME: check types *)
256 : jhr 81 (x, x', e')
257 : jhr 72 end
258 :     (* end case *))
259 :    
260 : jhr 70 (* typecheck a statement and translate it to AST *)
261 : jhr 71 fun checkStmt (env, cxt, s) = (case s
262 : jhr 86 of PT.S_Mark m => checkStmt (withEnvAndContext (env, cxt, m))
263 : jhr 72 | PT.S_Block stms => let
264 :     fun chk (_, [], stms) = AST.S_Block(List.rev stms)
265 :     | chk (env, s::ss, stms) = let
266 :     val (s', env') = checkStmt (env, cxt, s)
267 :     in
268 : jhr 81 chk (env', ss, s'::stms)
269 : jhr 72 end
270 :     in
271 :     (chk (env, stms, []), env)
272 :     end
273 :     | PT.S_Decl vd => let
274 : jhr 81 val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
275 : jhr 72 in
276 : jhr 81 (AST.S_Decl(AST.VD_Decl(x', e)), Env.insertLocal(env, x, x'))
277 : jhr 72 end
278 :     | PT.S_IfThen(e, s) => let
279 :     val (e', ty) = checkExpr (env, cxt, e)
280 : jhr 81 val (s', _) = checkStmt (env, cxt, s)
281 : jhr 72 in
282 :     (* check that condition has bool type *)
283 :     case ty
284 :     of Ty.T_Bool => ()
285 :     | _ => raise Fail "condition not boolean type"
286 :     (* end case *);
287 :     (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
288 :     end
289 :     | PT.S_IfThenElse(e, s1, s2) => let
290 :     val (e', ty) = checkExpr (env, cxt, e)
291 : jhr 81 val (s1', _) = checkStmt (env, cxt, s1)
292 :     val (s2', _) = checkStmt (env, cxt, s2)
293 : jhr 72 in
294 :     (* check that condition has bool type *)
295 :     case ty
296 :     of Ty.T_Bool => ()
297 :     | _ => raise Fail "condition not boolean type"
298 :     (* end case *);
299 :     (AST.S_IfThenElse(e', s1', s2'), env)
300 :     end
301 :     | PT.S_Assign(x, e) => (case Env.findVar (env, x)
302 :     of NONE => raise Fail "undefined variable"
303 :     | SOME x' => let
304 :     val (e', ty) = checkExpr (env, cxt, e)
305 :     in
306 :     (* FIXME: check types *)
307 :     (* check that x' is mutable *)
308 :     case Var.kindOf x'
309 :     of Var.ActorStateVar => ()
310 :     | Var.LocalVar => ()
311 :     | _ => raise Fail "assignment to immutable variable"
312 :     (* end case *);
313 :     (AST.S_Assign(x', e'), env)
314 :     end
315 :     (* end case *))
316 :     | PT.S_New(actor, args) => let
317 : jhr 81 val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
318 :     val (args', tys') = ListPair.unzip argsAndTys'
319 : jhr 72 in
320 :     (* FIXME: check that actor is defined and has the argument types match *)
321 : jhr 81 (AST.S_New(actor, args'), env)
322 : jhr 72 end
323 :     | PT.S_Die => (AST.S_Die, env)
324 :     | PT.S_Stabilize => (AST.S_Stabilize, env)
325 : jhr 70 (* end case *))
326 :    
327 : jhr 82 fun checkParams (env, cxt, params) = let
328 :     fun chkParam (env, cxt, param) = (case param
329 : jhr 86 of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
330 : jhr 82 | PT.P_Param(ty, x) => let
331 :     val x' = Var.new(x, AST.ActorParam, checkTy (cxt, ty))
332 :     in
333 :     (x', Env.insertLocal(env, x, x'))
334 :     end
335 :     (* end case *))
336 :     fun chk (param, (xs, env)) = let
337 :     val (x, env) = chkParam (env, cxt, param)
338 :     in
339 :     (x::xs, env)
340 :     end
341 :     in
342 :     (* FIXME: need to check for multiple occurences of the same parameter name! *)
343 :     List.foldr chk ([], env) params
344 :     end
345 :    
346 :     fun checkMethod (env, cxt, meth) = (case meth
347 : jhr 86 of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
348 : jhr 82 | PT.M_Method(name, body) => let
349 :     val (body, _) = checkStmt(env, cxt, body)
350 :     in
351 :     AST.M_Method(name, body)
352 :     end
353 :     (* end case *))
354 :    
355 :     fun checkActor (env, cxt, {name, params, state, methods}) = let
356 :     (* check the actor parameters *)
357 :     val (params, env) = checkParams (env, cxt, params)
358 :     (* check the actor state variable definitions *)
359 :     val (vds, env) = let
360 :     fun checkStateVar (vd, (vds, env)) = let
361 :     val (x, x', e') = checkVarDecl (env, cxt, AST.ActorStateVar, vd)
362 :     in
363 :     (AST.VD_Decl(x', e')::vds, Env.insertLocal(env, x, x'))
364 :     end
365 :     val (vds, env) = List.foldl checkStateVar ([], env) state
366 :     in
367 :     (List.rev vds, env)
368 :     end
369 :     (* check the actor methods *)
370 :     val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
371 :     in
372 :     AST.D_Actor{name = name, params = params, state = vds, methods = methods}
373 :     end
374 :    
375 : jhr 89 fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
376 :     | checkCreate (env, cxt, PT.C_Create(actor, args)) = let
377 :     val (args, tys) = checkExprList (env, cxt, args)
378 :     in
379 :     (* FIXME: check against actor definition *)
380 :     AST.C_Create(actor, args)
381 :     end
382 :    
383 :     fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
384 :     | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
385 :     val (e1', ty1) = checkExpr (env, cxt, e1)
386 :     val (e2', ty2) = checkExpr (env, cxt, e2)
387 :     val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
388 :     val env' = Env.insertLocal(env, x, x')
389 :     in
390 :     case (ty1, ty2)
391 :     of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), env')
392 :     | _ => err(cxt, [
393 :     S "range expressions must have integer type\n",
394 :     S " but found: ", TY ty1, S " .. ", TY ty2, S "\n"
395 :     ])
396 :     (* end case *)
397 :     end
398 :    
399 :     fun checkIters (env, cxt, iters) = let
400 :     fun chk (env, [], iters) = (List.rev iters, env)
401 :     | chk (env, iter::rest, iters) = let
402 :     val (iter, env) = checkIter (env, cxt, iter)
403 :     in
404 :     chk (env, rest, iter::iters)
405 :     end
406 :     in
407 :     chk (env, iters, [])
408 :     end
409 :    
410 : jhr 71 fun checkDecl (env, cxt, d) = (case d
411 : jhr 86 of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
412 : jhr 72 | PT.D_Input(ty, x, optExp) => let
413 : jhr 71 val ty = checkTy(cxt, ty)
414 :     val x' = Var.new(x, Var.InputVar, ty)
415 :     val dcl = (case optExp
416 :     of NONE => AST.D_Input(x', NONE)
417 :     | SOME e => let
418 :     val (e', ty') = checkExpr (env, cxt, e)
419 :     in
420 : jhr 89 if U.matchType (ty, ty')
421 :     then AST.D_Input(x', SOME e')
422 :     else err(cxt, [
423 :     S "definition of ", V x', S " has wrong type\n",
424 :     S " expected: ", TY ty, S "\n",
425 :     S " but found: ", TY ty', S "\n"
426 :     ])
427 : jhr 71 end
428 :     (* end case *))
429 :     in
430 :     (dcl, Env.insertGlobal(env, x, x'))
431 :     end
432 : jhr 72 | PT.D_Var vd => let
433 : jhr 81 val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
434 : jhr 72 in
435 : jhr 81 (AST.D_Var(AST.VD_Decl(x', e')), Env.insertGlobal(env, x, x'))
436 : jhr 72 end
437 : jhr 82 | PT.D_Actor arg => (checkActor(env, cxt, arg), env)
438 : jhr 89 | PT.D_InitialArray(create, iterators) => let
439 :     val (iterators, env') = checkIters (env, cxt, iterators)
440 :     val create = checkCreate (env', cxt, create)
441 :     in
442 :     (AST.D_InitialArray(create, iterators), env)
443 :     end
444 :     | PT.D_InitialCollection(create, iterators) => let
445 :     val (iterators, env') = checkIters (env, cxt, iterators)
446 :     val create = checkCreate (env', cxt, create)
447 :     in
448 :     (AST.D_InitialCollection(create, iterators), env)
449 :     end
450 : jhr 70 (* end case *))
451 :    
452 : jhr 86 fun check errStrm (PT.Program{span, tree}) = let
453 :     val cxt = (errStrm, span)
454 : jhr 81 fun chk (env, [], dcls') = AST.Program(List.rev dcls')
455 :     | chk (env, dcl::dcls, dcls') = let
456 : jhr 86 val (dcl', env) = checkDecl (env, cxt, dcl)
457 : jhr 81 in
458 :     chk (env, dcls, dcl'::dcls')
459 :     end
460 :     in
461 :     chk (Basis.env, tree, [])
462 :     end
463 : jhr 70
464 : jhr 69 end

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