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 1923 - (view) (download)

1 : jhr 69 (* typechecker.sml
2 :     *
3 : jhr 435 * COPYRIGHT (c) 2010 The Diderot Project (http://diderot-language.cs.uchicago.edu)
4 : jhr 69 * All rights reserved.
5 : jhr 228 *
6 : jhr 1116 * TODO:
7 :     * check that variables are not redefined in the same scope
8 :     * int --> real type promotion
9 :     * sequence operations
10 : jhr 69 *)
11 :    
12 :     structure Typechecker : sig
13 :    
14 : jhr 88 exception Error
15 :    
16 : jhr 86 val check : Error.err_stream -> ParseTree.program -> AST.program
17 : jhr 69
18 :     end = struct
19 :    
20 : jhr 1116 structure BV = BasisVars
21 : jhr 70 structure PT = ParseTree
22 : jhr 69 structure Ty = Types
23 : jhr 96 structure TU = TypeUtil
24 : jhr 81 structure U = Util
25 : jhr 69
26 : jhr 511 datatype scope = GlobalScope | StrandScope | MethodScope | InitScope
27 : jhr 169
28 : jhr 1116 type env = {
29 :     scope : scope,
30 :     bindings : Error.location AtomMap.map,
31 :     env : Env.env
32 :     }
33 : jhr 228
34 : jhr 1116 type context = Error.err_stream * Error.span
35 : jhr 228
36 : jhr 1116 (* start a new scope *)
37 :     fun strandScope {scope, bindings, env} =
38 :     {scope=StrandScope, bindings=AtomMap.empty, env=env}
39 :     fun methodScope {scope, bindings, env} =
40 :     {scope=MethodScope, bindings=AtomMap.empty, env=env}
41 :     fun initScope {scope, bindings, env} =
42 :     {scope=InitScope, bindings=AtomMap.empty, env=env}
43 :     fun blockScope {scope, bindings, env} =
44 :     {scope=scope, bindings=AtomMap.empty, env=env}
45 :    
46 :     fun inStrand {scope=StrandScope, bindings, env} = true
47 : jhr 511 | inStrand {scope=MethodScope, ...} = true
48 :     | inStrand _ = false
49 : jhr 228
50 : jhr 1116 fun insertLocal ({scope, bindings, env}, cxt, x, x') = {
51 :     scope=scope,
52 :     bindings = AtomMap.insert(bindings, x, Error.location cxt),
53 :     env=Env.insertLocal(env, x, x')
54 :     }
55 :     fun insertGlobal ({scope, bindings, env}, cxt, x, x') = {
56 :     scope=scope,
57 :     bindings = AtomMap.insert(bindings, x, Error.location cxt),
58 :     env=Env.insertGlobal(env, x, x')
59 :     }
60 : jhr 228
61 : jhr 88 exception Error
62 :    
63 : jhr 86 fun withContext ((errStrm, _), {span, tree}) =
64 :     ((errStrm, span), tree)
65 :     fun withEnvAndContext (env, (errStrm, _), {span, tree}) =
66 :     (env, (errStrm, span), tree)
67 :    
68 : jhr 88 fun error ((errStrm, span), msg) = (
69 :     Error.errorAt(errStrm, span, msg);
70 :     raise Error)
71 : jhr 86
72 : jhr 88 datatype token
73 :     = S of string | A of Atom.atom
74 :     | V of AST.var | TY of Types.ty | TYS of Types.ty list
75 :    
76 :     fun err (cxt, toks) = let
77 :     fun tok2str (S s) = s
78 :     | tok2str (A a) = Atom.toString a
79 :     | tok2str (V x) = Var.nameOf x
80 : jhr 96 | tok2str (TY ty) = TU.toString ty
81 : jhr 88 | tok2str (TYS []) = "()"
82 : jhr 96 | tok2str (TYS[ty]) = TU.toString ty
83 : jhr 88 | tok2str (TYS tys) = String.concat[
84 : jhr 96 "(", String.concatWith " * " (List.map TU.toString tys), ")"
85 : jhr 88 ]
86 :     in
87 :     error(cxt, List.map tok2str toks)
88 :     end
89 :    
90 : jhr 1116 fun checkForRedef (env : env, cxt : context, x) = (case AtomMap.find(#bindings env,x)
91 :     of SOME loc => err (cxt, [
92 :     S "redefinition of ", A x, S ", previous definition at ",
93 :     S(Error.locToString loc)
94 :     ])
95 :     | NONE => ()
96 :     (* end case *))
97 :    
98 : jhr 83 val realZero = AST.E_Lit(Literal.Float(FloatLit.zero true))
99 :    
100 : jhr 70 (* check a differentiation level, which muse be >= 0 *)
101 :     fun checkDiff (cxt, k) =
102 :     if (k < 0)
103 : jhr 1116 then err (cxt, [S "differentiation must be >= 0"])
104 : jhr 75 else Ty.DiffConst(IntInf.toInt k)
105 : jhr 70
106 : jhr 1116 (* check a dimension, which must be 1, 2 or 3 *)
107 : jhr 70 fun checkDim (cxt, d) =
108 : jhr 1116 if (d < 1) orelse (3 < d)
109 :     then err (cxt, [S "invalid dimension; must be 1, 2, or 3"])
110 : jhr 75 else Ty.DimConst(IntInf.toInt d)
111 : jhr 70
112 :     (* check a shape *)
113 : jhr 1116 fun checkShape (cxt, shape) = let
114 :     fun checkDim d =
115 :     if (d <= 1)
116 :     then err (cxt, [S "invalid tensor-shape dimension; must be > 1"])
117 :     else Ty.DimConst(IntInf.toInt d)
118 : jhr 70 in
119 : jhr 1116 Ty.Shape(List.map checkDim shape)
120 : jhr 70 end
121 :    
122 : jhr 69 (* check the well-formedness of a type and translate it to an AST type *)
123 : jhr 70 fun checkTy (cxt, ty) = (case ty
124 : jhr 86 of PT.T_Mark m => checkTy(withContext(cxt, m))
125 : jhr 70 | PT.T_Bool => Ty.T_Bool
126 :     | PT.T_Int => Ty.T_Int
127 :     | PT.T_Real => Ty.realTy
128 :     | PT.T_String => Ty.T_String
129 :     | PT.T_Vec n => (* NOTE: the parser guarantees that 2 <= n <= 4 *)
130 :     Ty.vecTy(IntInf.toInt n)
131 :     | PT.T_Kernel k => Ty.T_Kernel(checkDiff(cxt, k))
132 :     | PT.T_Field{diff, dim, shape} => Ty.T_Field{
133 :     diff = checkDiff (cxt, diff),
134 :     dim = checkDim (cxt, dim),
135 :     shape = checkShape (cxt, shape)
136 :     }
137 :     | PT.T_Tensor shape => Ty.T_Tensor(checkShape(cxt, shape))
138 :     | PT.T_Image{dim, shape} => Ty.T_Image{
139 :     dim = checkDim (cxt, dim),
140 :     shape = checkShape (cxt, shape)
141 :     }
142 : jhr 1640 | PT.T_Seq(ty, dim) => let
143 :     val ty = checkTy(cxt, ty)
144 :     in
145 :     if TU.isValueType ty
146 :     then Ty.T_Sequence(ty, checkDim (cxt, dim))
147 :     else err(cxt, [S "elements of sequence types must be value types"])
148 :     end
149 : jhr 69 (* end case *))
150 :    
151 : jhr 71 fun checkLit lit = (case lit
152 :     of (Literal.Int _) => (AST.E_Lit lit, Ty.T_Int)
153 :     | (Literal.Float _) => (AST.E_Lit lit, Ty.realTy)
154 :     | (Literal.String s) => (AST.E_Lit lit, Ty.T_String)
155 :     | (Literal.Bool _) => (AST.E_Lit lit, Ty.T_Bool)
156 :     (* end case *))
157 :    
158 : jhr 85 (* resolve overloading: we use a simple scheme that selects the first operator in the
159 :     * list that matches the argument types.
160 :     *)
161 : jhr 1116 fun resolveOverload (_, rator, _, _, []) = raise Fail(concat[
162 :     "resolveOverload: \"", Atom.toString rator, "\" has no candidates"
163 :     ])
164 :     | resolveOverload (cxt, rator, argTys, args, candidates) = let
165 : jhr 91 fun tryCandidates [] = err(cxt, [
166 :     S "unable to resolve overloaded operator \"", A rator, S "\"\n",
167 :     S " argument type is: ", TYS argTys, S "\n"
168 : jhr 85 ])
169 :     | tryCandidates (x::xs) = let
170 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
171 :     in
172 :     if U.tryMatchTypes(domTy, argTys)
173 :     then (AST.E_Apply(x, tyArgs, args, rngTy), rngTy)
174 :     else tryCandidates xs
175 :     end
176 :     in
177 :     tryCandidates candidates
178 :     end
179 :    
180 : jhr 70 (* typecheck an expression and translate it to AST *)
181 : jhr 169 fun checkExpr (env : env, cxt, e) = (case e
182 : jhr 86 of PT.E_Mark m => checkExpr (withEnvAndContext (env, cxt, m))
183 : jhr 169 | PT.E_Var x => (case Env.findVar (#env env, x)
184 : jhr 171 of SOME x' => (AST.E_Var x', Var.monoTypeOf x')
185 : jhr 88 | NONE => err(cxt, [S "undeclared variable ", A x])
186 : jhr 71 (* end case *))
187 :     | PT.E_Lit lit => checkLit lit
188 : jhr 81 | PT.E_OrElse(e1, e2) => let
189 :     val (e1', ty1) = checkExpr(env, cxt, e1)
190 :     val (e2', ty2) = checkExpr(env, cxt, e2)
191 :     in
192 :     case (ty1, ty2)
193 :     of (Ty.T_Bool, Ty.T_Bool) =>
194 : jhr 416 (AST.E_Cond(e1', AST.E_Lit(Literal.Bool true), e2', Ty.T_Bool), Ty.T_Bool)
195 : jhr 99 | _ => err (cxt, [S "arguments to \"||\" must have bool type"])
196 : jhr 81 (* end case *)
197 :     end
198 :     | PT.E_AndAlso(e1, e2) => let
199 :     val (e1', ty1) = checkExpr(env, cxt, e1)
200 :     val (e2', ty2) = checkExpr(env, cxt, e2)
201 :     in
202 :     case (ty1, ty2)
203 :     of (Ty.T_Bool, Ty.T_Bool) =>
204 : jhr 416 (AST.E_Cond(e1', e2', AST.E_Lit(Literal.Bool false), Ty.T_Bool), Ty.T_Bool)
205 : jhr 99 | _ => err (cxt, [S "arguments to \"&&\" must have bool type"])
206 : jhr 81 (* end case *)
207 :     end
208 : jhr 370 | PT.E_Cond(e1, cond, e2) => let
209 :     val (e1', ty1) = checkExpr(env, cxt, e1)
210 :     val (e2', ty2) = checkExpr(env, cxt, e2)
211 :     in
212 :     case checkExpr(env, cxt, cond)
213 :     of (cond', Ty.T_Bool) =>
214 :     if U.matchType(ty1, ty2)
215 : jhr 416 then (AST.E_Cond(cond', e1', e2', ty1), ty1)
216 : jhr 370 else err (cxt, [
217 :     S "type do not match in conditional expression\n",
218 : jhr 1116 S " true branch: ", TY ty1, S "\n",
219 : jhr 370 S " false branch: ", TY ty2
220 :     ])
221 :     | (_, ty') => err (cxt, [S "expected bool type, but found ", TY ty'])
222 :     (* end case *)
223 :     end
224 : jhr 81 | PT.E_BinOp(e1, rator, e2) => let
225 :     val (e1', ty1) = checkExpr(env, cxt, e1)
226 :     val (e2', ty2) = checkExpr(env, cxt, e2)
227 :     in
228 : jhr 1116 if Atom.same(rator, BasisNames.op_dot)
229 :     (* we have to handle inner product as a special case, because out type
230 :     * system cannot express the constraint that the type is
231 :     * ALL[sigma1, d1, sigma2] . tensor[sigma1, d1] * tensor[d1, sigma2] -> tensor[sigma1, sigma2]
232 :     *)
233 :     then (case (TU.prune ty1, TU.prune ty2)
234 :     of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_)), Ty.T_Tensor(s2 as Ty.Shape(d2::dd2))) => let
235 :     val (dd1, d1) = let
236 :     fun splitLast (prefix, [d]) = (List.rev prefix, d)
237 :     | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
238 :     | splitLast (_, []) = raise Fail "impossible"
239 :     in
240 :     splitLast ([], dd1)
241 :     end
242 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_inner)
243 :     val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
244 :     in
245 :     if U.matchDim(d1, d2)
246 :     andalso U.matchTypes(domTy, [ty1, ty2])
247 :     andalso U.matchType(rngTy, resTy)
248 :     then (AST.E_Apply(BV.op_inner, tyArgs, [e1', e2'], rngTy), rngTy)
249 :     else err (cxt, [
250 :     S "type error for arguments of binary operator \"•\"\n",
251 :     S " found: ", TYS[ty1, ty2], S "\n"
252 :     ])
253 :     end
254 :     | (ty1, ty2) => err (cxt, [
255 :     S "type error for arguments of binary operator \"•\"\n",
256 :     S " found: ", TYS[ty1, ty2], S "\n"
257 :     ])
258 :     (* end case *))
259 :     else (case Env.findFunc (#env env, rator)
260 :     of [rator] => let
261 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
262 :     in
263 :     if U.matchTypes(domTy, [ty1, ty2])
264 :     then (AST.E_Apply(rator, tyArgs, [e1', e2'], rngTy), rngTy)
265 :     else err (cxt, [
266 :     S "type error for binary operator \"", V rator, S "\"\n",
267 :     S " expected: ", TYS domTy, S "\n",
268 :     S " but found: ", TYS[ty1, ty2]
269 :     ])
270 :     end
271 :     | ovldList => resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
272 :     (* end case *))
273 : jhr 81 end
274 :     | PT.E_UnaryOp(rator, e) => let
275 :     val (e', ty) = checkExpr(env, cxt, e)
276 :     in
277 : jhr 1116 case Env.findFunc (#env env, rator)
278 : jhr 81 of [rator] => let
279 : jhr 381 val (tyArgs, Ty.T_Fun([domTy], rngTy)) = U.instantiate(Var.typeOf rator)
280 : jhr 81 in
281 :     if U.matchType(domTy, ty)
282 :     then (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
283 : jhr 89 else err (cxt, [
284 :     S "type error for unary operator \"", V rator, S "\"\n",
285 :     S " expected: ", TY domTy, S "\n",
286 : jhr 1116 S " but found: ", TY ty
287 : jhr 85 ])
288 : jhr 81 end
289 : jhr 91 | ovldList => resolveOverload (cxt, rator, [ty], [e'], ovldList)
290 : jhr 81 (* end case *)
291 :     end
292 : jhr 381 | PT.E_Slice(e, indices) => let
293 :     val (e', ty) = checkExpr (env, cxt, e)
294 :     fun checkIndex NONE = NONE
295 :     | checkIndex (SOME e) = let
296 :     val (e', ty) = checkExpr (env, cxt, e)
297 :     in
298 :     if U.matchType(ty, Ty.T_Int)
299 :     then (SOME e')
300 :     else err (cxt, [
301 :     S "type error in index expression\n",
302 : jhr 1116 S " expected int, but found: ", TY ty
303 : jhr 381 ])
304 :     end
305 :     val indices' = List.map checkIndex indices
306 :     val order = List.length indices'
307 : jhr 399 val expectedTy = TU.mkTensorTy order
308 :     val resultTy = TU.slice(expectedTy, List.map Option.isSome indices')
309 : jhr 381 in
310 : jhr 399 if U.matchType(ty, expectedTy)
311 : jhr 381 then ()
312 :     else err (cxt, [
313 :     S "type error in slice operation\n",
314 :     S " expected: ", S(Int.toString order), S "-order tensor\n",
315 : jhr 1116 S " but found: ", TY ty
316 : jhr 381 ]);
317 : jhr 399 (AST.E_Slice(e', indices', resultTy), resultTy)
318 : jhr 381 end
319 : jhr 1116 | PT.E_Subscript(e1, e2) => let
320 :     val (e1', ty1) = checkExpr (env, cxt, e1)
321 :     val (e2', ty2) = checkExpr (env, cxt, e2)
322 : jhr 1640 val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.subscript)
323 : jhr 1116 in
324 : jhr 1640 if U.matchTypes(domTy, [ty1, ty2])
325 :     then let
326 :     val exp = AST.E_Apply(BasisVars.subscript, tyArgs, [e1', e2'], rngTy)
327 :     in
328 :     (exp, rngTy)
329 :     end
330 :     else err (cxt, [
331 :     S "type error for sequence subscript\n",
332 :     S " expected: ", TYS domTy, S "\n",
333 :     S " but found: ", TYS[ty1, ty2]
334 :     ])
335 : jhr 1116 end
336 :     | PT.E_Apply(e, args) => let
337 :     fun stripMark (PT.E_Mark{tree, ...}) = stripMark tree
338 :     | stripMark e = e
339 :     val (args, tys) = checkExprList (env, cxt, args)
340 :     fun checkFieldApp (e1', ty1) = (case (args, tys)
341 :     of ([e2'], [ty2]) => let
342 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) =
343 : jhr 1923 Util.instantiate(Var.typeOf BV.op_probe)
344 : jhr 1116 in
345 :     if U.matchTypes(domTy, [ty1, ty2])
346 : jhr 1923 then (AST.E_Apply(BV.op_probe, tyArgs, [e1', e2'], rngTy), rngTy)
347 : jhr 1116 else err (cxt, [
348 :     S "type error for field application\n",
349 :     S " expected: ", TYS domTy, S "\n",
350 :     S " but found: ", TYS[ty1, ty2]
351 :     ])
352 :     end
353 :     | _ => err(cxt, [S "badly formed field application"])
354 :     (* end case *))
355 :     in
356 :     case stripMark e
357 :     of PT.E_Var f => (case Env.findVar (#env env, f)
358 :     of SOME f' => checkFieldApp (AST.E_Var f', Var.monoTypeOf f')
359 :     | NONE => (case Env.findFunc (#env env, f)
360 :     of [] => err(cxt, [S "unknown function ", A f])
361 :     | [f] =>
362 :     if (inStrand env) andalso (Basis.isRestricted f)
363 :     then err(cxt, [
364 :     S "use of restricted operation ", V f,
365 :     S " in strand body"
366 :     ])
367 :     else (case Util.instantiate(Var.typeOf f)
368 :     of (tyArgs, Ty.T_Fun(domTy, rngTy)) =>
369 :     if U.matchTypes(domTy, tys)
370 :     then (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
371 :     else err(cxt, [
372 :     S "type error in application of ", V f, S "\n",
373 :     S " expected: ", TYS domTy, S "\n",
374 :     S " but found: ", TYS tys
375 :     ])
376 :     | _ => err(cxt, [S "application of non-function ", V f])
377 :     (* end case *))
378 :     | ovldList => resolveOverload (cxt, f, tys, args, ovldList)
379 :     (* end case *))
380 :     (* end case *))
381 :     | _ => checkFieldApp (checkExpr (env, cxt, e))
382 :     (* end case *)
383 :     end
384 : jhr 81 | PT.E_Tuple args => let
385 :     val (args, tys) = checkExprList (env, cxt, args)
386 :     in
387 : jhr 1116 raise Fail "E_Tuple not yet implemented" (* FIXME *)
388 : jhr 81 end
389 : jhr 1116 | PT.E_Sequence args => let
390 : jhr 1640 val (args, ty::tys) = checkExprList (env, cxt, args)
391 : jhr 81 in
392 : jhr 1640 if TU.isValueType(TU.pruneHead ty)
393 :     then let
394 :     fun chkTy ty' = U.matchType(ty, ty')
395 :     val resTy = Ty.T_Sequence(ty, Ty.DimConst(List.length args))
396 :     in
397 :     if List.all chkTy tys
398 :     then (AST.E_Cons args, resTy)
399 :     else err(cxt, [S "arguments of sequence expression must have same type"])
400 :     end
401 :     else err(cxt, [S "sequence expression of non-value argument type"])
402 : jhr 81 end
403 : jhr 86 | PT.E_Cons args => let
404 :     val (args, ty::tys) = checkExprList (env, cxt, args)
405 : jhr 81 in
406 : jhr 96 case TU.pruneHead ty
407 : jhr 475 of ty as Ty.T_Tensor shape => let
408 :     val Ty.Shape dd = TU.pruneShape shape (* NOTE: this may fail if we allow user polymorphism *)
409 : jhr 86 fun chkTy ty' = U.matchType(ty, ty')
410 : jhr 475 val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
411 : jhr 83 in
412 : jhr 86 if List.all chkTy tys
413 :     then (AST.E_Cons args, resTy)
414 : jhr 99 else err(cxt, [S "arguments of tensor construction must have same type"])
415 : jhr 83 end
416 : jhr 99 | _ => err(cxt, [S "Invalid argument type for tensor construction"])
417 : jhr 83 (* end case *)
418 : jhr 81 end
419 : jhr 86 | PT.E_Real e => (case checkExpr (env, cxt, e)
420 :     of (e', Ty.T_Int) =>
421 : jhr 1116 (AST.E_Apply(BV.i2r, [], [e'], Ty.realTy), Ty.realTy)
422 : jhr 99 | _ => err(cxt, [S "argument of real conversion must be int"])
423 : jhr 86 (* end case *))
424 : jhr 1116 | PT.E_Id d => let
425 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
426 :     Util.instantiate(Var.typeOf(BV.identity))
427 :     in
428 :     if U.matchType(Ty.T_Tensor(checkShape(cxt, [d,d])), rngTy)
429 :     then (AST.E_Apply(BV.identity, tyArgs, [], rngTy), rngTy)
430 :     else raise Fail "impossible"
431 :     end
432 :     | PT.E_Zero dd => let
433 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
434 :     Util.instantiate(Var.typeOf(BV.zero))
435 :     in
436 :     if U.matchType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
437 :     then (AST.E_Apply(BV.zero, tyArgs, [], rngTy), rngTy)
438 :     else raise Fail "impossible"
439 :     end
440 : jhr 70 (* end case *))
441 :    
442 : jhr 81 (* typecheck a list of expressions returning a list of AST expressions and a list
443 :     * of types of the expressions.
444 :     *)
445 :     and checkExprList (env, cxt, exprs) = let
446 :     fun chk (e, (es, tys)) = let
447 :     val (e, ty) = checkExpr (env, cxt, e)
448 :     in
449 :     (e::es, ty::tys)
450 :     end
451 :     in
452 :     List.foldr chk ([], []) exprs
453 :     end
454 :    
455 : jhr 72 fun checkVarDecl (env, cxt, kind, d) = (case d
456 : jhr 86 of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
457 : jhr 72 | PT.VD_Decl(ty, x, e) => let
458 : jhr 81 val ty = checkTy (cxt, ty)
459 : jhr 72 val x' = Var.new (x, kind, ty)
460 :     val (e', ty') = checkExpr (env, cxt, e)
461 :     in
462 : jhr 99 (* FIXME: this check is not flexible enough; should allow lhs type to support
463 :     * fewer levels of differentiation than rhs provides.
464 :     *)
465 :     if U.matchType(ty, ty')
466 :     then (x, x', e')
467 :     else err(cxt, [
468 :     S "type of variable ", A x,
469 :     S " does not match type of initializer\n",
470 :     S " expected: ", TY ty, S "\n",
471 : jhr 1116 S " but found: ", TY ty'
472 : jhr 99 ])
473 : jhr 72 end
474 :     (* end case *))
475 :    
476 : jhr 70 (* typecheck a statement and translate it to AST *)
477 : jhr 71 fun checkStmt (env, cxt, s) = (case s
478 : jhr 86 of PT.S_Mark m => checkStmt (withEnvAndContext (env, cxt, m))
479 : jhr 72 | PT.S_Block stms => let
480 :     fun chk (_, [], stms) = AST.S_Block(List.rev stms)
481 :     | chk (env, s::ss, stms) = let
482 :     val (s', env') = checkStmt (env, cxt, s)
483 :     in
484 : jhr 81 chk (env', ss, s'::stms)
485 : jhr 72 end
486 :     in
487 : jhr 1116 (chk (blockScope env, stms, []), env)
488 : jhr 72 end
489 :     | PT.S_Decl vd => let
490 : jhr 1116 val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
491 : jhr 72 in
492 : jhr 1116 checkForRedef (env, cxt, x);
493 :     (AST.S_Decl(AST.VD_Decl(x', e)), insertLocal(env, cxt, x, x'))
494 : jhr 72 end
495 :     | PT.S_IfThen(e, s) => let
496 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
497 : jhr 81 val (s', _) = checkStmt (env, cxt, s)
498 : jhr 72 in
499 :     (* check that condition has bool type *)
500 :     case ty
501 :     of Ty.T_Bool => ()
502 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
503 : jhr 72 (* end case *);
504 :     (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
505 :     end
506 :     | PT.S_IfThenElse(e, s1, s2) => let
507 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
508 : jhr 81 val (s1', _) = checkStmt (env, cxt, s1)
509 :     val (s2', _) = checkStmt (env, cxt, s2)
510 : jhr 72 in
511 :     (* check that condition has bool type *)
512 :     case ty
513 :     of Ty.T_Bool => ()
514 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
515 : jhr 72 (* end case *);
516 :     (AST.S_IfThenElse(e', s1', s2'), env)
517 :     end
518 : jhr 228 | PT.S_Assign(x, e) => (case Env.findVar (#env env, x)
519 : jhr 99 of NONE => err(cxt, [
520 :     S "undefined variable ", A x
521 :     ])
522 : jhr 72 | SOME x' => let
523 : jhr 99 (* FIXME: check for polymorphic variables *)
524 :     val ([], ty) = Var.typeOf x'
525 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
526 : jhr 72 in
527 : jhr 99 if U.matchType(ty, ty')
528 :     then (x, x', e')
529 :     else err(cxt, [
530 :     S "type of assigned variable ", A x,
531 :     S " does not match type of rhs\n",
532 :     S " expected: ", TY ty, S "\n",
533 : jhr 1116 S " but found: ", TY ty'
534 : jhr 99 ]);
535 : jhr 72 (* check that x' is mutable *)
536 :     case Var.kindOf x'
537 : jhr 511 of Var.StrandStateVar => ()
538 :     | Var.StrandOutputVar => ()
539 : jhr 72 | Var.LocalVar => ()
540 : jhr 99 | _ => err(cxt, [
541 :     S "assignment to immutable variable ", A x
542 :     ])
543 : jhr 72 (* end case *);
544 :     (AST.S_Assign(x', e'), env)
545 :     end
546 :     (* end case *))
547 : jhr 1296 | PT.S_OpAssign(x, rator, e) => (case Env.findVar (#env env, x)
548 :     of SOME x' => let
549 :     val e1' = AST.E_Var x'
550 :     val ty1 = Var.monoTypeOf x'
551 :     val (e2', ty2) = checkExpr(env, cxt, e)
552 :     val ovldList = Env.findFunc (#env env, rator)
553 :     val (rhs, _) = resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
554 :     in
555 :     (AST.S_Assign(x', rhs), env)
556 :     end
557 :     | NONE => err(cxt, [S "undeclared variable ", A x, S " on lhs of ", A rator])
558 :     (* end case *))
559 : jhr 511 | PT.S_New(strand, args) => let
560 : jhr 228 val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
561 : jhr 81 val (args', tys') = ListPair.unzip argsAndTys'
562 : jhr 72 in
563 : jhr 228 case #scope env
564 :     of MethodScope => ()
565 :     | InitScope => ()
566 : jhr 511 | _ => err(cxt, [S "invalid scope for new strand"])
567 : jhr 228 (* end case *);
568 : jhr 511 (* FIXME: check that strand is defined and has the argument types match *)
569 :     (AST.S_New(strand, args'), env)
570 : jhr 72 end
571 : jhr 228 | PT.S_Die => (
572 :     case #scope env
573 : jhr 235 of MethodScope => ()
574 :     | _ => err(cxt, [S "\"die\" statment outside of method"])
575 : jhr 228 (* end case *);
576 :     (AST.S_Die, env))
577 :     | PT.S_Stabilize => (
578 :     case #scope env
579 : jhr 235 of MethodScope => ()
580 :     | _ => err(cxt, [S "\"stabilize\" statment outside of method"])
581 : jhr 228 (* end case *);
582 :     (AST.S_Stabilize, env))
583 : jhr 1640 | PT.S_Print args => let
584 :     fun chkArg e = let
585 :     val (e', ty) = checkExpr (env, cxt, e)
586 :     in
587 :     if TU.isValueType ty
588 :     then ()
589 :     else err(cxt, [
590 :     S "expected value type in print, but found ", TY ty
591 :     ]);
592 :     e'
593 :     end
594 :     val args' = List.map chkArg args
595 :     in
596 :     (AST.S_Print args', env)
597 :     end
598 : jhr 70 (* end case *))
599 :    
600 : jhr 82 fun checkParams (env, cxt, params) = let
601 :     fun chkParam (env, cxt, param) = (case param
602 : jhr 86 of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
603 : jhr 82 | PT.P_Param(ty, x) => let
604 : jhr 511 val x' = Var.new(x, AST.StrandParam, checkTy (cxt, ty))
605 : jhr 82 in
606 : jhr 1116 checkForRedef (env, cxt, x);
607 :     (x', insertLocal(env, cxt, x, x'))
608 : jhr 82 end
609 :     (* end case *))
610 :     fun chk (param, (xs, env)) = let
611 :     val (x, env) = chkParam (env, cxt, param)
612 :     in
613 :     (x::xs, env)
614 :     end
615 :     in
616 :     (* FIXME: need to check for multiple occurences of the same parameter name! *)
617 :     List.foldr chk ([], env) params
618 :     end
619 :    
620 :     fun checkMethod (env, cxt, meth) = (case meth
621 : jhr 86 of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
622 : jhr 82 | PT.M_Method(name, body) => let
623 : jhr 228 val (body, _) = checkStmt(methodScope env, cxt, body)
624 : jhr 82 in
625 :     AST.M_Method(name, body)
626 :     end
627 :     (* end case *))
628 :    
629 : jhr 511 fun checkStrand (env, cxt, {name, params, state, methods}) = let
630 :     (* check the strand parameters *)
631 : jhr 82 val (params, env) = checkParams (env, cxt, params)
632 : jhr 511 (* check the strand state variable definitions *)
633 : jhr 82 val (vds, env) = let
634 : jhr 164 fun checkStateVar ((isOut, vd), (vds, env)) = let
635 : jhr 511 val kind = if isOut then AST.StrandOutputVar else AST.StrandStateVar
636 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, kind, vd)
637 : jhr 82 in
638 : jhr 228 (* check that output variables have value types *)
639 :     if isOut andalso not(TU.isValueType(Var.monoTypeOf x'))
640 :     then err(cxt, [
641 :     S "output variable ", V x', S " has non-value type ",
642 :     TY(Var.monoTypeOf x')
643 :     ])
644 :     else ();
645 : jhr 1116 checkForRedef (env, cxt, x);
646 :     (AST.VD_Decl(x', e')::vds, insertLocal(env, cxt, x, x'))
647 : jhr 82 end
648 :     val (vds, env) = List.foldl checkStateVar ([], env) state
649 :     in
650 :     (List.rev vds, env)
651 :     end
652 : jhr 511 (* check the strand methods *)
653 : jhr 82 val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
654 : jhr 1444 (* get the list of methods defined by the user *)
655 :     val methodNames = List.map (fn (AST.M_Method(name, _)) => name) methods
656 : jhr 1116 (* if the stabilize method is not provided, add one *)
657 : jhr 1640 val methods = if List.exists (fn StrandUtil.Stabilize => true | _ => false) methodNames
658 : jhr 1116 then methods
659 : jhr 1640 else methods @ [AST.M_Method(StrandUtil.Stabilize, AST.S_Block[])]
660 : jhr 82 in
661 : jhr 1444 (* FIXME: should check for duplicate method definitions *)
662 : jhr 1640 if not(List.exists (fn StrandUtil.Update => true | _ => false) methodNames)
663 : jhr 1116 then err(cxt, [S "strand ", A name, S " is missing an update method"])
664 :     else ();
665 : jhr 511 AST.D_Strand{name = name, params = params, state = vds, methods = methods}
666 : jhr 82 end
667 :    
668 : jhr 89 fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
669 : jhr 511 | checkCreate (env, cxt, PT.C_Create(strand, args)) = let
670 : jhr 228 val (args, tys) = checkExprList (env, cxt, args)
671 : jhr 89 in
672 : jhr 511 (* FIXME: check against strand definition *)
673 :     AST.C_Create(strand, args)
674 : jhr 89 end
675 :    
676 : jhr 1116 fun checkIters (env0, cxt, iters) = let
677 :     (* check an iteration range specification from the initially clause. We do the checking
678 :     * of the expressions using env0, which does not have any of the iteration variables in
679 :     * it (the iteration is rectangular), but we also accumulate the iteration bindings,
680 :     * which are used to create the final environment for checking the create call.
681 :     *)
682 :     fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
683 :     | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
684 :     val (e1', ty1) = checkExpr (env, cxt, e1)
685 :     val (e2', ty2) = checkExpr (env, cxt, e2)
686 :     val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
687 : jhr 89 in
688 : jhr 1116 case (ty1, ty2)
689 :     of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), (x, x'))
690 :     | _ => err(cxt, [
691 :     S "range expressions must have integer type\n",
692 :     S " but found: ", TY ty1, S " .. ", TY ty2
693 :     ])
694 :     (* end case *)
695 : jhr 89 end
696 : jhr 1116 fun chk ([], iters, bindings) =
697 :     (List.rev iters, List.foldl (fn ((x, x'), env) => insertLocal(env, cxt, x, x')) env0 bindings)
698 :     | chk (iter::rest, iters, bindings) = let
699 :     val (iter, binding) = checkIter (env0, cxt, iter)
700 :     in
701 :     chk (rest, iter::iters, binding::bindings)
702 :     end
703 : jhr 89 in
704 : jhr 1116 chk (iters, [], [])
705 : jhr 89 end
706 :    
707 : jhr 71 fun checkDecl (env, cxt, d) = (case d
708 : jhr 86 of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
709 : jhr 1301 | PT.D_Input(ty, x, desc, optExp) => let
710 :     (* FIXME: need to do something with the description *)
711 : jhr 71 val ty = checkTy(cxt, ty)
712 :     val x' = Var.new(x, Var.InputVar, ty)
713 :     val dcl = (case optExp
714 : jhr 1301 of NONE => AST.D_Input(x', desc, NONE)
715 : jhr 71 | SOME e => let
716 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
717 : jhr 71 in
718 : jhr 89 if U.matchType (ty, ty')
719 : jhr 1301 then AST.D_Input(x', desc, SOME e')
720 : jhr 89 else err(cxt, [
721 :     S "definition of ", V x', S " has wrong type\n",
722 :     S " expected: ", TY ty, S "\n",
723 : jhr 1116 S " but found: ", TY ty'
724 : jhr 89 ])
725 : jhr 71 end
726 :     (* end case *))
727 :     in
728 : jhr 228 (* check that input variables have value types *)
729 :     if not(TU.isValueType ty)
730 :     then err(cxt, [S "input variable ", V x', S " has non-value type ", TY ty])
731 :     else ();
732 : jhr 1116 checkForRedef (env, cxt, x);
733 :     (dcl, insertGlobal(env, cxt, x, x'))
734 : jhr 71 end
735 : jhr 72 | PT.D_Var vd => let
736 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
737 : jhr 72 in
738 : jhr 1116 checkForRedef (env, cxt, x);
739 :     (AST.D_Var(AST.VD_Decl(x', e')), insertGlobal(env, cxt, x, x'))
740 : jhr 72 end
741 : jhr 511 | PT.D_Strand arg => (checkStrand(strandScope env, cxt, arg), env)
742 : jhr 89 | PT.D_InitialArray(create, iterators) => let
743 : jhr 228 val env = initScope env
744 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
745 :     val create = checkCreate (env', cxt, create)
746 :     in
747 :     (AST.D_InitialArray(create, iterators), env)
748 :     end
749 :     | PT.D_InitialCollection(create, iterators) => let
750 : jhr 228 val env = initScope env
751 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
752 :     val create = checkCreate (env', cxt, create)
753 :     in
754 :     (AST.D_InitialCollection(create, iterators), env)
755 :     end
756 : jhr 70 (* end case *))
757 :    
758 : jhr 1301 (* reorder the declarations so that the input variables come first *)
759 :     fun reorderDecls dcls = let
760 :     fun isInput (AST.D_Input _) = true
761 :     | isInput _ = false
762 :     val (inputs, others) = List.partition isInput dcls
763 :     in
764 :     inputs @ others
765 :     end
766 :    
767 : jhr 86 fun check errStrm (PT.Program{span, tree}) = let
768 :     val cxt = (errStrm, span)
769 : jhr 1301 fun chk (env, [], dcls') = AST.Program(reorderDecls(List.rev dcls'))
770 : jhr 81 | chk (env, dcl::dcls, dcls') = let
771 : jhr 86 val (dcl', env) = checkDecl (env, cxt, dcl)
772 : jhr 81 in
773 :     chk (env, dcls, dcl'::dcls')
774 :     end
775 :     in
776 : jhr 1116 chk ({scope=GlobalScope, bindings=AtomMap.empty, env=Basis.env}, tree, [])
777 : jhr 81 end
778 : jhr 70
779 : jhr 69 end

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