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

1 : jhr 69 (* typechecker.sml
2 :     *
3 : jhr 3349 * This code is part of the Diderot Project (http://diderot-language.cs.uchicago.edu)
4 :     *
5 :     * COPYRIGHT (c) 2015 The University of Chicago
6 : jhr 69 * All rights reserved.
7 : jhr 228 *
8 : jhr 1116 * TODO:
9 : jhr 2356 * prune unreachable code?? (see simplify/simplify.sml)
10 :     * error recovery so that we can detect multiple errors in a single compile
11 :     * check that the args of strand creation have the same type and number as the params
12 : jhr 69 *)
13 :    
14 :     structure Typechecker : sig
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 2356 (* exception to abort typechecking when we hit an error. Eventually, we should continue
27 :     * checking for more errors and not use this.
28 :     *)
29 :     exception TypeError
30 : jhr 169
31 : jhr 2660 (* variable properties to support unused variable warning *)
32 :     val {getFn=isUsed, setFn=markUsed} = Var.newFlag()
33 :     val {setFn=(setLoc : AST.var * Error.location -> unit), getFn=getLoc, ...} =
34 : jhr 3082 Var.newProp(fn x => raise Fail("no location for " ^ Var.nameOf x))
35 : jhr 2660
36 : jhr 2356 datatype scope
37 :     = GlobalScope
38 :     | FunctionScope of Ty.ty * Atom.atom
39 :     | StrandScope
40 :     | MethodScope of StrandUtil.method_name
41 :     | InitScope
42 :    
43 : jhr 2462 fun scopeToString GlobalScope = "global scope"
44 :     | scopeToString (FunctionScope(_, f)) = "function " ^ Atom.toString f
45 :     | scopeToString StrandScope = "strand initialization"
46 :     | scopeToString (MethodScope m) = "method " ^ StrandUtil.nameToString m
47 :     | scopeToString InitScope = "initialization"
48 :    
49 : jhr 1116 type env = {
50 : jhr 3082 scope : scope, (* current scope *)
51 :     bindings : Error.location AtomMap.map, (* map from atoms to innermost binding location *)
52 :     env : Env.env (* variable environment *)
53 : jhr 1116 }
54 : jhr 228
55 : jhr 1116 type context = Error.err_stream * Error.span
56 : jhr 228
57 : jhr 1116 (* start a new scope *)
58 : jhr 2356 fun functionScope ({scope, bindings, env}, ty, f) =
59 :     {scope=FunctionScope(ty, f), bindings=AtomMap.empty, env=env}
60 : jhr 1116 fun strandScope {scope, bindings, env} =
61 : jhr 2356 {scope=StrandScope, bindings=AtomMap.empty, env=env}
62 :     fun methodScope ({scope, bindings, env}, name) =
63 :     {scope=MethodScope name, bindings=AtomMap.empty, env=env}
64 : jhr 1116 fun initScope {scope, bindings, env} =
65 : jhr 2356 {scope=InitScope, bindings=AtomMap.empty, env=env}
66 : jhr 1116 fun blockScope {scope, bindings, env} =
67 : jhr 2356 {scope=scope, bindings=AtomMap.empty, env=env}
68 : jhr 1116
69 :     fun inStrand {scope=StrandScope, bindings, env} = true
70 : jhr 2356 | inStrand {scope=MethodScope _, ...} = true
71 : jhr 511 | inStrand _ = false
72 : jhr 228
73 : jhr 2356 fun insertStrand ({scope, bindings, env}, cxt, s as AST.Strand{name, ...}) = {
74 :     scope=scope,
75 :     bindings = AtomMap.insert(bindings, name, Error.location cxt),
76 :     env=Env.insertStrand(env, s)
77 :     }
78 : jhr 3145 fun insertFunc ({scope, bindings, env}, cxt, f, f') = let
79 :     val loc = Error.location cxt
80 :     in
81 :     setLoc(f', loc);
82 :     {
83 :     scope = scope,
84 :     bindings = AtomMap.insert(bindings, f, loc),
85 :     env = Env.insertFunc(env, f, Env.UserFun f')
86 :     }
87 :     end
88 : jhr 2660 fun insertLocal ({scope, bindings, env}, cxt, x, x') = let
89 : jhr 3082 val loc = Error.location cxt
90 :     in
91 :     setLoc(x', loc);
92 :     {
93 : jhr 3145 scope = scope,
94 : jhr 3147 bindings = AtomMap.insert(bindings, x, loc),
95 : jhr 3145 env = Env.insertLocal(env, x, x')
96 : jhr 3082 }
97 :     end
98 : jhr 2660 fun insertGlobal ({scope, bindings, env}, cxt, x, x') = let
99 : jhr 3082 val loc = Error.location cxt
100 :     in
101 :     setLoc(x', loc);
102 :     {
103 : jhr 3145 scope = scope,
104 : jhr 3082 bindings = AtomMap.insert(bindings, x, loc),
105 : jhr 3145 env = Env.insertGlobal(env, x, x')
106 : jhr 3082 }
107 :     end
108 : jhr 228
109 : jhr 86 fun withContext ((errStrm, _), {span, tree}) =
110 : jhr 2356 ((errStrm, span), tree)
111 : jhr 86 fun withEnvAndContext (env, (errStrm, _), {span, tree}) =
112 : jhr 2356 (env, (errStrm, span), tree)
113 : jhr 86
114 : jhr 88 datatype token
115 :     = S of string | A of Atom.atom
116 :     | V of AST.var | TY of Types.ty | TYS of Types.ty list
117 :    
118 : jhr 2356 local
119 :     fun tysToString tys = String.concat[
120 :     "(", String.concatWith " * " (List.map TU.toString tys), ")"
121 :     ]
122 :     fun tok2str (S s) = s
123 :     | tok2str (A a) = concat["'", Atom.toString a, "'"]
124 :     | tok2str (V x) = concat["'", Var.nameOf x, "'"]
125 :     | tok2str (TY ty) = TU.toString ty
126 :     | tok2str (TYS []) = "()"
127 :     | tok2str (TYS[ty]) = TU.toString ty
128 :     | tok2str (TYS tys) = tysToString tys
129 :     in
130 :     fun warn ((errStrm, span), toks) = Error.warningAt(errStrm, span, List.map tok2str toks)
131 :     fun err ((errStrm, span), toks) = (
132 :     Error.errorAt(errStrm, span, List.map tok2str toks);
133 :     (* FIXME: add error recovery *)
134 :     raise TypeError)
135 :     end (* local *)
136 : jhr 88
137 : jhr 2660 (* check for redefinition of an identifier in the same scope *)
138 :     (* TODO: check for shadowing too? *)
139 :     fun checkForRedef (env : env, cxt : context, x) = (case AtomMap.find(#bindings env, x)
140 : jhr 2356 of SOME loc => err (cxt, [
141 :     S "redefinition of ", A x, S ", previous definition at ",
142 :     S(Error.locToString loc)
143 :     ])
144 :     | NONE => ()
145 :     (* end case *))
146 : jhr 1116
147 : jhr 83 val realZero = AST.E_Lit(Literal.Float(FloatLit.zero true))
148 :    
149 : jhr 2356 (* check a differentiation level, which must be >= 0 *)
150 : jhr 70 fun checkDiff (cxt, k) =
151 : jhr 2356 if (k < 0)
152 :     then err (cxt, [S "differentiation must be >= 0"])
153 :     else Ty.DiffConst(IntInf.toInt k)
154 : jhr 70
155 : jhr 2356 (* check a sequence dimension, which must be > 0 *)
156 :     fun checkSeqDim (cxt, d) =
157 :     if (d < 0)
158 :     then err (cxt, [S "invalid dimension; must be positive"])
159 :     else Ty.DimConst(IntInf.toInt d)
160 :    
161 : jhr 1116 (* check a dimension, which must be 1, 2 or 3 *)
162 : jhr 70 fun checkDim (cxt, d) =
163 : jhr 2356 if (d < 1) orelse (3 < d)
164 :     then err (cxt, [S "invalid dimension; must be 1, 2, or 3"])
165 :     else Ty.DimConst(IntInf.toInt d)
166 : jhr 70
167 :     (* check a shape *)
168 : jhr 1116 fun checkShape (cxt, shape) = let
169 : jhr 2356 fun checkDim d =
170 :     if (d <= 1)
171 :     then err (cxt, [S "invalid tensor-shape dimension; must be > 1"])
172 :     else Ty.DimConst(IntInf.toInt d)
173 :     in
174 :     Ty.Shape(List.map checkDim shape)
175 :     end
176 : jhr 70
177 : jhr 69 (* check the well-formedness of a type and translate it to an AST type *)
178 : jhr 70 fun checkTy (cxt, ty) = (case ty
179 : jhr 2356 of PT.T_Mark m => checkTy(withContext(cxt, m))
180 :     | PT.T_Bool => Ty.T_Bool
181 :     | PT.T_Int => Ty.T_Int
182 :     | PT.T_Real => Ty.realTy
183 :     | PT.T_String => Ty.T_String
184 :     | PT.T_Vec n => (* NOTE: the parser guarantees that 2 <= n <= 4 *)
185 :     Ty.vecTy(IntInf.toInt n)
186 :     | PT.T_Kernel k => Ty.T_Kernel(checkDiff(cxt, k))
187 :     | PT.T_Field{diff, dim, shape} => Ty.T_Field{
188 :     diff = checkDiff (cxt, diff),
189 :     dim = checkDim (cxt, dim),
190 :     shape = checkShape (cxt, shape)
191 :     }
192 :     | PT.T_Tensor shape => Ty.T_Tensor(checkShape(cxt, shape))
193 :     | PT.T_Image{dim, shape} => Ty.T_Image{
194 :     dim = checkDim (cxt, dim),
195 :     shape = checkShape (cxt, shape)
196 :     }
197 :     | PT.T_Seq(ty, dim) => let
198 : jhr 1640 val ty = checkTy(cxt, ty)
199 :     in
200 : jhr 2636 if TU.isFixedSizeType ty
201 : jhr 2356 then Ty.T_Sequence(ty, checkSeqDim (cxt, dim))
202 : jhr 2636 else err(cxt, [S "elements of sequence types must be fixed-size types"])
203 : jhr 1640 end
204 : jhr 2356 (* end case *))
205 : jhr 69
206 : jhr 71 fun checkLit lit = (case lit
207 : jhr 2356 of (Literal.Int _) => (AST.E_Lit lit, Ty.T_Int)
208 :     | (Literal.Float _) => (AST.E_Lit lit, Ty.realTy)
209 :     | (Literal.String s) => (AST.E_Lit lit, Ty.T_String)
210 :     | (Literal.Bool _) => (AST.E_Lit lit, Ty.T_Bool)
211 :     (* end case *))
212 : jhr 71
213 : jhr 2356 fun coerceExp (Ty.T_Tensor(Ty.Shape[]), Ty.T_Int, AST.E_Lit(Literal.Int n)) =
214 :     AST.E_Lit(Literal.Float(FloatLit.fromInt n))
215 :     | coerceExp (ty1, ty2, e) = AST.E_Coerce{srcTy=ty2, dstTy=ty1, e=e}
216 :    
217 :     fun coerceType (dstTy, srcTy, e) = (case U.matchType(dstTy, srcTy)
218 :     of U.EQ => SOME e
219 :     | U.COERCE => SOME(coerceExp (dstTy, srcTy, e))
220 :     | U.FAIL => NONE
221 :     (* end case *))
222 :    
223 :     fun realType (ty as Ty.T_Tensor(Ty.Shape[])) = ty
224 :     | realType (ty as Ty.T_Int) = Ty.realTy
225 :     | realType ty = ty
226 :    
227 : jhr 85 (* resolve overloading: we use a simple scheme that selects the first operator in the
228 :     * list that matches the argument types.
229 :     *)
230 : jhr 1116 fun resolveOverload (_, rator, _, _, []) = raise Fail(concat[
231 : jhr 2356 "resolveOverload: \"", Atom.toString rator, "\" has no candidates"
232 :     ])
233 : jhr 1116 | resolveOverload (cxt, rator, argTys, args, candidates) = let
234 : jhr 2356 (* FIXME: we could be more efficient by just checking for coercion matchs the first pass
235 :     * and remembering those that are not pure EQ matches.
236 :     *)
237 :     (* try to match candidates while allowing type coercions *)
238 :     fun tryMatchCandidates [] = err(cxt, [
239 :     S "unable to resolve overloaded operator ", A rator, S "\n",
240 :     S " argument type is: ", TYS argTys, S "\n"
241 :     ])
242 :     | tryMatchCandidates (x::xs) = let
243 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
244 :     in
245 :     case U.tryMatchArgs (domTy, args, argTys)
246 :     of SOME args' => (AST.E_Apply(x, tyArgs, args', rngTy), rngTy)
247 :     | NONE => tryMatchCandidates xs
248 :     (* end case *)
249 :     end
250 :     fun tryCandidates [] = tryMatchCandidates candidates
251 :     | tryCandidates (x::xs) = let
252 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
253 :     in
254 :     if U.tryEqualTypes(domTy, argTys)
255 :     then (AST.E_Apply(x, tyArgs, args, rngTy), rngTy)
256 :     else tryCandidates xs
257 :     end
258 :     in
259 :     tryCandidates candidates
260 :     end
261 : jhr 85
262 : jhr 70 (* typecheck an expression and translate it to AST *)
263 : jhr 169 fun checkExpr (env : env, cxt, e) = (case e
264 : jhr 2356 of PT.E_Mark m => checkExpr (withEnvAndContext (env, cxt, m))
265 :     | PT.E_Var x => (case Env.findVar (#env env, x)
266 : jhr 2660 of SOME x' => (
267 : jhr 3082 markUsed (x', true);
268 :     (AST.E_Var x', Var.monoTypeOf x'))
269 : jhr 2356 | NONE => err(cxt, [S "undeclared variable ", A x])
270 :     (* end case *))
271 :     | PT.E_Lit lit => checkLit lit
272 :     | PT.E_OrElse(e1, e2) => let
273 :     val (e1', ty1) = checkExpr(env, cxt, e1)
274 :     val (e2', ty2) = checkExpr(env, cxt, e2)
275 :     in
276 :     case (ty1, ty2)
277 :     of (Ty.T_Bool, Ty.T_Bool) =>
278 :     (AST.E_Cond(e1', AST.E_Lit(Literal.Bool true), e2', Ty.T_Bool), Ty.T_Bool)
279 :     | _ => err (cxt, [S "arguments to \"||\" must have bool type"])
280 :     (* end case *)
281 :     end
282 :     | PT.E_AndAlso(e1, e2) => let
283 :     val (e1', ty1) = checkExpr(env, cxt, e1)
284 :     val (e2', ty2) = checkExpr(env, cxt, e2)
285 :     in
286 :     case (ty1, ty2)
287 :     of (Ty.T_Bool, Ty.T_Bool) =>
288 :     (AST.E_Cond(e1', e2', AST.E_Lit(Literal.Bool false), Ty.T_Bool), Ty.T_Bool)
289 :     | _ => err (cxt, [S "arguments to \"&&\" must have bool type"])
290 :     (* end case *)
291 :     end
292 :     | PT.E_Cond(e1, cond, e2) => let
293 :     val (e1', ty1) = checkExpr(env, cxt, e1)
294 :     val (e2', ty2) = checkExpr(env, cxt, e2)
295 :     in
296 :     case checkExpr(env, cxt, cond)
297 :     of (cond', Ty.T_Bool) =>
298 :     if U.equalType(ty1, ty2)
299 :     then (AST.E_Cond(cond', e1', e2', ty1), ty1)
300 :     else err (cxt, [
301 :     S "types do not match in conditional expression\n",
302 :     S " true branch: ", TY ty1, S "\n",
303 :     S " false branch: ", TY ty2
304 :     ])
305 :     | (_, ty') => err (cxt, [S "expected bool type, but found ", TY ty'])
306 :     (* end case *)
307 :     end
308 :     | PT.E_BinOp(e1, rator, e2) => let
309 :     val (e1', ty1) = checkExpr(env, cxt, e1)
310 :     val (e2', ty2) = checkExpr(env, cxt, e2)
311 :     in
312 :     if Atom.same(rator, BasisNames.op_dot)
313 :     (* we have to handle inner product as a special case, because out type
314 :     * system cannot express the constraint that the type is
315 :     * ALL[sigma1, d1, sigma2] . tensor[sigma1, d1] * tensor[d1, sigma2] -> tensor[sigma1, sigma2]
316 :     *)
317 :     then (case (TU.prune ty1, TU.prune ty2)
318 :     of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_)), Ty.T_Tensor(s2 as Ty.Shape(d2::dd2))) => let
319 :     val (dd1, d1) = let
320 :     fun splitLast (prefix, [d]) = (List.rev prefix, d)
321 :     | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
322 :     | splitLast (_, []) = raise Fail "impossible"
323 :     in
324 :     splitLast ([], dd1)
325 :     end
326 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_inner)
327 :     val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
328 :     in
329 :     if U.equalDim(d1, d2)
330 :     andalso U.equalTypes(domTy, [ty1, ty2])
331 :     andalso U.equalType(rngTy, resTy)
332 :     then (AST.E_Apply(BV.op_inner, tyArgs, [e1', e2'], rngTy), rngTy)
333 :     else err (cxt, [
334 :     S "type error for arguments of binary operator \"•\"\n",
335 :     S " found: ", TYS[ty1, ty2], S "\n"
336 :     ])
337 :     end
338 :     | (ty1, ty2) => err (cxt, [
339 :     S "type error for arguments of binary operator \"•\"\n",
340 :     S " found: ", TYS[ty1, ty2], S "\n"
341 :     ])
342 :     (* end case *))
343 :     else if Atom.same(rator, BasisNames.op_colon)
344 :     then (case (TU.prune ty1, TU.prune ty2)
345 : jhr 3082 of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_::_)),
346 :     Ty.T_Tensor(s2 as Ty.Shape(d21::d22::dd2))) => let
347 : jhr 2356 val (dd1, d11, d12) = let
348 :     fun splitLast (prefix, [d1, d2]) = (List.rev prefix, d1, d2)
349 :     | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
350 :     | splitLast (_, []) = raise Fail "impossible"
351 :     in
352 :     splitLast ([], dd1)
353 :     end
354 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_colon)
355 :     val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
356 :     in
357 :     if U.equalDim(d11, d21) andalso U.equalDim(d12, d22)
358 :     andalso U.equalTypes(domTy, [ty1, ty2])
359 :     andalso U.equalType(rngTy, resTy)
360 :     then (AST.E_Apply(BV.op_colon, tyArgs, [e1', e2'], rngTy), rngTy)
361 :     else err (cxt, [
362 :     S "type error for arguments of binary operator \":\"\n",
363 :     S " found: ", TYS[ty1, ty2], S "\n"
364 :     ])
365 :     end
366 :     | (ty1, ty2) => err (cxt, [
367 :     S "type error for arguments of binary operator \":\"\n",
368 :     S " found: ", TYS[ty1, ty2], S "\n"
369 :     ])
370 :     (* end case *))
371 :     else (case Env.findFunc (#env env, rator)
372 :     of Env.PrimFun[rator] => let
373 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
374 :     in
375 :     case U.matchArgs(domTy, [e1', e2'], [ty1, ty2])
376 :     of SOME args => (AST.E_Apply(rator, tyArgs, args, rngTy), rngTy)
377 :     | NONE => err (cxt, [
378 :     S "type error for binary operator \"", V rator, S "\"\n",
379 :     S " expected: ", TYS domTy, S "\n",
380 :     S " but found: ", TYS[ty1, ty2]
381 :     ])
382 :     (* end case *)
383 :     end
384 :     | Env.PrimFun ovldList =>
385 :     resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
386 :     | _ => raise Fail "impossible"
387 :     (* end case *))
388 :     end
389 :     | PT.E_UnaryOp(rator, e) => let
390 :     val (e', ty) = checkExpr(env, cxt, e)
391 :     in
392 :     case Env.findFunc (#env env, rator)
393 :     of Env.PrimFun[rator] => let
394 :     val (tyArgs, Ty.T_Fun([domTy], rngTy)) = U.instantiate(Var.typeOf rator)
395 :     in
396 :     case coerceType (domTy, ty, e')
397 :     of SOME e' => (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
398 :     | NONE => err (cxt, [
399 :     S "type error for unary operator \"", V rator, S "\"\n",
400 :     S " expected: ", TY domTy, S "\n",
401 :     S " but found: ", TY ty
402 :     ])
403 :     (* end case *)
404 :     end
405 :     | Env.PrimFun ovldList => resolveOverload (cxt, rator, [ty], [e'], ovldList)
406 :     | _ => raise Fail "impossible"
407 :     (* end case *)
408 :     end
409 :     | PT.E_Slice(e, indices) => let
410 :     val (e', ty) = checkExpr (env, cxt, e)
411 :     fun checkIndex NONE = NONE
412 :     | checkIndex (SOME e) = let
413 :     val (e', ty) = checkExpr (env, cxt, e)
414 : jhr 1640 in
415 : jhr 2356 if U.equalType(ty, Ty.T_Int)
416 :     then (SOME e')
417 :     else err (cxt, [
418 :     S "type error in index expression\n",
419 :     S " expected int, but found: ", TY ty
420 :     ])
421 : jhr 1640 end
422 : jhr 2356 val indices' = List.map checkIndex indices
423 :     val order = List.length indices'
424 :     val expectedTy = TU.mkTensorTy order
425 :     val resultTy = TU.slice(expectedTy, List.map Option.isSome indices')
426 :     in
427 :     if U.equalType(ty, expectedTy)
428 :     then ()
429 :     else err (cxt, [
430 :     S "type error in slice operation\n",
431 :     S " expected: ", S(Int.toString order), S "-order tensor\n",
432 :     S " but found: ", TY ty
433 :     ]);
434 :     (AST.E_Slice(e', indices', resultTy), resultTy)
435 :     end
436 :     | PT.E_Subscript(e1, e2) => let
437 :     val (e1', ty1) = checkExpr (env, cxt, e1)
438 :     val (e2', ty2) = checkExpr (env, cxt, e2)
439 :     fun chkIndex () = if U.equalType(ty2, Ty.T_Int)
440 :     then ()
441 :     else err (cxt, [
442 :     S "expected int type for subscript index\n",
443 :     S " but found: ", TY ty2
444 :     ])
445 :     fun finish rator = let
446 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = U.instantiate(Var.typeOf rator)
447 : jhr 1640 in
448 : jhr 2356 if U.equalTypes(domTy, [ty1, ty2])
449 :     then let
450 :     val exp = AST.E_Apply(rator, tyArgs, [e1', e2'], rngTy)
451 :     in
452 :     (exp, rngTy)
453 :     end
454 :     else raise Fail "unexpected unification failure"
455 : jhr 1640 end
456 : jhr 2356 in
457 :     case TU.pruneHead ty1
458 :     of Ty.T_Sequence _ => (
459 :     chkIndex ();
460 :     finish BV.subscript)
461 :     | _ => err (cxt, [
462 :     S "expected sequence type for subscript\n",
463 :     S " but found: ", TY ty1
464 :     ])
465 :     (* end case *)
466 :     end
467 :     | PT.E_Apply(e, args) => let
468 :     fun stripMark (PT.E_Mark{tree, ...}) = stripMark tree
469 :     | stripMark e = e
470 :     val (args, tys) = checkExprList (env, cxt, args)
471 :     fun checkFunApp f = (case Util.instantiate(Var.typeOf f)
472 :     of (tyArgs, Ty.T_Fun(domTy, rngTy)) => (
473 :     case U.matchArgs (domTy, args, tys)
474 :     of SOME args => (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
475 :     | NONE => err(cxt, [
476 :     S "type error in application of ", V f, S "\n",
477 :     S " expected: ", TYS domTy, S "\n",
478 :     S " but found: ", TYS tys
479 :     ])
480 :     (* end case *))
481 :     | _ => err(cxt, [S "application of non-function ", V f])
482 :     (* end case *))
483 :     fun checkFieldApp (e1', ty1) = (case (args, tys)
484 :     of ([e2'], [ty2]) => let
485 :     val (tyArgs, Ty.T_Fun([fldTy, domTy], rngTy)) =
486 :     Util.instantiate(Var.typeOf BV.op_probe)
487 :     fun tyError () = err (cxt, [
488 :     S "type error for field application\n",
489 :     S " expected: ", TYS[fldTy, domTy], S "\n",
490 :     S " but found: ", TYS[ty1, ty2]
491 :     ])
492 :     in
493 :     if U.equalType(fldTy, ty1)
494 :     then (case coerceType(domTy, ty2, e2')
495 :     of SOME e2' => (AST.E_Apply(BV.op_probe, tyArgs, [e1', e2'], rngTy), rngTy)
496 :     | NONE => tyError()
497 :     (* end case *))
498 :     else tyError()
499 :     end
500 :     | _ => err(cxt, [S "badly formed field application"])
501 :     (* end case *))
502 :     in
503 :     case stripMark e
504 :     of PT.E_Var f => (case Env.findVar (#env env, f)
505 : jhr 3147 of SOME f' => (
506 :     markUsed (f', true);
507 :     checkFieldApp (AST.E_Var f', Var.monoTypeOf f'))
508 : jhr 2356 | NONE => (case Env.findFunc (#env env, f)
509 :     of Env.PrimFun[] => err(cxt, [S "unknown function ", A f])
510 :     | Env.PrimFun[f'] =>
511 :     if (inStrand env) andalso (Basis.isRestricted f')
512 :     then err(cxt, [
513 :     S "use of restricted operation ", V f',
514 :     S " in strand body"
515 :     ])
516 :     else checkFunApp f'
517 :     | Env.PrimFun ovldList =>
518 :     resolveOverload (cxt, f, tys, args, ovldList)
519 : jhr 3147 | Env.UserFun f' => (
520 :     markUsed (f', true);
521 :     checkFunApp f')
522 : jhr 2356 (* end case *))
523 :     (* end case *))
524 :     | _ => checkFieldApp (checkExpr (env, cxt, e))
525 :     (* end case *)
526 :     end
527 :     | PT.E_Tuple args => let
528 :     val (args, tys) = checkExprList (env, cxt, args)
529 :     in
530 :     raise Fail "E_Tuple not yet implemented" (* FIXME *)
531 :     end
532 :     | PT.E_Sequence args => (case checkExprList (env, cxt, args)
533 :     (* FIXME: need kind for concrete types here! *)
534 : jhr 2636 of ([], _) => (AST.E_Seq[], Ty.T_Sequence(Ty.T_Var(MetaVar.newTyVar()), Ty.DimConst 0))
535 : jhr 2356 | (args, ty::tys) =>
536 : jhr 2636 if TU.isFixedSizeType(TU.pruneHead ty)
537 : jhr 2356 then let
538 :     fun chkTy ty' = U.equalType(ty, ty')
539 :     val resTy = Ty.T_Sequence(ty, Ty.DimConst(List.length args))
540 :     in
541 :     if List.all chkTy tys
542 : jhr 2636 then (AST.E_Seq args, resTy)
543 : jhr 2356 else err(cxt, [S "arguments of sequence expression must have same type"])
544 :     end
545 :     else err(cxt, [S "sequence expression of non-value argument type"])
546 :     (* end case *))
547 :     | PT.E_Cons args => let
548 :     val (args, tys as ty::_) = checkExprList (env, cxt, args)
549 :     in
550 :     case realType(TU.pruneHead ty)
551 :     of ty as Ty.T_Tensor shape => let
552 :     val Ty.Shape dd = TU.pruneShape shape (* NOTE: this may fail if we allow user polymorphism *)
553 :     val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
554 :     fun chkArgs (arg::args, argTy::tys, args') = (case coerceType(ty, argTy, arg)
555 :     of SOME arg' => chkArgs (args, tys, arg'::args')
556 :     | NONE => err(cxt, [S "arguments of tensor construction must have same type"])
557 :     (* end case *))
558 :     | chkArgs ([], [], args') = (AST.E_Cons(List.rev args'), resTy)
559 :     in
560 :     chkArgs (args, tys, [])
561 :     end
562 :     | _ => err(cxt, [S "Invalid argument type for tensor construction"])
563 : jhr 2660 (* end case *)
564 : jhr 2356 end
565 :     | PT.E_Real e => (case checkExpr (env, cxt, e)
566 :     of (e', Ty.T_Int) =>
567 :     (AST.E_Apply(BV.i2r, [], [e'], Ty.realTy), Ty.realTy)
568 :     | _ => err(cxt, [S "argument of real conversion must be int"])
569 :     (* end case *))
570 :     | PT.E_Id d => let
571 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
572 :     Util.instantiate(Var.typeOf(BV.identity))
573 :     in
574 :     if U.equalType(Ty.T_Tensor(checkShape(cxt, [d,d])), rngTy)
575 :     then (AST.E_Apply(BV.identity, tyArgs, [], rngTy), rngTy)
576 :     else raise Fail "impossible"
577 :     end
578 :     | PT.E_Zero dd => let
579 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
580 :     Util.instantiate(Var.typeOf(BV.zero))
581 :     in
582 :     if U.equalType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
583 :     then (AST.E_Apply(BV.zero, tyArgs, [], rngTy), rngTy)
584 :     else raise Fail "impossible"
585 :     end
586 : jhr 2636 | PT.E_Image nrrd => let
587 :     val (tyArgs, Ty.T_Fun(_, rngTy)) = Util.instantiate(Var.typeOf(BV.fn_image))
588 :     in
589 :     (AST.E_LoadNrrd(tyArgs, nrrd, rngTy), rngTy)
590 :     end
591 : jhr 2356 (* end case *))
592 : jhr 70
593 : jhr 81 (* typecheck a list of expressions returning a list of AST expressions and a list
594 :     * of types of the expressions.
595 :     *)
596 :     and checkExprList (env, cxt, exprs) = let
597 : jhr 2356 fun chk (e, (es, tys)) = let
598 :     val (e, ty) = checkExpr (env, cxt, e)
599 :     in
600 :     (e::es, ty::tys)
601 :     end
602 :     in
603 :     List.foldr chk ([], []) exprs
604 :     end
605 : jhr 81
606 : jhr 72 fun checkVarDecl (env, cxt, kind, d) = (case d
607 : jhr 2356 of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
608 :     | PT.VD_Decl(ty, x, e) => let
609 :     val ty = checkTy (cxt, ty)
610 :     val x' = Var.new (x, kind, ty)
611 :     val (e', ty') = checkExpr (env, cxt, e)
612 :     in
613 :     case coerceType (ty, ty', e')
614 :     of SOME e' => (x, x', e')
615 :     | NONE => err(cxt, [
616 :     S "type of variable ", A x,
617 :     S " does not match type of initializer\n",
618 :     S " expected: ", TY ty, S "\n",
619 :     S " but found: ", TY ty'
620 :     ])
621 :     (* end case *)
622 :     end
623 :     (* end case *))
624 : jhr 72
625 : jhr 2356 (* check for unreachable code and non-return statements in the tail position of a function.
626 :     * Note that unreachable code is typechecked and included in the AST. It is pruned away
627 :     * by simplify.
628 :     *)
629 :     fun chkCtlFlow (cxt, scope, stm) = let
630 :     val (inFun, inUpdate, funName) = (case scope
631 :     of FunctionScope(_, f) => (true, false, Atom.toString f)
632 :     | MethodScope StrandUtil.Update => (false, true, "")
633 :     | _ => (false, false, "")
634 :     (* end case *))
635 :     (* checks a statement for correct control flow; it returns false if control may
636 :     * flow from the statement to the next in a sequence and true if control cannot
637 :     * flow to the next statement.
638 :     *)
639 :     fun chk ((errStrm, _), hasSucc, isJoin, unreachable, PT.S_Mark{span, tree}) =
640 :     chk((errStrm, span), hasSucc, isJoin, unreachable, tree)
641 :     | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Block(stms as _::_)) = let
642 :     fun chk' ([], escapes) = escapes
643 :     | chk' ([stm], escapes) =
644 :     chk(cxt, hasSucc, isJoin, escapes orelse unreachable, stm) orelse escapes
645 :     | chk' (stm::stms, escapes) = let
646 :     val escapes = chk(cxt, true, false, escapes orelse unreachable, stm) orelse escapes
647 :     in
648 :     chk'(stms, escapes)
649 :     end
650 :     in
651 :     chk' (stms, false)
652 :     end
653 :     | chk (cxt, hasSucc, isJoin, unreachable, PT.S_IfThen(_, stm)) = (
654 :     if inFun andalso not hasSucc andalso not unreachable
655 :     then err(cxt, [
656 :     S "Missing return statement in tail position of function ", S funName
657 :     ])
658 :     else ();
659 :     ignore (chk (cxt, hasSucc, true, unreachable, stm));
660 :     false)
661 :     | chk (cxt, hasSucc, isJoin, unreachable, PT.S_IfThenElse(_, stm1, stm2)) = let
662 :     val escapes = chk (cxt, hasSucc, true, unreachable, stm1)
663 :     val escapes = chk (cxt, hasSucc, true, unreachable, stm2) andalso escapes
664 :     in
665 :     if escapes andalso hasSucc andalso not unreachable
666 :     then (
667 :     warn(cxt, [S "unreachable statements after \"if-then-else\" statement"]);
668 :     true)
669 :     else escapes
670 :     end
671 : jhr 2636 | chk (cxt, _, _, _, PT.S_New _) = (
672 :     if not inUpdate
673 :     then err(cxt, [S "\"new\" statement outside of update method"])
674 :     else ();
675 :     false)
676 : jhr 2356 | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Die) = (
677 :     if not inUpdate
678 :     then err(cxt, [S "\"die\" statment outside of update method"])
679 :     else if hasSucc andalso not isJoin andalso not unreachable
680 :     then warn(cxt, [S "statements following \"die\" statment are unreachable"])
681 :     else ();
682 :     true)
683 :     | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Stabilize) = (
684 :     if not inUpdate
685 :     then err(cxt, [S "\"stabilize\" statment outside of update method"])
686 :     else if hasSucc andalso not isJoin andalso not unreachable
687 :     then warn(cxt, [S "statements following \"stabilize\" statment are unreachable"])
688 :     else ();
689 :     true)
690 :     | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Return _) = (
691 :     if not inFun
692 :     then err(cxt, [S "\"return\" statment outside of function body"])
693 :     else if hasSucc andalso not isJoin andalso not unreachable
694 :     then warn(cxt, [S "statements following \"return\" statment are unreachable"])
695 :     else ();
696 :     true)
697 :     | chk (cxt, hasSucc, isJoin, unreachable, _) = (
698 :     if inFun andalso not hasSucc andalso not unreachable
699 :     then err(cxt, [
700 :     S "Missing return statement in tail position of function ", S funName
701 :     ])
702 :     else ();
703 :     false)
704 :     in
705 :     ignore (chk (cxt, false, false, false, stm))
706 :     end
707 :    
708 :     (* check the creation of a new strand; either in a "new" statement or in an "initially"
709 :     * block.
710 :     *)
711 :     fun checkStrandCreate (env, cxt, strand, args) = let
712 :     val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
713 :     val (args', tys') = ListPair.unzip argsAndTys'
714 :     in
715 :     (* check that strand is defined and that the argument types match *)
716 :     case Env.findStrand (#env env, strand)
717 :     of SOME(AST.Strand{params, ...}) => let
718 :     val paramTys = List.map Var.monoTypeOf params
719 :     in
720 :     case U.matchArgs (paramTys, args', tys')
721 :     of SOME args' => (strand, args', env)
722 :     | NONE => err(cxt, [
723 :     S "type error in new ", A strand, S "\n",
724 :     S " expected: ", TYS paramTys, S "\n",
725 :     S " but found: ", TYS tys'
726 :     ])
727 :     (* end case *)
728 :     end
729 :     | NONE => err(cxt, [S "unknown strand ", A strand])
730 :     (* end case *)
731 :     end
732 :    
733 : jhr 70 (* typecheck a statement and translate it to AST *)
734 : jhr 2356 fun checkStmt (env : env, cxt : context, stm) = let
735 :     fun chkStmt (env : env, cxt : context, s) = (case s
736 :     of PT.S_Mark m => chkStmt (withEnvAndContext (env, cxt, m))
737 :     | PT.S_Block stms => let
738 :     fun chk (_, [], stms) = AST.S_Block(List.rev stms)
739 :     | chk (env, s::ss, stms) = let
740 :     val (s', env') = chkStmt (env, cxt, s)
741 :     in
742 :     chk (env', ss, s'::stms)
743 :     end
744 :     in
745 :     (chk (blockScope env, stms, []), env)
746 :     end
747 :     | PT.S_Decl vd => let
748 :     val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
749 :     in
750 :     checkForRedef (env, cxt, x);
751 :     (AST.S_Decl(AST.VD_Decl(x', e)), insertLocal(env, cxt, x, x'))
752 :     end
753 :     | PT.S_IfThen(e, s) => let
754 :     val (e', ty) = checkExpr (env, cxt, e)
755 :     val (s', _) = chkStmt (env, cxt, s)
756 :     in
757 :     (* check that condition has bool type *)
758 :     case ty
759 :     of Ty.T_Bool => ()
760 :     | _ => err(cxt, [S "condition not boolean type"])
761 :     (* end case *);
762 :     (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
763 :     end
764 :     | PT.S_IfThenElse(e, s1, s2) => let
765 :     val (e', ty) = checkExpr (env, cxt, e)
766 :     val (s1', _) = chkStmt (env, cxt, s1)
767 :     val (s2', _) = chkStmt (env, cxt, s2)
768 :     in
769 :     (* check that condition has bool type *)
770 :     case ty
771 :     of Ty.T_Bool => ()
772 :     | _ => err(cxt, [S "condition not boolean type"])
773 :     (* end case *);
774 :     (AST.S_IfThenElse(e', s1', s2'), env)
775 :     end
776 :     | PT.S_Assign(x, e) => (case Env.findVar (#env env, x)
777 :     of NONE => err(cxt, [
778 :     S "undefined variable ", A x
779 :     ])
780 :     | SOME x' => let
781 : jhr 99 (* FIXME: check for polymorphic variables *)
782 : jhr 2356 val ([], ty) = Var.typeOf x'
783 :     val (e', ty') = checkExpr (env, cxt, e)
784 :     (* check for promotion *)
785 :     val e' = (case coerceType(ty, ty', e')
786 :     of SOME e' => e'
787 :     | NONE => err(cxt, [
788 :     S "type of assigned variable ", A x,
789 :     S " does not match type of rhs\n",
790 :     S " expected: ", TY ty, S "\n",
791 :     S " but found: ", TY ty'
792 :     ])
793 :     (* end case *))
794 :     in
795 :     (* check that x' is mutable *)
796 :     case Var.kindOf x'
797 :     of Var.StrandStateVar => ()
798 : jhr 3147 | Var.StrandOutputVar => markUsed (x', true)
799 : jhr 2356 | Var.LocalVar => ()
800 :     | _ => err(cxt, [
801 : jhr 2462 S "assignment to immutable variable ", A x,
802 :     S " in ", S(scopeToString(#scope env))
803 : jhr 2356 ])
804 :     (* end case *);
805 :     (AST.S_Assign(x', e'), env)
806 :     end
807 :     (* end case *))
808 :     | PT.S_OpAssign(x, rator, e) => (case Env.findVar (#env env, x)
809 :     of SOME x' => let
810 :     val e1' = AST.E_Var x'
811 :     val ty1 = Var.monoTypeOf x'
812 :     val (e2', ty2) = checkExpr(env, cxt, e)
813 :     val Env.PrimFun ovldList = Env.findFunc (#env env, rator)
814 :     val (rhs, _) = resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
815 :     in
816 :     (* check that x' is mutable *)
817 :     case Var.kindOf x'
818 :     of Var.StrandStateVar => ()
819 : jhr 3147 | Var.StrandOutputVar => markUsed (x', true)
820 : jhr 2356 | Var.LocalVar => ()
821 :     | _ => err(cxt, [
822 : jhr 2462 S "assignment to immutable variable ", A x,
823 :     S " in ", S(scopeToString(#scope env))
824 : jhr 2356 ])
825 :     (* end case *);
826 :     (AST.S_Assign(x', rhs), env)
827 :     end
828 :     | NONE => err(cxt, [S "undeclared variable ", A x, S " on lhs of ", A rator])
829 :     (* end case *))
830 :     | PT.S_New(strand, args) => let
831 : jhr 2636 (* note that scope has already been checked in chkCtlFlow *)
832 : jhr 2356 val (strand, args, env) = checkStrandCreate (env, cxt, strand, args)
833 :     in
834 : jhr 2636 Env.recordProp (#env env, StrandUtil.NewStrands);
835 : jhr 2356 (AST.S_New(strand, args), env)
836 :     end
837 : jhr 2636 | PT.S_Die => (
838 :     (* note that scope has already been checked in chkCtlFlow *)
839 :     Env.recordProp (#env env, StrandUtil.StrandsMayDie);
840 :     (AST.S_Die, env))
841 :     | PT.S_Stabilize => (AST.S_Stabilize, env) (* note that scope has already been checked in chkCtlFlow *)
842 : jhr 2356 | PT.S_Return e => let
843 : jhr 1640 val (e', ty) = checkExpr (env, cxt, e)
844 :     in
845 : jhr 2356 case #scope env
846 :     of FunctionScope(ty', f) => (case coerceType(ty', ty, e')
847 :     of SOME e' => (AST.S_Return e', env)
848 :     | NONE => err(cxt, [
849 :     S "type of return expression does not match return type of function ",
850 :     A f, S "\n",
851 :     S " expected: ", TY ty', S "\n",
852 :     S " but found: ", TY ty
853 :     ])
854 :     (* end case *))
855 :     | _ => (AST.S_Return e', env) (* this error condition has already been checked *)
856 :     (* end case *)
857 : jhr 1640 end
858 : jhr 2356 | PT.S_Print args => let
859 :     fun chkArg e = let
860 :     val (e', ty) = checkExpr (env, cxt, e)
861 :     in
862 :     if TU.isValueType ty
863 :     then ()
864 :     else err(cxt, [
865 :     S "expected value type in print, but found ", TY ty
866 :     ]);
867 :     e'
868 :     end
869 :     val args' = List.map chkArg args
870 :     in
871 :     (AST.S_Print args', env)
872 :     end
873 :     (* end case *))
874 :     in
875 :     chkCtlFlow (cxt, #scope env, stm);
876 :     chkStmt (env, cxt, stm)
877 :     end (* checkStmt *)
878 :    
879 :     fun checkParams (env, cxt, params) = let
880 :     fun chkParam (env, cxt, param) = (case param
881 :     of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
882 :     | PT.P_Param(ty, x) => let
883 :     val x' = Var.new(x, AST.StrandParam, checkTy (cxt, ty))
884 :     in
885 :     checkForRedef (env, cxt, x);
886 :     (x', insertLocal(env, cxt, x, x'))
887 :     end
888 :     (* end case *))
889 :     fun chk (param, (xs, env)) = let
890 :     val (x, env) = chkParam (env, cxt, param)
891 : jhr 1640 in
892 : jhr 2356 (x::xs, env)
893 : jhr 1640 end
894 : jhr 2356 in
895 :     List.foldr chk ([], env) params
896 :     end
897 : jhr 70
898 : jhr 82 fun checkMethod (env, cxt, meth) = (case meth
899 : jhr 2356 of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
900 :     | PT.M_Method(name, body) => let
901 :     val (body, _) = checkStmt(methodScope (env, name), cxt, body)
902 :     in
903 :     AST.M_Method(name, body)
904 :     end
905 :     (* end case *))
906 : jhr 82
907 : jhr 511 fun checkStrand (env, cxt, {name, params, state, methods}) = let
908 : jhr 2356 (* check the strand parameters *)
909 :     val (params, env) = checkParams (strandScope env, cxt, params)
910 :     (* check the strand state variable definitions *)
911 :     val (vds, env) = let
912 :     fun checkStateVar ((isOut, vd), (vds, env)) = let
913 :     val kind = if isOut then AST.StrandOutputVar else AST.StrandStateVar
914 :     val (x, x', e') = checkVarDecl (env, cxt, kind, vd)
915 :     in
916 :     (* check that output variables have value types *)
917 :     if isOut andalso not(TU.isValueType(Var.monoTypeOf x'))
918 :     then err(cxt, [
919 :     S "output variable ", V x', S " has non-value type ",
920 :     TY(Var.monoTypeOf x')
921 :     ])
922 :     else ();
923 :     checkForRedef (env, cxt, x);
924 :     (AST.VD_Decl(x', e')::vds, insertLocal(env, cxt, x, x'))
925 :     end
926 :     val (vds, env) = List.foldl checkStateVar ([], env) state
927 :     in
928 :     (List.rev vds, env)
929 :     end
930 : jhr 2636 (* define a dummy strand definition so that recursive mentions of this strand will
931 :     * typecheck.
932 :     *)
933 :     val env = let
934 :     val strand = AST.Strand{name = name, params = params, state = vds, methods = []}
935 :     in
936 :     insertStrand(env, cxt, strand)
937 :     end
938 : jhr 2356 (* check the strand methods *)
939 :     val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
940 :     (* get the list of methods defined by the user *)
941 : jhr 1444 val methodNames = List.map (fn (AST.M_Method(name, _)) => name) methods
942 : jhr 2356 (* if the stabilize method is not provided, add one *)
943 : jhr 1640 val methods = if List.exists (fn StrandUtil.Stabilize => true | _ => false) methodNames
944 : jhr 2356 then methods
945 :     else methods @ [AST.M_Method(StrandUtil.Stabilize, AST.S_Block[])]
946 :     in
947 : jhr 1444 (* FIXME: should check for duplicate method definitions *)
948 : jhr 1640 if not(List.exists (fn StrandUtil.Update => true | _ => false) methodNames)
949 : jhr 2356 then err(cxt, [S "strand ", A name, S " is missing an update method"])
950 :     else ();
951 :     AST.Strand{name = name, params = params, state = vds, methods = methods}
952 :     end
953 : jhr 82
954 : jhr 89 fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
955 : jhr 511 | checkCreate (env, cxt, PT.C_Create(strand, args)) = let
956 : jhr 2356 val (strand, args, env) = checkStrandCreate (env, cxt, strand, args)
957 :     in
958 :     AST.C_Create(strand, args)
959 :     end
960 : jhr 89
961 : jhr 1116 fun checkIters (env0, cxt, iters) = let
962 : jhr 2356 (* check an iteration range specification from the initially clause. We do the checking
963 :     * of the expressions using env0, which does not have any of the iteration variables in
964 :     * it (the iteration is rectangular), but we also accumulate the iteration bindings,
965 :     * which are used to create the final environment for checking the create call.
966 :     *)
967 :     fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
968 :     | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
969 :     val (e1', ty1) = checkExpr (env, cxt, e1)
970 :     val (e2', ty2) = checkExpr (env, cxt, e2)
971 :     val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
972 :     in
973 :     case (ty1, ty2)
974 :     of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), (x, x'))
975 :     | _ => err(cxt, [
976 :     S "range expressions must have integer type\n",
977 :     S " but found: ", TY ty1, S " .. ", TY ty2
978 :     ])
979 :     (* end case *)
980 :     end
981 :     fun chk ([], iters, bindings) =
982 :     (List.rev iters, List.foldl (fn ((x, x'), env) => insertLocal(env, cxt, x, x')) env0 bindings)
983 :     | chk (iter::rest, iters, bindings) = let
984 :     val (iter, binding) = checkIter (env0, cxt, iter)
985 :     in
986 :     chk (rest, iter::iters, binding::bindings)
987 :     end
988 :     in
989 :     chk (iters, [], [])
990 :     end
991 : jhr 89
992 : jhr 71 fun checkDecl (env, cxt, d) = (case d
993 : jhr 2356 of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
994 :     | PT.D_Input(ty, x, desc, optExp) => let
995 : jhr 1301 (* FIXME: need to do something with the description *)
996 : jhr 2356 val ty = checkTy(cxt, ty)
997 :     val x' = Var.new(x, Var.InputVar, ty)
998 :     val dcl = (case optExp
999 :     of NONE => AST.D_Input(x', desc, NONE)
1000 :     | SOME e => let
1001 :     val (e', ty') = checkExpr (env, cxt, e)
1002 :     in
1003 :     case coerceType (ty, ty', e')
1004 :     of SOME e' => AST.D_Input(x', desc, SOME e')
1005 :     | NONE => err(cxt, [
1006 :     S "definition of ", V x', S " has wrong type\n",
1007 :     S " expected: ", TY ty, S "\n",
1008 :     S " but found: ", TY ty'
1009 :     ])
1010 :     (* end case *)
1011 :     end
1012 :     (* end case *))
1013 :     in
1014 : jhr 2636 (* check that input variables have valid types *)
1015 :     if not(TU.isValueType ty orelse TU.isImageType ty)
1016 :     then err(cxt, [S "input variable ", V x', S " has invalid type ", TY ty])
1017 : jhr 2356 else ();
1018 :     checkForRedef (env, cxt, x);
1019 :     (dcl, insertGlobal(env, cxt, x, x'))
1020 :     end
1021 :     | PT.D_Var vd => let
1022 :     val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
1023 :     in
1024 :     checkForRedef (env, cxt, x);
1025 :     (AST.D_Var(AST.VD_Decl(x', e')), insertGlobal(env, cxt, x, x'))
1026 :     end
1027 :     | PT.D_Func(ty, f, params, body) => let
1028 :     val ty' = checkTy(cxt, ty)
1029 :     val env' = functionScope (env, ty', f)
1030 :     val (params', env') = checkParams (env', cxt, params)
1031 :     val body' = (case body
1032 :     of PT.FB_Expr e => let
1033 :     val (e', ty) = checkExpr (env', cxt, e)
1034 :     in
1035 :     case coerceType(ty', ty, e')
1036 :     of SOME e' => AST.S_Return e'
1037 :     | NONE => err(cxt, [
1038 :     S "type of function body does not match return type\n",
1039 :     S " expected: ", TY ty', S "\n",
1040 :     S " but found: ", TY ty
1041 :     ])
1042 :     (* end case *)
1043 :     end
1044 :     | PT.FB_Stmt s => #1(checkStmt(env', cxt, s))
1045 :     (* end case *))
1046 :     val fnTy = Ty.T_Fun(List.map Var.monoTypeOf params', ty')
1047 :     val f' = Var.new (f, AST.FunVar, fnTy)
1048 :     in
1049 :     (* QUESTION: should we check for redefinition of basis functions? *)
1050 :     checkForRedef (env, cxt, f);
1051 :     (AST.D_Func(f', params', body'), insertFunc(env, cxt, f, f'))
1052 :     end
1053 :     | PT.D_Strand arg => let
1054 : jhr 2636 val strand = checkStrand(strandScope env, cxt, arg)
1055 : jhr 2356 in
1056 :     checkForRedef (env, cxt, #name arg);
1057 :     (AST.D_Strand strand, insertStrand(env, cxt, strand))
1058 :     end
1059 :     | PT.D_InitialArray(create, iterators) => let
1060 : jhr 2636 val (iterators, env') = checkIters (initScope env, cxt, iterators)
1061 : jhr 2356 val create = checkCreate (env', cxt, create)
1062 :     in
1063 : jhr 2636 if StrandUtil.hasProp StrandUtil.StrandsMayDie (Env.properties (#env env))
1064 :     then err(cxt, [
1065 :     S "initial strand grid conflicts with use of \"die\", use collection instead"
1066 :     ])
1067 :     else if StrandUtil.hasProp StrandUtil.NewStrands (Env.properties (#env env))
1068 :     then err(cxt, [
1069 :     S "initial strand grid conflicts with use of \"new\", use collection instead"
1070 :     ])
1071 :     else ();
1072 : jhr 2356 (AST.D_InitialArray(create, iterators), env)
1073 :     end
1074 :     | PT.D_InitialCollection(create, iterators) => let
1075 : jhr 2636 val (iterators, env') = checkIters (initScope env, cxt, iterators)
1076 : jhr 2356 val create = checkCreate (env', cxt, create)
1077 :     in
1078 :     (AST.D_InitialCollection(create, iterators), env)
1079 :     end
1080 :     (* end case *))
1081 : jhr 70
1082 : jhr 2660 (* check AST for unused variables *)
1083 :     fun checkForUnused cxt dcl = let
1084 : jhr 3082 fun chkVar x = if not(isUsed x)
1085 :     then warn (cxt, [
1086 :     S(Var.kindToString x), S " ", V x, S " declared at ",
1087 :     S(Error.locToString(getLoc x)), S " is unused"
1088 :     ])
1089 :     else ()
1090 :     fun chkVDcl (AST.VD_Decl(x, _)) = chkVar x
1091 :     fun chkStm stm = (case stm
1092 :     of AST.S_Block stms => List.app chkStm stms
1093 :     | AST.S_Decl vd => chkVDcl vd
1094 :     | AST.S_IfThenElse(_, s1, s2) => (chkStm s1; chkStm s2)
1095 :     | _ => ()
1096 :     (* end case *))
1097 :     in
1098 :     case dcl
1099 :     of AST.D_Input(x, _, _) => chkVar x
1100 :     | AST.D_Var vd => chkVDcl vd
1101 :     | AST.D_Func(f, params, body) => (
1102 :     chkVar f;
1103 :     List.app chkVar params;
1104 :     chkStm body)
1105 :     | AST.D_Strand(AST.Strand{state, methods, ...}) => let
1106 :     fun chkMeth (AST.M_Method(_, body)) = chkStm body
1107 :     in
1108 : jhr 2660 (* FIXME: should skip output variables! *)
1109 : jhr 3082 List.app chkVDcl state;
1110 :     List.app chkMeth methods
1111 :     end
1112 :     | AST.D_InitialArray _ => ()
1113 :     | AST.D_InitialCollection _ => ()
1114 :     (* end case *)
1115 :     end
1116 : jhr 2660
1117 : jhr 1301 (* reorder the declarations so that the input variables come first *)
1118 :     fun reorderDecls dcls = let
1119 : jhr 2356 fun isInput (AST.D_Input _) = true
1120 :     | isInput _ = false
1121 :     val (inputs, others) = List.partition isInput dcls
1122 :     in
1123 :     inputs @ others
1124 :     end
1125 : jhr 1301
1126 : jhr 86 fun check errStrm (PT.Program{span, tree}) = let
1127 : jhr 2356 val cxt = (errStrm, span)
1128 : jhr 2636 fun chk (env, [], dcls') = reorderDecls(List.rev dcls')
1129 : jhr 2356 | chk (env, dcl::dcls, dcls') = let
1130 :     val (dcl', env) = checkDecl (env, cxt, dcl)
1131 :     in
1132 :     chk (env, dcls, dcl'::dcls')
1133 :     end
1134 : jhr 2462 val env = Basis.env()
1135 : jhr 2636 val dcls' = chk ({scope=GlobalScope, bindings=AtomMap.empty, env=env}, tree, [])
1136 :     handle TypeError => []
1137 : jhr 2356 in
1138 : jhr 3082 List.app (checkForUnused cxt) dcls';
1139 : jhr 2636 AST.Program{
1140 :     props = Env.properties env,
1141 :     decls = dcls'
1142 :     }
1143 : jhr 2356 end
1144 : jhr 70
1145 : jhr 69 end

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