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

1 : jhr 69 (* typechecker.sml
2 :     *
3 : jhr 435 * COPYRIGHT (c) 2010 The Diderot Project (http://diderot-language.cs.uchicago.edu)
4 : jhr 69 * All rights reserved.
5 : jhr 228 *
6 : jhr 1116 * TODO:
7 :     * check that variables are not redefined in the same scope
8 :     * int --> real type promotion
9 :     * sequence operations
10 : jhr 69 *)
11 :    
12 :     structure Typechecker : sig
13 :    
14 : jhr 88 exception Error
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 511 datatype scope = GlobalScope | StrandScope | MethodScope | InitScope
27 : jhr 169
28 : jhr 1116 type env = {
29 :     scope : scope,
30 :     bindings : Error.location AtomMap.map,
31 :     env : Env.env
32 :     }
33 : jhr 228
34 : jhr 1116 type context = Error.err_stream * Error.span
35 : jhr 228
36 : jhr 1116 (* start a new scope *)
37 :     fun strandScope {scope, bindings, env} =
38 :     {scope=StrandScope, bindings=AtomMap.empty, env=env}
39 :     fun methodScope {scope, bindings, env} =
40 :     {scope=MethodScope, bindings=AtomMap.empty, env=env}
41 :     fun initScope {scope, bindings, env} =
42 :     {scope=InitScope, bindings=AtomMap.empty, env=env}
43 :     fun blockScope {scope, bindings, env} =
44 :     {scope=scope, bindings=AtomMap.empty, env=env}
45 :    
46 :     fun inStrand {scope=StrandScope, bindings, env} = true
47 : jhr 511 | inStrand {scope=MethodScope, ...} = true
48 :     | inStrand _ = false
49 : jhr 228
50 : jhr 1116 fun insertLocal ({scope, bindings, env}, cxt, x, x') = {
51 :     scope=scope,
52 :     bindings = AtomMap.insert(bindings, x, Error.location cxt),
53 :     env=Env.insertLocal(env, x, x')
54 :     }
55 :     fun insertGlobal ({scope, bindings, env}, cxt, x, x') = {
56 :     scope=scope,
57 :     bindings = AtomMap.insert(bindings, x, Error.location cxt),
58 :     env=Env.insertGlobal(env, x, x')
59 :     }
60 : jhr 228
61 : jhr 88 exception Error
62 :    
63 : jhr 86 fun withContext ((errStrm, _), {span, tree}) =
64 :     ((errStrm, span), tree)
65 :     fun withEnvAndContext (env, (errStrm, _), {span, tree}) =
66 :     (env, (errStrm, span), tree)
67 :    
68 : jhr 88 fun error ((errStrm, span), msg) = (
69 :     Error.errorAt(errStrm, span, msg);
70 :     raise Error)
71 : jhr 86
72 : jhr 88 datatype token
73 :     = S of string | A of Atom.atom
74 :     | V of AST.var | TY of Types.ty | TYS of Types.ty list
75 :    
76 : jhr 1925 fun tysToString tys = String.concat[
77 :     "(", String.concatWith " * " (List.map TU.toString tys), ")"
78 :     ]
79 :    
80 : jhr 88 fun err (cxt, toks) = let
81 :     fun tok2str (S s) = s
82 :     | tok2str (A a) = Atom.toString a
83 :     | tok2str (V x) = Var.nameOf x
84 : jhr 96 | tok2str (TY ty) = TU.toString ty
85 : jhr 88 | tok2str (TYS []) = "()"
86 : jhr 96 | tok2str (TYS[ty]) = TU.toString ty
87 : jhr 1925 | tok2str (TYS tys) = tysToString tys
88 : jhr 88 in
89 :     error(cxt, List.map tok2str toks)
90 :     end
91 :    
92 : jhr 1116 fun checkForRedef (env : env, cxt : context, x) = (case AtomMap.find(#bindings env,x)
93 :     of SOME loc => err (cxt, [
94 :     S "redefinition of ", A x, S ", previous definition at ",
95 :     S(Error.locToString loc)
96 :     ])
97 :     | NONE => ()
98 :     (* end case *))
99 :    
100 : jhr 83 val realZero = AST.E_Lit(Literal.Float(FloatLit.zero true))
101 :    
102 : jhr 70 (* check a differentiation level, which muse be >= 0 *)
103 :     fun checkDiff (cxt, k) =
104 :     if (k < 0)
105 : jhr 1116 then err (cxt, [S "differentiation must be >= 0"])
106 : jhr 75 else Ty.DiffConst(IntInf.toInt k)
107 : jhr 70
108 : jhr 1116 (* check a dimension, which must be 1, 2 or 3 *)
109 : jhr 70 fun checkDim (cxt, d) =
110 : jhr 1116 if (d < 1) orelse (3 < d)
111 :     then err (cxt, [S "invalid dimension; must be 1, 2, or 3"])
112 : jhr 75 else Ty.DimConst(IntInf.toInt d)
113 : jhr 70
114 :     (* check a shape *)
115 : jhr 1116 fun checkShape (cxt, shape) = let
116 :     fun checkDim d =
117 :     if (d <= 1)
118 :     then err (cxt, [S "invalid tensor-shape dimension; must be > 1"])
119 :     else Ty.DimConst(IntInf.toInt d)
120 : jhr 70 in
121 : jhr 1116 Ty.Shape(List.map checkDim shape)
122 : jhr 70 end
123 :    
124 : jhr 69 (* check the well-formedness of a type and translate it to an AST type *)
125 : jhr 70 fun checkTy (cxt, ty) = (case ty
126 : jhr 86 of PT.T_Mark m => checkTy(withContext(cxt, m))
127 : jhr 70 | PT.T_Bool => Ty.T_Bool
128 :     | PT.T_Int => Ty.T_Int
129 :     | PT.T_Real => Ty.realTy
130 :     | PT.T_String => Ty.T_String
131 :     | PT.T_Vec n => (* NOTE: the parser guarantees that 2 <= n <= 4 *)
132 :     Ty.vecTy(IntInf.toInt n)
133 :     | PT.T_Kernel k => Ty.T_Kernel(checkDiff(cxt, k))
134 :     | PT.T_Field{diff, dim, shape} => Ty.T_Field{
135 :     diff = checkDiff (cxt, diff),
136 :     dim = checkDim (cxt, dim),
137 :     shape = checkShape (cxt, shape)
138 :     }
139 :     | PT.T_Tensor shape => Ty.T_Tensor(checkShape(cxt, shape))
140 :     | PT.T_Image{dim, shape} => Ty.T_Image{
141 :     dim = checkDim (cxt, dim),
142 :     shape = checkShape (cxt, shape)
143 :     }
144 : jhr 1640 | PT.T_Seq(ty, dim) => let
145 :     val ty = checkTy(cxt, ty)
146 :     in
147 : jhr 1687 if TU.isFixedSizeType ty
148 : jhr 1640 then Ty.T_Sequence(ty, checkDim (cxt, dim))
149 : jhr 1687 else err(cxt, [S "elements of sequence types must be fixed-size types"])
150 : jhr 1640 end
151 : jhr 1687 | PT.T_DynSeq ty => let
152 :     val ty = checkTy(cxt, ty)
153 :     in
154 :     if TU.isFixedSizeType ty
155 :     then Ty.T_DynSequence(ty)
156 :     else err(cxt, [S "elements of sequence types must be fixed-size types"])
157 :     end
158 : jhr 69 (* end case *))
159 :    
160 : jhr 71 fun checkLit lit = (case lit
161 :     of (Literal.Int _) => (AST.E_Lit lit, Ty.T_Int)
162 :     | (Literal.Float _) => (AST.E_Lit lit, Ty.realTy)
163 :     | (Literal.String s) => (AST.E_Lit lit, Ty.T_String)
164 :     | (Literal.Bool _) => (AST.E_Lit lit, Ty.T_Bool)
165 :     (* end case *))
166 :    
167 : jhr 1971 fun coerceType (ty1, ty2, e) = (case U.matchType(ty1, ty2)
168 :     of U.EQ => SOME e
169 :     | U.COERCE => SOME(AST.E_Coerce{srcTy=ty2, dstTy=ty1, e=e})
170 :     | U.FAIL => NONE
171 :     (* end case *))
172 :    
173 :     fun realType (ty as Ty.T_Tensor(Ty.Shape[])) = ty
174 :     | realType (ty as Ty.T_Int) = Ty.realTy
175 :     | realType ty = ty
176 :    
177 : jhr 85 (* resolve overloading: we use a simple scheme that selects the first operator in the
178 :     * list that matches the argument types.
179 :     *)
180 : jhr 1116 fun resolveOverload (_, rator, _, _, []) = raise Fail(concat[
181 :     "resolveOverload: \"", Atom.toString rator, "\" has no candidates"
182 :     ])
183 :     | resolveOverload (cxt, rator, argTys, args, candidates) = let
184 : jhr 1971 (* FIXME: we could be more efficient by just checking for coercion matchs the first pass
185 :     * and remembering those that are not pure EQ matches.
186 :     *)
187 :     (* try to match candidates while allowing type coercions *)
188 :     fun tryMatchCandidates [] = err(cxt, [
189 : jhr 91 S "unable to resolve overloaded operator \"", A rator, S "\"\n",
190 :     S " argument type is: ", TYS argTys, S "\n"
191 : jhr 85 ])
192 : jhr 1971 | tryMatchCandidates (x::xs) = let
193 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
194 :     in
195 : jhr 1973 case U.tryMatchArgs (domTy, args, argTys)
196 :     of SOME args' => (AST.E_Apply(x, tyArgs, args', rngTy), rngTy)
197 :     | NONE => tryMatchCandidates xs
198 :     (* end case *)
199 : jhr 1971 end
200 :     fun tryCandidates [] = tryMatchCandidates candidates
201 : jhr 85 | tryCandidates (x::xs) = let
202 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
203 :     in
204 : jhr 1971 if U.tryEqualTypes(domTy, argTys)
205 : jhr 85 then (AST.E_Apply(x, tyArgs, args, rngTy), rngTy)
206 :     else tryCandidates xs
207 :     end
208 :     in
209 :     tryCandidates candidates
210 :     end
211 :    
212 : jhr 70 (* typecheck an expression and translate it to AST *)
213 : jhr 169 fun checkExpr (env : env, cxt, e) = (case e
214 : jhr 86 of PT.E_Mark m => checkExpr (withEnvAndContext (env, cxt, m))
215 : jhr 169 | PT.E_Var x => (case Env.findVar (#env env, x)
216 : jhr 171 of SOME x' => (AST.E_Var x', Var.monoTypeOf x')
217 : jhr 88 | NONE => err(cxt, [S "undeclared variable ", A x])
218 : jhr 71 (* end case *))
219 :     | PT.E_Lit lit => checkLit lit
220 : jhr 81 | PT.E_OrElse(e1, e2) => let
221 :     val (e1', ty1) = checkExpr(env, cxt, e1)
222 :     val (e2', ty2) = checkExpr(env, cxt, e2)
223 :     in
224 :     case (ty1, ty2)
225 :     of (Ty.T_Bool, Ty.T_Bool) =>
226 : jhr 416 (AST.E_Cond(e1', AST.E_Lit(Literal.Bool true), e2', Ty.T_Bool), Ty.T_Bool)
227 : jhr 99 | _ => err (cxt, [S "arguments to \"||\" must have bool type"])
228 : jhr 81 (* end case *)
229 :     end
230 :     | PT.E_AndAlso(e1, e2) => let
231 :     val (e1', ty1) = checkExpr(env, cxt, e1)
232 :     val (e2', ty2) = checkExpr(env, cxt, e2)
233 :     in
234 :     case (ty1, ty2)
235 :     of (Ty.T_Bool, Ty.T_Bool) =>
236 : jhr 416 (AST.E_Cond(e1', e2', AST.E_Lit(Literal.Bool false), Ty.T_Bool), Ty.T_Bool)
237 : jhr 99 | _ => err (cxt, [S "arguments to \"&&\" must have bool type"])
238 : jhr 81 (* end case *)
239 :     end
240 : jhr 370 | PT.E_Cond(e1, cond, e2) => let
241 :     val (e1', ty1) = checkExpr(env, cxt, e1)
242 :     val (e2', ty2) = checkExpr(env, cxt, e2)
243 :     in
244 :     case checkExpr(env, cxt, cond)
245 :     of (cond', Ty.T_Bool) =>
246 : jhr 1687 if U.equalType(ty1, ty2)
247 : jhr 416 then (AST.E_Cond(cond', e1', e2', ty1), ty1)
248 : jhr 370 else err (cxt, [
249 :     S "type do not match in conditional expression\n",
250 : jhr 1116 S " true branch: ", TY ty1, S "\n",
251 : jhr 370 S " false branch: ", TY ty2
252 :     ])
253 :     | (_, ty') => err (cxt, [S "expected bool type, but found ", TY ty'])
254 :     (* end case *)
255 :     end
256 : jhr 81 | PT.E_BinOp(e1, rator, e2) => let
257 :     val (e1', ty1) = checkExpr(env, cxt, e1)
258 :     val (e2', ty2) = checkExpr(env, cxt, e2)
259 :     in
260 : jhr 1116 if Atom.same(rator, BasisNames.op_dot)
261 :     (* we have to handle inner product as a special case, because out type
262 :     * system cannot express the constraint that the type is
263 :     * ALL[sigma1, d1, sigma2] . tensor[sigma1, d1] * tensor[d1, sigma2] -> tensor[sigma1, sigma2]
264 :     *)
265 :     then (case (TU.prune ty1, TU.prune ty2)
266 :     of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_)), Ty.T_Tensor(s2 as Ty.Shape(d2::dd2))) => let
267 :     val (dd1, d1) = let
268 :     fun splitLast (prefix, [d]) = (List.rev prefix, d)
269 :     | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
270 :     | splitLast (_, []) = raise Fail "impossible"
271 :     in
272 :     splitLast ([], dd1)
273 :     end
274 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_inner)
275 :     val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
276 :     in
277 : jhr 1687 if U.equalDim(d1, d2)
278 :     andalso U.equalTypes(domTy, [ty1, ty2])
279 :     andalso U.equalType(rngTy, resTy)
280 : jhr 1116 then (AST.E_Apply(BV.op_inner, tyArgs, [e1', e2'], rngTy), rngTy)
281 :     else err (cxt, [
282 :     S "type error for arguments of binary operator \"•\"\n",
283 :     S " found: ", TYS[ty1, ty2], S "\n"
284 :     ])
285 :     end
286 :     | (ty1, ty2) => err (cxt, [
287 :     S "type error for arguments of binary operator \"•\"\n",
288 :     S " found: ", TYS[ty1, ty2], S "\n"
289 :     ])
290 :     (* end case *))
291 : jhr 1945 else if Atom.same(rator, BasisNames.op_colon)
292 :     then (case (TU.prune ty1, TU.prune ty2)
293 :     of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_::_)), Ty.T_Tensor(s2 as Ty.Shape(d21::d22::dd2))) => let
294 :     val (dd1, d11, d12) = let
295 :     fun splitLast (prefix, [d1, d2]) = (List.rev prefix, d1, d2)
296 :     | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
297 :     | splitLast (_, []) = raise Fail "impossible"
298 :     in
299 :     splitLast ([], dd1)
300 :     end
301 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_colon)
302 :     val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
303 :     in
304 :     if U.equalDim(d11, d21) andalso U.equalDim(d12, d22)
305 :     andalso U.equalTypes(domTy, [ty1, ty2])
306 :     andalso U.equalType(rngTy, resTy)
307 :     then (AST.E_Apply(BV.op_colon, tyArgs, [e1', e2'], rngTy), rngTy)
308 :     else err (cxt, [
309 :     S "type error for arguments of binary operator \":\"\n",
310 :     S " found: ", TYS[ty1, ty2], S "\n"
311 :     ])
312 :     end
313 :     | (ty1, ty2) => err (cxt, [
314 :     S "type error for arguments of binary operator \":\"\n",
315 :     S " found: ", TYS[ty1, ty2], S "\n"
316 :     ])
317 :     (* end case *))
318 : jhr 1116 else (case Env.findFunc (#env env, rator)
319 :     of [rator] => let
320 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
321 :     in
322 : jhr 1975 case U.matchArgs(domTy, [e1', e2'], [ty1, ty2])
323 :     of SOME args => (AST.E_Apply(rator, tyArgs, args, rngTy), rngTy)
324 :     | NONE => err (cxt, [
325 :     S "type error for binary operator \"", V rator, S "\"\n",
326 :     S " expected: ", TYS domTy, S "\n",
327 :     S " but found: ", TYS[ty1, ty2]
328 :     ])
329 :     (* end case *)
330 : jhr 1116 end
331 :     | ovldList => resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
332 :     (* end case *))
333 : jhr 81 end
334 :     | PT.E_UnaryOp(rator, e) => let
335 :     val (e', ty) = checkExpr(env, cxt, e)
336 :     in
337 : jhr 1116 case Env.findFunc (#env env, rator)
338 : jhr 81 of [rator] => let
339 : jhr 381 val (tyArgs, Ty.T_Fun([domTy], rngTy)) = U.instantiate(Var.typeOf rator)
340 : jhr 81 in
341 : jhr 1975 case coerceType (domTy, ty, e')
342 :     of SOME e' => (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
343 :     | NONE => err (cxt, [
344 :     S "type error for unary operator \"", V rator, S "\"\n",
345 :     S " expected: ", TY domTy, S "\n",
346 :     S " but found: ", TY ty
347 :     ])
348 :     (* end case *)
349 : jhr 81 end
350 : jhr 91 | ovldList => resolveOverload (cxt, rator, [ty], [e'], ovldList)
351 : jhr 81 (* end case *)
352 :     end
353 : jhr 381 | PT.E_Slice(e, indices) => let
354 :     val (e', ty) = checkExpr (env, cxt, e)
355 :     fun checkIndex NONE = NONE
356 :     | checkIndex (SOME e) = let
357 :     val (e', ty) = checkExpr (env, cxt, e)
358 :     in
359 : jhr 1687 if U.equalType(ty, Ty.T_Int)
360 : jhr 381 then (SOME e')
361 :     else err (cxt, [
362 :     S "type error in index expression\n",
363 : jhr 1116 S " expected int, but found: ", TY ty
364 : jhr 381 ])
365 :     end
366 :     val indices' = List.map checkIndex indices
367 :     val order = List.length indices'
368 : jhr 399 val expectedTy = TU.mkTensorTy order
369 :     val resultTy = TU.slice(expectedTy, List.map Option.isSome indices')
370 : jhr 381 in
371 : jhr 1687 if U.equalType(ty, expectedTy)
372 : jhr 381 then ()
373 :     else err (cxt, [
374 :     S "type error in slice operation\n",
375 :     S " expected: ", S(Int.toString order), S "-order tensor\n",
376 : jhr 1116 S " but found: ", TY ty
377 : jhr 381 ]);
378 : jhr 399 (AST.E_Slice(e', indices', resultTy), resultTy)
379 : jhr 381 end
380 : jhr 1116 | PT.E_Subscript(e1, e2) => let
381 :     val (e1', ty1) = checkExpr (env, cxt, e1)
382 :     val (e2', ty2) = checkExpr (env, cxt, e2)
383 : jhr 1991 fun chkIndex () = if U.equalType(ty2, Ty.T_Int)
384 :     then ()
385 :     else err (cxt, [
386 :     S "expected int type for subscript index\n",
387 :     S " but found: ", TY ty2
388 :     ])
389 :     fun finish rator = let
390 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = U.instantiate(Var.typeOf rator)
391 :     in
392 :     if U.equalTypes(domTy, [ty1, ty2])
393 :     then let
394 :     val exp = AST.E_Apply(BV.subscript, tyArgs, [e1', e2'], rngTy)
395 :     in
396 :     (exp, rngTy)
397 :     end
398 :     else raise Fail "unexpected unification failure"
399 :     end
400 : jhr 1116 in
401 : jhr 1991 case TU.pruneHead ty1
402 :     of Ty.T_DynSequence _ => (
403 :     chkIndex ();
404 :     finish BV.dynSubscript)
405 :     | Ty.T_Sequence _ => (
406 :     chkIndex ();
407 :     finish BV.subscript)
408 :     | _ => err (cxt, [
409 :     S "expected sequence type for subscript\n",
410 :     S " but found: ", TY ty1
411 :     ])
412 :     (* end case *)
413 : jhr 1116 end
414 :     | PT.E_Apply(e, args) => let
415 :     fun stripMark (PT.E_Mark{tree, ...}) = stripMark tree
416 :     | stripMark e = e
417 :     val (args, tys) = checkExprList (env, cxt, args)
418 :     fun checkFieldApp (e1', ty1) = (case (args, tys)
419 :     of ([e2'], [ty2]) => let
420 : jhr 1975 val (tyArgs, Ty.T_Fun([fldTy, domTy], rngTy)) =
421 : jhr 1687 Util.instantiate(Var.typeOf BV.op_probe)
422 : jhr 1975 fun tyError () = err (cxt, [
423 : jhr 1116 S "type error for field application\n",
424 : jhr 1975 S " expected: ", TYS[fldTy, domTy], S "\n",
425 : jhr 1116 S " but found: ", TYS[ty1, ty2]
426 :     ])
427 : jhr 1975 in
428 :     if U.equalType(fldTy, ty1)
429 :     then (case coerceType(domTy, ty2, e2')
430 :     of SOME e2' => (AST.E_Apply(BV.op_probe, tyArgs, [e1', e2'], rngTy), rngTy)
431 :     | NONE => tyError()
432 :     (* end case *))
433 :     else tyError()
434 : jhr 1116 end
435 :     | _ => err(cxt, [S "badly formed field application"])
436 :     (* end case *))
437 :     in
438 :     case stripMark e
439 :     of PT.E_Var f => (case Env.findVar (#env env, f)
440 :     of SOME f' => checkFieldApp (AST.E_Var f', Var.monoTypeOf f')
441 :     | NONE => (case Env.findFunc (#env env, f)
442 :     of [] => err(cxt, [S "unknown function ", A f])
443 :     | [f] =>
444 :     if (inStrand env) andalso (Basis.isRestricted f)
445 :     then err(cxt, [
446 :     S "use of restricted operation ", V f,
447 :     S " in strand body"
448 :     ])
449 :     else (case Util.instantiate(Var.typeOf f)
450 : jhr 1975 of (tyArgs, Ty.T_Fun(domTy, rngTy)) => (
451 :     case U.matchArgs (domTy, args, tys)
452 :     of SOME args => (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
453 :     | NONE => err(cxt, [
454 :     S "type error in application of ", V f, S "\n",
455 :     S " expected: ", TYS domTy, S "\n",
456 :     S " but found: ", TYS tys
457 :     ])
458 :     (* end case *))
459 : jhr 1116 | _ => err(cxt, [S "application of non-function ", V f])
460 :     (* end case *))
461 :     | ovldList => resolveOverload (cxt, f, tys, args, ovldList)
462 :     (* end case *))
463 :     (* end case *))
464 :     | _ => checkFieldApp (checkExpr (env, cxt, e))
465 :     (* end case *)
466 :     end
467 : jhr 81 | PT.E_Tuple args => let
468 :     val (args, tys) = checkExprList (env, cxt, args)
469 :     in
470 : jhr 1116 raise Fail "E_Tuple not yet implemented" (* FIXME *)
471 : jhr 81 end
472 : jhr 1116 | PT.E_Sequence args => let
473 : jhr 1640 val (args, ty::tys) = checkExprList (env, cxt, args)
474 : jhr 81 in
475 : jhr 1687 if TU.isFixedSizeType(TU.pruneHead ty)
476 : jhr 1640 then let
477 : jhr 1687 fun chkTy ty' = U.equalType(ty, ty')
478 : jhr 1640 val resTy = Ty.T_Sequence(ty, Ty.DimConst(List.length args))
479 :     in
480 :     if List.all chkTy tys
481 : jhr 1688 then (AST.E_Seq args, resTy)
482 : jhr 1640 else err(cxt, [S "arguments of sequence expression must have same type"])
483 :     end
484 :     else err(cxt, [S "sequence expression of non-value argument type"])
485 : jhr 81 end
486 : jhr 86 | PT.E_Cons args => let
487 : jhr 1971 val (args, tys as ty::_) = checkExprList (env, cxt, args)
488 : jhr 81 in
489 : jhr 1971 case realType(TU.pruneHead ty)
490 : jhr 475 of ty as Ty.T_Tensor shape => let
491 :     val Ty.Shape dd = TU.pruneShape shape (* NOTE: this may fail if we allow user polymorphism *)
492 :     val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
493 : jhr 1971 fun chkArgs (arg::args, argTy::tys, args') = (case coerceType(ty, argTy, arg)
494 :     of SOME arg' => chkArgs (args, tys, arg'::args')
495 :     | NONE => err(cxt, [S "arguments of tensor construction must have same type"])
496 :     (* end case *))
497 :     | chkArgs ([], [], args') = (AST.E_Cons(List.rev args'), resTy)
498 : jhr 83 in
499 : jhr 1971 chkArgs (args, tys, [])
500 : jhr 83 end
501 : jhr 99 | _ => err(cxt, [S "Invalid argument type for tensor construction"])
502 : jhr 83 (* end case *)
503 : jhr 81 end
504 : jhr 86 | PT.E_Real e => (case checkExpr (env, cxt, e)
505 :     of (e', Ty.T_Int) =>
506 : jhr 1116 (AST.E_Apply(BV.i2r, [], [e'], Ty.realTy), Ty.realTy)
507 : jhr 99 | _ => err(cxt, [S "argument of real conversion must be int"])
508 : jhr 86 (* end case *))
509 : jhr 1116 | PT.E_Id d => let
510 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
511 :     Util.instantiate(Var.typeOf(BV.identity))
512 :     in
513 : jhr 1687 if U.equalType(Ty.T_Tensor(checkShape(cxt, [d,d])), rngTy)
514 : jhr 1116 then (AST.E_Apply(BV.identity, tyArgs, [], rngTy), rngTy)
515 :     else raise Fail "impossible"
516 :     end
517 :     | PT.E_Zero dd => let
518 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
519 :     Util.instantiate(Var.typeOf(BV.zero))
520 :     in
521 : jhr 1687 if U.equalType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
522 : jhr 1116 then (AST.E_Apply(BV.zero, tyArgs, [], rngTy), rngTy)
523 :     else raise Fail "impossible"
524 :     end
525 : jhr 1992 | PT.E_Image nrrd => let
526 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf(BV.fn_image))
527 :     in
528 :     (AST.E_LoadNrrd(tyArgs, nrrd, rngTy), rngTy)
529 :     end
530 :     | PT.E_Load nrrd => let
531 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf(BV.fn_load))
532 :     in
533 :     (AST.E_LoadNrrd(tyArgs, nrrd, rngTy), rngTy)
534 :     end
535 : jhr 70 (* end case *))
536 :    
537 : jhr 81 (* typecheck a list of expressions returning a list of AST expressions and a list
538 :     * of types of the expressions.
539 :     *)
540 :     and checkExprList (env, cxt, exprs) = let
541 :     fun chk (e, (es, tys)) = let
542 :     val (e, ty) = checkExpr (env, cxt, e)
543 :     in
544 :     (e::es, ty::tys)
545 :     end
546 :     in
547 :     List.foldr chk ([], []) exprs
548 :     end
549 :    
550 : jhr 72 fun checkVarDecl (env, cxt, kind, d) = (case d
551 : jhr 86 of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
552 : jhr 72 | PT.VD_Decl(ty, x, e) => let
553 : jhr 81 val ty = checkTy (cxt, ty)
554 : jhr 72 val x' = Var.new (x, kind, ty)
555 :     val (e', ty') = checkExpr (env, cxt, e)
556 :     in
557 : jhr 1687 case coerceType (ty, ty', e')
558 : jhr 1971 of SOME e' => (x, x', e')
559 : jhr 1687 | NONE => err(cxt, [
560 : jhr 99 S "type of variable ", A x,
561 :     S " does not match type of initializer\n",
562 :     S " expected: ", TY ty, S "\n",
563 : jhr 1116 S " but found: ", TY ty'
564 : jhr 99 ])
565 : jhr 1687 (* end case *)
566 : jhr 72 end
567 :     (* end case *))
568 :    
569 : jhr 70 (* typecheck a statement and translate it to AST *)
570 : jhr 71 fun checkStmt (env, cxt, s) = (case s
571 : jhr 86 of PT.S_Mark m => checkStmt (withEnvAndContext (env, cxt, m))
572 : jhr 72 | PT.S_Block stms => let
573 :     fun chk (_, [], stms) = AST.S_Block(List.rev stms)
574 :     | chk (env, s::ss, stms) = let
575 :     val (s', env') = checkStmt (env, cxt, s)
576 :     in
577 : jhr 81 chk (env', ss, s'::stms)
578 : jhr 72 end
579 :     in
580 : jhr 1116 (chk (blockScope env, stms, []), env)
581 : jhr 72 end
582 :     | PT.S_Decl vd => let
583 : jhr 1116 val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
584 : jhr 72 in
585 : jhr 1116 checkForRedef (env, cxt, x);
586 :     (AST.S_Decl(AST.VD_Decl(x', e)), insertLocal(env, cxt, x, x'))
587 : jhr 72 end
588 :     | PT.S_IfThen(e, s) => let
589 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
590 : jhr 81 val (s', _) = checkStmt (env, cxt, s)
591 : jhr 72 in
592 :     (* check that condition has bool type *)
593 :     case ty
594 :     of Ty.T_Bool => ()
595 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
596 : jhr 72 (* end case *);
597 :     (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
598 :     end
599 :     | PT.S_IfThenElse(e, s1, s2) => let
600 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
601 : jhr 81 val (s1', _) = checkStmt (env, cxt, s1)
602 :     val (s2', _) = checkStmt (env, cxt, s2)
603 : jhr 72 in
604 :     (* check that condition has bool type *)
605 :     case ty
606 :     of Ty.T_Bool => ()
607 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
608 : jhr 72 (* end case *);
609 :     (AST.S_IfThenElse(e', s1', s2'), env)
610 :     end
611 : jhr 228 | PT.S_Assign(x, e) => (case Env.findVar (#env env, x)
612 : jhr 99 of NONE => err(cxt, [
613 :     S "undefined variable ", A x
614 :     ])
615 : jhr 72 | SOME x' => let
616 : jhr 99 (* FIXME: check for polymorphic variables *)
617 :     val ([], ty) = Var.typeOf x'
618 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
619 : jhr 1975 (* check for promotion *)
620 :     val e' = (case coerceType(ty, ty', e')
621 :     of SOME e' => e'
622 :     | NONE => err(cxt, [
623 :     S "type of assigned variable ", A x,
624 :     S " does not match type of rhs\n",
625 :     S " expected: ", TY ty, S "\n",
626 :     S " but found: ", TY ty'
627 :     ])
628 :     (* end case *))
629 : jhr 72 in
630 :     (* check that x' is mutable *)
631 :     case Var.kindOf x'
632 : jhr 511 of Var.StrandStateVar => ()
633 :     | Var.StrandOutputVar => ()
634 : jhr 72 | Var.LocalVar => ()
635 : jhr 99 | _ => err(cxt, [
636 :     S "assignment to immutable variable ", A x
637 :     ])
638 : jhr 72 (* end case *);
639 :     (AST.S_Assign(x', e'), env)
640 :     end
641 :     (* end case *))
642 : jhr 1296 | PT.S_OpAssign(x, rator, e) => (case Env.findVar (#env env, x)
643 :     of SOME x' => let
644 :     val e1' = AST.E_Var x'
645 :     val ty1 = Var.monoTypeOf x'
646 :     val (e2', ty2) = checkExpr(env, cxt, e)
647 :     val ovldList = Env.findFunc (#env env, rator)
648 :     val (rhs, _) = resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
649 :     in
650 :     (AST.S_Assign(x', rhs), env)
651 :     end
652 :     | NONE => err(cxt, [S "undeclared variable ", A x, S " on lhs of ", A rator])
653 :     (* end case *))
654 : jhr 511 | PT.S_New(strand, args) => let
655 : jhr 228 val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
656 : jhr 81 val (args', tys') = ListPair.unzip argsAndTys'
657 : jhr 72 in
658 : jhr 228 case #scope env
659 :     of MethodScope => ()
660 :     | InitScope => ()
661 : jhr 511 | _ => err(cxt, [S "invalid scope for new strand"])
662 : jhr 228 (* end case *);
663 : jhr 511 (* FIXME: check that strand is defined and has the argument types match *)
664 :     (AST.S_New(strand, args'), env)
665 : jhr 72 end
666 : jhr 228 | PT.S_Die => (
667 :     case #scope env
668 : jhr 235 of MethodScope => ()
669 :     | _ => err(cxt, [S "\"die\" statment outside of method"])
670 : jhr 228 (* end case *);
671 :     (AST.S_Die, env))
672 :     | PT.S_Stabilize => (
673 :     case #scope env
674 : jhr 235 of MethodScope => ()
675 :     | _ => err(cxt, [S "\"stabilize\" statment outside of method"])
676 : jhr 228 (* end case *);
677 :     (AST.S_Stabilize, env))
678 : jhr 1640 | PT.S_Print args => let
679 :     fun chkArg e = let
680 :     val (e', ty) = checkExpr (env, cxt, e)
681 :     in
682 :     if TU.isValueType ty
683 :     then ()
684 :     else err(cxt, [
685 :     S "expected value type in print, but found ", TY ty
686 :     ]);
687 :     e'
688 :     end
689 :     val args' = List.map chkArg args
690 :     in
691 :     (AST.S_Print args', env)
692 :     end
693 : jhr 70 (* end case *))
694 :    
695 : jhr 82 fun checkParams (env, cxt, params) = let
696 :     fun chkParam (env, cxt, param) = (case param
697 : jhr 86 of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
698 : jhr 82 | PT.P_Param(ty, x) => let
699 : jhr 511 val x' = Var.new(x, AST.StrandParam, checkTy (cxt, ty))
700 : jhr 82 in
701 : jhr 1116 checkForRedef (env, cxt, x);
702 :     (x', insertLocal(env, cxt, x, x'))
703 : jhr 82 end
704 :     (* end case *))
705 :     fun chk (param, (xs, env)) = let
706 :     val (x, env) = chkParam (env, cxt, param)
707 :     in
708 :     (x::xs, env)
709 :     end
710 :     in
711 :     (* FIXME: need to check for multiple occurences of the same parameter name! *)
712 :     List.foldr chk ([], env) params
713 :     end
714 :    
715 :     fun checkMethod (env, cxt, meth) = (case meth
716 : jhr 86 of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
717 : jhr 82 | PT.M_Method(name, body) => let
718 : jhr 228 val (body, _) = checkStmt(methodScope env, cxt, body)
719 : jhr 82 in
720 :     AST.M_Method(name, body)
721 :     end
722 :     (* end case *))
723 :    
724 : jhr 511 fun checkStrand (env, cxt, {name, params, state, methods}) = let
725 :     (* check the strand parameters *)
726 : jhr 82 val (params, env) = checkParams (env, cxt, params)
727 : jhr 511 (* check the strand state variable definitions *)
728 : jhr 82 val (vds, env) = let
729 : jhr 164 fun checkStateVar ((isOut, vd), (vds, env)) = let
730 : jhr 511 val kind = if isOut then AST.StrandOutputVar else AST.StrandStateVar
731 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, kind, vd)
732 : jhr 82 in
733 : jhr 228 (* check that output variables have value types *)
734 :     if isOut andalso not(TU.isValueType(Var.monoTypeOf x'))
735 :     then err(cxt, [
736 :     S "output variable ", V x', S " has non-value type ",
737 :     TY(Var.monoTypeOf x')
738 :     ])
739 :     else ();
740 : jhr 1116 checkForRedef (env, cxt, x);
741 :     (AST.VD_Decl(x', e')::vds, insertLocal(env, cxt, x, x'))
742 : jhr 82 end
743 :     val (vds, env) = List.foldl checkStateVar ([], env) state
744 :     in
745 :     (List.rev vds, env)
746 :     end
747 : jhr 511 (* check the strand methods *)
748 : jhr 82 val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
749 : jhr 1444 (* get the list of methods defined by the user *)
750 :     val methodNames = List.map (fn (AST.M_Method(name, _)) => name) methods
751 : jhr 1116 (* if the stabilize method is not provided, add one *)
752 : jhr 1640 val methods = if List.exists (fn StrandUtil.Stabilize => true | _ => false) methodNames
753 : jhr 1116 then methods
754 : jhr 1640 else methods @ [AST.M_Method(StrandUtil.Stabilize, AST.S_Block[])]
755 : jhr 82 in
756 : jhr 1444 (* FIXME: should check for duplicate method definitions *)
757 : jhr 1640 if not(List.exists (fn StrandUtil.Update => true | _ => false) methodNames)
758 : jhr 1116 then err(cxt, [S "strand ", A name, S " is missing an update method"])
759 :     else ();
760 : jhr 511 AST.D_Strand{name = name, params = params, state = vds, methods = methods}
761 : jhr 82 end
762 :    
763 : jhr 89 fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
764 : jhr 511 | checkCreate (env, cxt, PT.C_Create(strand, args)) = let
765 : jhr 228 val (args, tys) = checkExprList (env, cxt, args)
766 : jhr 89 in
767 : jhr 511 (* FIXME: check against strand definition *)
768 :     AST.C_Create(strand, args)
769 : jhr 89 end
770 :    
771 : jhr 1116 fun checkIters (env0, cxt, iters) = let
772 :     (* check an iteration range specification from the initially clause. We do the checking
773 :     * of the expressions using env0, which does not have any of the iteration variables in
774 :     * it (the iteration is rectangular), but we also accumulate the iteration bindings,
775 :     * which are used to create the final environment for checking the create call.
776 :     *)
777 :     fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
778 :     | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
779 :     val (e1', ty1) = checkExpr (env, cxt, e1)
780 :     val (e2', ty2) = checkExpr (env, cxt, e2)
781 :     val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
782 : jhr 89 in
783 : jhr 1116 case (ty1, ty2)
784 :     of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), (x, x'))
785 :     | _ => err(cxt, [
786 :     S "range expressions must have integer type\n",
787 :     S " but found: ", TY ty1, S " .. ", TY ty2
788 :     ])
789 :     (* end case *)
790 : jhr 89 end
791 : jhr 1116 fun chk ([], iters, bindings) =
792 :     (List.rev iters, List.foldl (fn ((x, x'), env) => insertLocal(env, cxt, x, x')) env0 bindings)
793 :     | chk (iter::rest, iters, bindings) = let
794 :     val (iter, binding) = checkIter (env0, cxt, iter)
795 :     in
796 :     chk (rest, iter::iters, binding::bindings)
797 :     end
798 : jhr 89 in
799 : jhr 1116 chk (iters, [], [])
800 : jhr 89 end
801 :    
802 : jhr 71 fun checkDecl (env, cxt, d) = (case d
803 : jhr 86 of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
804 : jhr 1301 | PT.D_Input(ty, x, desc, optExp) => let
805 :     (* FIXME: need to do something with the description *)
806 : jhr 71 val ty = checkTy(cxt, ty)
807 :     val x' = Var.new(x, Var.InputVar, ty)
808 :     val dcl = (case optExp
809 : jhr 1301 of NONE => AST.D_Input(x', desc, NONE)
810 : jhr 71 | SOME e => let
811 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
812 : jhr 71 in
813 : jhr 1971 case coerceType (ty, ty', e')
814 :     of SOME e' => AST.D_Input(x', desc, SOME e')
815 :     | NONE => err(cxt, [
816 :     S "definition of ", V x', S " has wrong type\n",
817 :     S " expected: ", TY ty, S "\n",
818 :     S " but found: ", TY ty'
819 :     ])
820 :     (* end case *)
821 : jhr 71 end
822 :     (* end case *))
823 :     in
824 : jhr 228 (* check that input variables have value types *)
825 :     if not(TU.isValueType ty)
826 :     then err(cxt, [S "input variable ", V x', S " has non-value type ", TY ty])
827 :     else ();
828 : jhr 1116 checkForRedef (env, cxt, x);
829 :     (dcl, insertGlobal(env, cxt, x, x'))
830 : jhr 71 end
831 : jhr 72 | PT.D_Var vd => let
832 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
833 : jhr 72 in
834 : jhr 1116 checkForRedef (env, cxt, x);
835 :     (AST.D_Var(AST.VD_Decl(x', e')), insertGlobal(env, cxt, x, x'))
836 : jhr 72 end
837 : jhr 511 | PT.D_Strand arg => (checkStrand(strandScope env, cxt, arg), env)
838 : jhr 89 | PT.D_InitialArray(create, iterators) => let
839 : jhr 228 val env = initScope env
840 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
841 :     val create = checkCreate (env', cxt, create)
842 :     in
843 :     (AST.D_InitialArray(create, iterators), env)
844 :     end
845 :     | PT.D_InitialCollection(create, iterators) => let
846 : jhr 228 val env = initScope env
847 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
848 :     val create = checkCreate (env', cxt, create)
849 :     in
850 :     (AST.D_InitialCollection(create, iterators), env)
851 :     end
852 : jhr 70 (* end case *))
853 :    
854 : jhr 1301 (* reorder the declarations so that the input variables come first *)
855 :     fun reorderDecls dcls = let
856 :     fun isInput (AST.D_Input _) = true
857 :     | isInput _ = false
858 :     val (inputs, others) = List.partition isInput dcls
859 :     in
860 :     inputs @ others
861 :     end
862 :    
863 : jhr 86 fun check errStrm (PT.Program{span, tree}) = let
864 :     val cxt = (errStrm, span)
865 : jhr 1301 fun chk (env, [], dcls') = AST.Program(reorderDecls(List.rev dcls'))
866 : jhr 81 | chk (env, dcl::dcls, dcls') = let
867 : jhr 86 val (dcl', env) = checkDecl (env, cxt, dcl)
868 : jhr 81 in
869 :     chk (env, dcls, dcl'::dcls')
870 :     end
871 :     in
872 : jhr 1116 chk ({scope=GlobalScope, bindings=AtomMap.empty, env=Basis.env}, tree, [])
873 : jhr 81 end
874 : jhr 70
875 : jhr 69 end

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