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

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2926 - (view) (download)

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

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