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 1116 - (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 1116 | PT.T_Seq(ty, dim) => Ty.T_Sequence(checkTy(cxt, ty), checkDim (cxt, dim))
143 : jhr 69 (* end case *))
144 :    
145 : jhr 71 fun checkLit lit = (case lit
146 :     of (Literal.Int _) => (AST.E_Lit lit, Ty.T_Int)
147 :     | (Literal.Float _) => (AST.E_Lit lit, Ty.realTy)
148 :     | (Literal.String s) => (AST.E_Lit lit, Ty.T_String)
149 :     | (Literal.Bool _) => (AST.E_Lit lit, Ty.T_Bool)
150 :     (* end case *))
151 :    
152 : jhr 85 (* resolve overloading: we use a simple scheme that selects the first operator in the
153 :     * list that matches the argument types.
154 :     *)
155 : jhr 1116 fun resolveOverload (_, rator, _, _, []) = raise Fail(concat[
156 :     "resolveOverload: \"", Atom.toString rator, "\" has no candidates"
157 :     ])
158 :     | resolveOverload (cxt, rator, argTys, args, candidates) = let
159 : jhr 91 fun tryCandidates [] = err(cxt, [
160 :     S "unable to resolve overloaded operator \"", A rator, S "\"\n",
161 :     S " argument type is: ", TYS argTys, S "\n"
162 : jhr 85 ])
163 :     | tryCandidates (x::xs) = let
164 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
165 :     in
166 :     if U.tryMatchTypes(domTy, argTys)
167 :     then (AST.E_Apply(x, tyArgs, args, rngTy), rngTy)
168 :     else tryCandidates xs
169 :     end
170 :     in
171 :     tryCandidates candidates
172 :     end
173 :    
174 : jhr 70 (* typecheck an expression and translate it to AST *)
175 : jhr 169 fun checkExpr (env : env, cxt, e) = (case e
176 : jhr 86 of PT.E_Mark m => checkExpr (withEnvAndContext (env, cxt, m))
177 : jhr 169 | PT.E_Var x => (case Env.findVar (#env env, x)
178 : jhr 171 of SOME x' => (AST.E_Var x', Var.monoTypeOf x')
179 : jhr 88 | NONE => err(cxt, [S "undeclared variable ", A x])
180 : jhr 71 (* end case *))
181 :     | PT.E_Lit lit => checkLit lit
182 : jhr 81 | PT.E_OrElse(e1, e2) => let
183 :     val (e1', ty1) = checkExpr(env, cxt, e1)
184 :     val (e2', ty2) = checkExpr(env, cxt, e2)
185 :     in
186 :     case (ty1, ty2)
187 :     of (Ty.T_Bool, Ty.T_Bool) =>
188 : jhr 416 (AST.E_Cond(e1', AST.E_Lit(Literal.Bool true), e2', Ty.T_Bool), Ty.T_Bool)
189 : jhr 99 | _ => err (cxt, [S "arguments to \"||\" must have bool type"])
190 : jhr 81 (* end case *)
191 :     end
192 :     | PT.E_AndAlso(e1, e2) => let
193 :     val (e1', ty1) = checkExpr(env, cxt, e1)
194 :     val (e2', ty2) = checkExpr(env, cxt, e2)
195 :     in
196 :     case (ty1, ty2)
197 :     of (Ty.T_Bool, Ty.T_Bool) =>
198 : jhr 416 (AST.E_Cond(e1', e2', AST.E_Lit(Literal.Bool false), Ty.T_Bool), Ty.T_Bool)
199 : jhr 99 | _ => err (cxt, [S "arguments to \"&&\" must have bool type"])
200 : jhr 81 (* end case *)
201 :     end
202 : jhr 370 | PT.E_Cond(e1, cond, e2) => let
203 :     val (e1', ty1) = checkExpr(env, cxt, e1)
204 :     val (e2', ty2) = checkExpr(env, cxt, e2)
205 :     in
206 :     case checkExpr(env, cxt, cond)
207 :     of (cond', Ty.T_Bool) =>
208 :     if U.matchType(ty1, ty2)
209 : jhr 416 then (AST.E_Cond(cond', e1', e2', ty1), ty1)
210 : jhr 370 else err (cxt, [
211 :     S "type do not match in conditional expression\n",
212 : jhr 1116 S " true branch: ", TY ty1, S "\n",
213 : jhr 370 S " false branch: ", TY ty2
214 :     ])
215 :     | (_, ty') => err (cxt, [S "expected bool type, but found ", TY ty'])
216 :     (* end case *)
217 :     end
218 : jhr 81 | PT.E_BinOp(e1, rator, e2) => let
219 :     val (e1', ty1) = checkExpr(env, cxt, e1)
220 :     val (e2', ty2) = checkExpr(env, cxt, e2)
221 :     in
222 : jhr 1116 if Atom.same(rator, BasisNames.op_dot)
223 :     (* we have to handle inner product as a special case, because out type
224 :     * system cannot express the constraint that the type is
225 :     * ALL[sigma1, d1, sigma2] . tensor[sigma1, d1] * tensor[d1, sigma2] -> tensor[sigma1, sigma2]
226 :     *)
227 :     then (case (TU.prune ty1, TU.prune ty2)
228 :     of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_)), Ty.T_Tensor(s2 as Ty.Shape(d2::dd2))) => let
229 :     val (dd1, d1) = let
230 :     fun splitLast (prefix, [d]) = (List.rev prefix, d)
231 :     | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
232 :     | splitLast (_, []) = raise Fail "impossible"
233 :     in
234 :     splitLast ([], dd1)
235 :     end
236 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_inner)
237 :     val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
238 :     in
239 :     if U.matchDim(d1, d2)
240 :     andalso U.matchTypes(domTy, [ty1, ty2])
241 :     andalso U.matchType(rngTy, resTy)
242 :     then (AST.E_Apply(BV.op_inner, tyArgs, [e1', e2'], rngTy), rngTy)
243 :     else err (cxt, [
244 :     S "type error for arguments of binary operator \"•\"\n",
245 :     S " found: ", TYS[ty1, ty2], S "\n"
246 :     ])
247 :     end
248 :     | (ty1, ty2) => err (cxt, [
249 :     S "type error for arguments of binary operator \"•\"\n",
250 :     S " found: ", TYS[ty1, ty2], S "\n"
251 :     ])
252 :     (* end case *))
253 :     else (case Env.findFunc (#env env, rator)
254 :     of [rator] => let
255 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
256 :     in
257 :     if U.matchTypes(domTy, [ty1, ty2])
258 :     then (AST.E_Apply(rator, tyArgs, [e1', e2'], rngTy), rngTy)
259 :     else err (cxt, [
260 :     S "type error for binary operator \"", V rator, S "\"\n",
261 :     S " expected: ", TYS domTy, S "\n",
262 :     S " but found: ", TYS[ty1, ty2]
263 :     ])
264 :     end
265 :     | ovldList => resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
266 :     (* end case *))
267 : jhr 81 end
268 :     | PT.E_UnaryOp(rator, e) => let
269 :     val (e', ty) = checkExpr(env, cxt, e)
270 :     in
271 : jhr 1116 case Env.findFunc (#env env, rator)
272 : jhr 81 of [rator] => let
273 : jhr 381 val (tyArgs, Ty.T_Fun([domTy], rngTy)) = U.instantiate(Var.typeOf rator)
274 : jhr 81 in
275 :     if U.matchType(domTy, ty)
276 :     then (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
277 : jhr 89 else err (cxt, [
278 :     S "type error for unary operator \"", V rator, S "\"\n",
279 :     S " expected: ", TY domTy, S "\n",
280 : jhr 1116 S " but found: ", TY ty
281 : jhr 85 ])
282 : jhr 81 end
283 : jhr 91 | ovldList => resolveOverload (cxt, rator, [ty], [e'], ovldList)
284 : jhr 81 (* end case *)
285 :     end
286 : jhr 381 | PT.E_Slice(e, indices) => let
287 :     val (e', ty) = checkExpr (env, cxt, e)
288 :     fun checkIndex NONE = NONE
289 :     | checkIndex (SOME e) = let
290 :     val (e', ty) = checkExpr (env, cxt, e)
291 :     in
292 :     if U.matchType(ty, Ty.T_Int)
293 :     then (SOME e')
294 :     else err (cxt, [
295 :     S "type error in index expression\n",
296 : jhr 1116 S " expected int, but found: ", TY ty
297 : jhr 381 ])
298 :     end
299 :     val indices' = List.map checkIndex indices
300 :     val order = List.length indices'
301 : jhr 399 val expectedTy = TU.mkTensorTy order
302 :     val resultTy = TU.slice(expectedTy, List.map Option.isSome indices')
303 : jhr 381 in
304 : jhr 399 if U.matchType(ty, expectedTy)
305 : jhr 381 then ()
306 :     else err (cxt, [
307 :     S "type error in slice operation\n",
308 :     S " expected: ", S(Int.toString order), S "-order tensor\n",
309 : jhr 1116 S " but found: ", TY ty
310 : jhr 381 ]);
311 : jhr 399 (AST.E_Slice(e', indices', resultTy), resultTy)
312 : jhr 381 end
313 : jhr 1116 | PT.E_Subscript(e1, e2) => let
314 :     val (e1', ty1) = checkExpr (env, cxt, e1)
315 :     val (e2', ty2) = checkExpr (env, cxt, e2)
316 :     in
317 :     raise Fail "E_Subscript not yet implemented" (* FIXME *)
318 :     end
319 :     | PT.E_Apply(e, args) => let
320 :     fun stripMark (PT.E_Mark{tree, ...}) = stripMark tree
321 :     | stripMark e = e
322 :     val (args, tys) = checkExprList (env, cxt, args)
323 :     fun checkFieldApp (e1', ty1) = (case (args, tys)
324 :     of ([e2'], [ty2]) => let
325 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) =
326 :     Util.instantiate(Var.typeOf BV.op_at)
327 :     in
328 :     if U.matchTypes(domTy, [ty1, ty2])
329 :     then (AST.E_Apply(BV.op_at, tyArgs, [e1', e2'], rngTy), rngTy)
330 :     else err (cxt, [
331 :     S "type error for field application\n",
332 :     S " expected: ", TYS domTy, S "\n",
333 :     S " but found: ", TYS[ty1, ty2]
334 :     ])
335 :     end
336 :     | _ => err(cxt, [S "badly formed field application"])
337 :     (* end case *))
338 :     in
339 :     case stripMark e
340 :     of PT.E_Var f => (case Env.findVar (#env env, f)
341 :     of SOME f' => checkFieldApp (AST.E_Var f', Var.monoTypeOf f')
342 :     | NONE => (case Env.findFunc (#env env, f)
343 :     of [] => err(cxt, [S "unknown function ", A f])
344 :     | [f] =>
345 :     if (inStrand env) andalso (Basis.isRestricted f)
346 :     then err(cxt, [
347 :     S "use of restricted operation ", V f,
348 :     S " in strand body"
349 :     ])
350 :     else (case Util.instantiate(Var.typeOf f)
351 :     of (tyArgs, Ty.T_Fun(domTy, rngTy)) =>
352 :     if U.matchTypes(domTy, tys)
353 :     then (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
354 :     else err(cxt, [
355 :     S "type error in application of ", V f, S "\n",
356 :     S " expected: ", TYS domTy, S "\n",
357 :     S " but found: ", TYS tys
358 :     ])
359 :     | _ => err(cxt, [S "application of non-function ", V f])
360 :     (* end case *))
361 :     | ovldList => resolveOverload (cxt, f, tys, args, ovldList)
362 :     (* end case *))
363 :     (* end case *))
364 :     | _ => checkFieldApp (checkExpr (env, cxt, e))
365 :     (* end case *)
366 :     end
367 : jhr 81 | PT.E_Tuple args => let
368 :     val (args, tys) = checkExprList (env, cxt, args)
369 :     in
370 : jhr 1116 raise Fail "E_Tuple not yet implemented" (* FIXME *)
371 : jhr 81 end
372 : jhr 1116 | PT.E_Sequence args => let
373 : jhr 81 val (args, tys) = checkExprList (env, cxt, args)
374 :     in
375 : jhr 1116 raise Fail "E_Sequence not yet implemented" (* FIXME *)
376 : jhr 81 end
377 : jhr 86 | PT.E_Cons args => let
378 :     val (args, ty::tys) = checkExprList (env, cxt, args)
379 : jhr 81 in
380 : jhr 96 case TU.pruneHead ty
381 : jhr 475 of ty as Ty.T_Tensor shape => let
382 :     val Ty.Shape dd = TU.pruneShape shape (* NOTE: this may fail if we allow user polymorphism *)
383 : jhr 86 fun chkTy ty' = U.matchType(ty, ty')
384 : jhr 475 val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
385 : jhr 83 in
386 : jhr 86 if List.all chkTy tys
387 :     then (AST.E_Cons args, resTy)
388 : jhr 99 else err(cxt, [S "arguments of tensor construction must have same type"])
389 : jhr 83 end
390 : jhr 99 | _ => err(cxt, [S "Invalid argument type for tensor construction"])
391 : jhr 83 (* end case *)
392 : jhr 81 end
393 : jhr 86 | PT.E_Real e => (case checkExpr (env, cxt, e)
394 :     of (e', Ty.T_Int) =>
395 : jhr 1116 (AST.E_Apply(BV.i2r, [], [e'], Ty.realTy), Ty.realTy)
396 : jhr 99 | _ => err(cxt, [S "argument of real conversion must be int"])
397 : jhr 86 (* end case *))
398 : jhr 1116 | PT.E_Id d => let
399 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
400 :     Util.instantiate(Var.typeOf(BV.identity))
401 :     in
402 :     if U.matchType(Ty.T_Tensor(checkShape(cxt, [d,d])), rngTy)
403 :     then (AST.E_Apply(BV.identity, tyArgs, [], rngTy), rngTy)
404 :     else raise Fail "impossible"
405 :     end
406 :     | PT.E_Zero dd => let
407 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
408 :     Util.instantiate(Var.typeOf(BV.zero))
409 :     in
410 :     if U.matchType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
411 :     then (AST.E_Apply(BV.zero, tyArgs, [], rngTy), rngTy)
412 :     else raise Fail "impossible"
413 :     end
414 : jhr 70 (* end case *))
415 :    
416 : jhr 81 (* typecheck a list of expressions returning a list of AST expressions and a list
417 :     * of types of the expressions.
418 :     *)
419 :     and checkExprList (env, cxt, exprs) = let
420 :     fun chk (e, (es, tys)) = let
421 :     val (e, ty) = checkExpr (env, cxt, e)
422 :     in
423 :     (e::es, ty::tys)
424 :     end
425 :     in
426 :     List.foldr chk ([], []) exprs
427 :     end
428 :    
429 : jhr 72 fun checkVarDecl (env, cxt, kind, d) = (case d
430 : jhr 86 of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
431 : jhr 72 | PT.VD_Decl(ty, x, e) => let
432 : jhr 81 val ty = checkTy (cxt, ty)
433 : jhr 72 val x' = Var.new (x, kind, ty)
434 :     val (e', ty') = checkExpr (env, cxt, e)
435 :     in
436 : jhr 99 (* FIXME: this check is not flexible enough; should allow lhs type to support
437 :     * fewer levels of differentiation than rhs provides.
438 :     *)
439 :     if U.matchType(ty, ty')
440 :     then (x, x', e')
441 :     else err(cxt, [
442 :     S "type of variable ", A x,
443 :     S " does not match type of initializer\n",
444 :     S " expected: ", TY ty, S "\n",
445 : jhr 1116 S " but found: ", TY ty'
446 : jhr 99 ])
447 : jhr 72 end
448 :     (* end case *))
449 :    
450 : jhr 70 (* typecheck a statement and translate it to AST *)
451 : jhr 71 fun checkStmt (env, cxt, s) = (case s
452 : jhr 86 of PT.S_Mark m => checkStmt (withEnvAndContext (env, cxt, m))
453 : jhr 72 | PT.S_Block stms => let
454 :     fun chk (_, [], stms) = AST.S_Block(List.rev stms)
455 :     | chk (env, s::ss, stms) = let
456 :     val (s', env') = checkStmt (env, cxt, s)
457 :     in
458 : jhr 81 chk (env', ss, s'::stms)
459 : jhr 72 end
460 :     in
461 : jhr 1116 (chk (blockScope env, stms, []), env)
462 : jhr 72 end
463 :     | PT.S_Decl vd => let
464 : jhr 1116 val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
465 : jhr 72 in
466 : jhr 1116 checkForRedef (env, cxt, x);
467 :     (AST.S_Decl(AST.VD_Decl(x', e)), insertLocal(env, cxt, x, x'))
468 : jhr 72 end
469 :     | PT.S_IfThen(e, s) => let
470 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
471 : jhr 81 val (s', _) = checkStmt (env, cxt, s)
472 : jhr 72 in
473 :     (* check that condition has bool type *)
474 :     case ty
475 :     of Ty.T_Bool => ()
476 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
477 : jhr 72 (* end case *);
478 :     (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
479 :     end
480 :     | PT.S_IfThenElse(e, s1, s2) => let
481 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
482 : jhr 81 val (s1', _) = checkStmt (env, cxt, s1)
483 :     val (s2', _) = checkStmt (env, cxt, s2)
484 : jhr 72 in
485 :     (* check that condition has bool type *)
486 :     case ty
487 :     of Ty.T_Bool => ()
488 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
489 : jhr 72 (* end case *);
490 :     (AST.S_IfThenElse(e', s1', s2'), env)
491 :     end
492 : jhr 228 | PT.S_Assign(x, e) => (case Env.findVar (#env env, x)
493 : jhr 99 of NONE => err(cxt, [
494 :     S "undefined variable ", A x
495 :     ])
496 : jhr 72 | SOME x' => let
497 : jhr 99 (* FIXME: check for polymorphic variables *)
498 :     val ([], ty) = Var.typeOf x'
499 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
500 : jhr 72 in
501 : jhr 99 if U.matchType(ty, ty')
502 :     then (x, x', e')
503 :     else err(cxt, [
504 :     S "type of assigned variable ", A x,
505 :     S " does not match type of rhs\n",
506 :     S " expected: ", TY ty, S "\n",
507 : jhr 1116 S " but found: ", TY ty'
508 : jhr 99 ]);
509 : jhr 72 (* check that x' is mutable *)
510 :     case Var.kindOf x'
511 : jhr 511 of Var.StrandStateVar => ()
512 :     | Var.StrandOutputVar => ()
513 : jhr 72 | Var.LocalVar => ()
514 : jhr 99 | _ => err(cxt, [
515 :     S "assignment to immutable variable ", A x
516 :     ])
517 : jhr 72 (* end case *);
518 :     (AST.S_Assign(x', e'), env)
519 :     end
520 :     (* end case *))
521 : jhr 511 | PT.S_New(strand, args) => let
522 : jhr 228 val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
523 : jhr 81 val (args', tys') = ListPair.unzip argsAndTys'
524 : jhr 72 in
525 : jhr 228 case #scope env
526 :     of MethodScope => ()
527 :     | InitScope => ()
528 : jhr 511 | _ => err(cxt, [S "invalid scope for new strand"])
529 : jhr 228 (* end case *);
530 : jhr 511 (* FIXME: check that strand is defined and has the argument types match *)
531 :     (AST.S_New(strand, args'), env)
532 : jhr 72 end
533 : jhr 228 | PT.S_Die => (
534 :     case #scope env
535 : jhr 235 of MethodScope => ()
536 :     | _ => err(cxt, [S "\"die\" statment outside of method"])
537 : jhr 228 (* end case *);
538 :     (AST.S_Die, env))
539 :     | PT.S_Stabilize => (
540 :     case #scope env
541 : jhr 235 of MethodScope => ()
542 :     | _ => err(cxt, [S "\"stabilize\" statment outside of method"])
543 : jhr 228 (* end case *);
544 :     (AST.S_Stabilize, env))
545 : jhr 70 (* end case *))
546 :    
547 : jhr 82 fun checkParams (env, cxt, params) = let
548 :     fun chkParam (env, cxt, param) = (case param
549 : jhr 86 of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
550 : jhr 82 | PT.P_Param(ty, x) => let
551 : jhr 511 val x' = Var.new(x, AST.StrandParam, checkTy (cxt, ty))
552 : jhr 82 in
553 : jhr 1116 checkForRedef (env, cxt, x);
554 :     (x', insertLocal(env, cxt, x, x'))
555 : jhr 82 end
556 :     (* end case *))
557 :     fun chk (param, (xs, env)) = let
558 :     val (x, env) = chkParam (env, cxt, param)
559 :     in
560 :     (x::xs, env)
561 :     end
562 :     in
563 :     (* FIXME: need to check for multiple occurences of the same parameter name! *)
564 :     List.foldr chk ([], env) params
565 :     end
566 :    
567 :     fun checkMethod (env, cxt, meth) = (case meth
568 : jhr 86 of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
569 : jhr 82 | PT.M_Method(name, body) => let
570 : jhr 228 val (body, _) = checkStmt(methodScope env, cxt, body)
571 : jhr 82 in
572 :     AST.M_Method(name, body)
573 :     end
574 :     (* end case *))
575 :    
576 : jhr 511 fun checkStrand (env, cxt, {name, params, state, methods}) = let
577 :     (* check the strand parameters *)
578 : jhr 82 val (params, env) = checkParams (env, cxt, params)
579 : jhr 511 (* check the strand state variable definitions *)
580 : jhr 82 val (vds, env) = let
581 : jhr 164 fun checkStateVar ((isOut, vd), (vds, env)) = let
582 : jhr 511 val kind = if isOut then AST.StrandOutputVar else AST.StrandStateVar
583 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, kind, vd)
584 : jhr 82 in
585 : jhr 228 (* check that output variables have value types *)
586 :     if isOut andalso not(TU.isValueType(Var.monoTypeOf x'))
587 :     then err(cxt, [
588 :     S "output variable ", V x', S " has non-value type ",
589 :     TY(Var.monoTypeOf x')
590 :     ])
591 :     else ();
592 : jhr 1116 checkForRedef (env, cxt, x);
593 :     (AST.VD_Decl(x', e')::vds, insertLocal(env, cxt, x, x'))
594 : jhr 82 end
595 :     val (vds, env) = List.foldl checkStateVar ([], env) state
596 :     in
597 :     (List.rev vds, env)
598 :     end
599 : jhr 511 (* check the strand methods *)
600 : jhr 82 val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
601 : jhr 1116 (* get the set of methods defined by the user *)
602 :     val methodNames = List.foldl
603 :     (fn (AST.M_Method(name, _), names) => AtomSet.add(names, name))
604 :     AtomSet.empty
605 :     methods
606 :     (* if the stabilize method is not provided, add one *)
607 :     val methods = if AtomSet.member(methodNames, BasisNames.meth_stabilize)
608 :     then methods
609 :     else methods @ [AST.M_Method(BasisNames.meth_stabilize, AST.S_Block[])]
610 : jhr 82 in
611 : jhr 1116 if not(AtomSet.member(methodNames, BasisNames.meth_update))
612 :     then err(cxt, [S "strand ", A name, S " is missing an update method"])
613 :     else ();
614 : jhr 511 AST.D_Strand{name = name, params = params, state = vds, methods = methods}
615 : jhr 82 end
616 :    
617 : jhr 89 fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
618 : jhr 511 | checkCreate (env, cxt, PT.C_Create(strand, args)) = let
619 : jhr 228 val (args, tys) = checkExprList (env, cxt, args)
620 : jhr 89 in
621 : jhr 511 (* FIXME: check against strand definition *)
622 :     AST.C_Create(strand, args)
623 : jhr 89 end
624 :    
625 : jhr 1116 fun checkIters (env0, cxt, iters) = let
626 :     (* check an iteration range specification from the initially clause. We do the checking
627 :     * of the expressions using env0, which does not have any of the iteration variables in
628 :     * it (the iteration is rectangular), but we also accumulate the iteration bindings,
629 :     * which are used to create the final environment for checking the create call.
630 :     *)
631 :     fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
632 :     | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
633 :     val (e1', ty1) = checkExpr (env, cxt, e1)
634 :     val (e2', ty2) = checkExpr (env, cxt, e2)
635 :     val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
636 : jhr 89 in
637 : jhr 1116 case (ty1, ty2)
638 :     of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), (x, x'))
639 :     | _ => err(cxt, [
640 :     S "range expressions must have integer type\n",
641 :     S " but found: ", TY ty1, S " .. ", TY ty2
642 :     ])
643 :     (* end case *)
644 : jhr 89 end
645 : jhr 1116 fun chk ([], iters, bindings) =
646 :     (List.rev iters, List.foldl (fn ((x, x'), env) => insertLocal(env, cxt, x, x')) env0 bindings)
647 :     | chk (iter::rest, iters, bindings) = let
648 :     val (iter, binding) = checkIter (env0, cxt, iter)
649 :     in
650 :     chk (rest, iter::iters, binding::bindings)
651 :     end
652 : jhr 89 in
653 : jhr 1116 chk (iters, [], [])
654 : jhr 89 end
655 :    
656 : jhr 71 fun checkDecl (env, cxt, d) = (case d
657 : jhr 86 of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
658 : jhr 72 | PT.D_Input(ty, x, optExp) => let
659 : jhr 71 val ty = checkTy(cxt, ty)
660 :     val x' = Var.new(x, Var.InputVar, ty)
661 :     val dcl = (case optExp
662 :     of NONE => AST.D_Input(x', NONE)
663 :     | SOME e => let
664 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
665 : jhr 71 in
666 : jhr 89 if U.matchType (ty, ty')
667 :     then AST.D_Input(x', SOME e')
668 :     else err(cxt, [
669 :     S "definition of ", V x', S " has wrong type\n",
670 :     S " expected: ", TY ty, S "\n",
671 : jhr 1116 S " but found: ", TY ty'
672 : jhr 89 ])
673 : jhr 71 end
674 :     (* end case *))
675 :     in
676 : jhr 228 (* check that input variables have value types *)
677 :     if not(TU.isValueType ty)
678 :     then err(cxt, [S "input variable ", V x', S " has non-value type ", TY ty])
679 :     else ();
680 : jhr 1116 checkForRedef (env, cxt, x);
681 :     (dcl, insertGlobal(env, cxt, x, x'))
682 : jhr 71 end
683 : jhr 72 | PT.D_Var vd => let
684 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
685 : jhr 72 in
686 : jhr 1116 checkForRedef (env, cxt, x);
687 :     (AST.D_Var(AST.VD_Decl(x', e')), insertGlobal(env, cxt, x, x'))
688 : jhr 72 end
689 : jhr 511 | PT.D_Strand arg => (checkStrand(strandScope env, cxt, arg), env)
690 : jhr 89 | PT.D_InitialArray(create, iterators) => let
691 : jhr 228 val env = initScope env
692 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
693 :     val create = checkCreate (env', cxt, create)
694 :     in
695 :     (AST.D_InitialArray(create, iterators), env)
696 :     end
697 :     | PT.D_InitialCollection(create, iterators) => let
698 : jhr 228 val env = initScope env
699 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
700 :     val create = checkCreate (env', cxt, create)
701 :     in
702 :     (AST.D_InitialCollection(create, iterators), env)
703 :     end
704 : jhr 70 (* end case *))
705 :    
706 : jhr 86 fun check errStrm (PT.Program{span, tree}) = let
707 :     val cxt = (errStrm, span)
708 : jhr 81 fun chk (env, [], dcls') = AST.Program(List.rev dcls')
709 :     | chk (env, dcl::dcls, dcls') = let
710 : jhr 86 val (dcl', env) = checkDecl (env, cxt, dcl)
711 : jhr 81 in
712 :     chk (env, dcls, dcl'::dcls')
713 :     end
714 :     in
715 : jhr 1116 chk ({scope=GlobalScope, bindings=AtomMap.empty, env=Basis.env}, tree, [])
716 : jhr 81 end
717 : jhr 70
718 : jhr 69 end

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