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

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2784 - (view) (download)

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

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