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

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

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