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

SCM Repository

[diderot] Annotation of /branches/staging/src/compiler/typechecker/typechecker.sml
ViewVC logotype

Annotation of /branches/staging/src/compiler/typechecker/typechecker.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2746 - (view) (download)

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

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