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 1975 - (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 1640 val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.subscript)
384 : jhr 1116 in
385 : jhr 1687 if U.equalTypes(domTy, [ty1, ty2])
386 : jhr 1640 then let
387 :     val exp = AST.E_Apply(BasisVars.subscript, tyArgs, [e1', e2'], rngTy)
388 :     in
389 :     (exp, rngTy)
390 :     end
391 :     else err (cxt, [
392 :     S "type error for sequence subscript\n",
393 :     S " expected: ", TYS domTy, S "\n",
394 :     S " but found: ", TYS[ty1, ty2]
395 :     ])
396 : jhr 1116 end
397 :     | PT.E_Apply(e, args) => let
398 :     fun stripMark (PT.E_Mark{tree, ...}) = stripMark tree
399 :     | stripMark e = e
400 :     val (args, tys) = checkExprList (env, cxt, args)
401 :     fun checkFieldApp (e1', ty1) = (case (args, tys)
402 :     of ([e2'], [ty2]) => let
403 : jhr 1975 val (tyArgs, Ty.T_Fun([fldTy, domTy], rngTy)) =
404 : jhr 1687 Util.instantiate(Var.typeOf BV.op_probe)
405 : jhr 1975 fun tyError () = err (cxt, [
406 : jhr 1116 S "type error for field application\n",
407 : jhr 1975 S " expected: ", TYS[fldTy, domTy], S "\n",
408 : jhr 1116 S " but found: ", TYS[ty1, ty2]
409 :     ])
410 : jhr 1975 in
411 :     if U.equalType(fldTy, ty1)
412 :     then (case coerceType(domTy, ty2, e2')
413 :     of SOME e2' => (AST.E_Apply(BV.op_probe, tyArgs, [e1', e2'], rngTy), rngTy)
414 :     | NONE => tyError()
415 :     (* end case *))
416 :     else tyError()
417 : jhr 1116 end
418 :     | _ => err(cxt, [S "badly formed field application"])
419 :     (* end case *))
420 :     in
421 :     case stripMark e
422 :     of PT.E_Var f => (case Env.findVar (#env env, f)
423 :     of SOME f' => checkFieldApp (AST.E_Var f', Var.monoTypeOf f')
424 :     | NONE => (case Env.findFunc (#env env, f)
425 :     of [] => err(cxt, [S "unknown function ", A f])
426 :     | [f] =>
427 :     if (inStrand env) andalso (Basis.isRestricted f)
428 :     then err(cxt, [
429 :     S "use of restricted operation ", V f,
430 :     S " in strand body"
431 :     ])
432 :     else (case Util.instantiate(Var.typeOf f)
433 : jhr 1975 of (tyArgs, Ty.T_Fun(domTy, rngTy)) => (
434 :     case U.matchArgs (domTy, args, tys)
435 :     of SOME args => (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
436 :     | NONE => err(cxt, [
437 :     S "type error in application of ", V f, S "\n",
438 :     S " expected: ", TYS domTy, S "\n",
439 :     S " but found: ", TYS tys
440 :     ])
441 :     (* end case *))
442 : jhr 1116 | _ => err(cxt, [S "application of non-function ", V f])
443 :     (* end case *))
444 :     | ovldList => resolveOverload (cxt, f, tys, args, ovldList)
445 :     (* end case *))
446 :     (* end case *))
447 :     | _ => checkFieldApp (checkExpr (env, cxt, e))
448 :     (* end case *)
449 :     end
450 : jhr 81 | PT.E_Tuple args => let
451 :     val (args, tys) = checkExprList (env, cxt, args)
452 :     in
453 : jhr 1116 raise Fail "E_Tuple not yet implemented" (* FIXME *)
454 : jhr 81 end
455 : jhr 1116 | PT.E_Sequence args => let
456 : jhr 1640 val (args, ty::tys) = checkExprList (env, cxt, args)
457 : jhr 81 in
458 : jhr 1687 if TU.isFixedSizeType(TU.pruneHead ty)
459 : jhr 1640 then let
460 : jhr 1687 fun chkTy ty' = U.equalType(ty, ty')
461 : jhr 1640 val resTy = Ty.T_Sequence(ty, Ty.DimConst(List.length args))
462 :     in
463 :     if List.all chkTy tys
464 : jhr 1688 then (AST.E_Seq args, resTy)
465 : jhr 1640 else err(cxt, [S "arguments of sequence expression must have same type"])
466 :     end
467 :     else err(cxt, [S "sequence expression of non-value argument type"])
468 : jhr 81 end
469 : jhr 86 | PT.E_Cons args => let
470 : jhr 1971 val (args, tys as ty::_) = checkExprList (env, cxt, args)
471 : jhr 81 in
472 : jhr 1971 case realType(TU.pruneHead ty)
473 : jhr 475 of ty as Ty.T_Tensor shape => let
474 :     val Ty.Shape dd = TU.pruneShape shape (* NOTE: this may fail if we allow user polymorphism *)
475 :     val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
476 : jhr 1971 fun chkArgs (arg::args, argTy::tys, args') = (case coerceType(ty, argTy, arg)
477 :     of SOME arg' => chkArgs (args, tys, arg'::args')
478 :     | NONE => err(cxt, [S "arguments of tensor construction must have same type"])
479 :     (* end case *))
480 :     | chkArgs ([], [], args') = (AST.E_Cons(List.rev args'), resTy)
481 : jhr 83 in
482 : jhr 1971 chkArgs (args, tys, [])
483 : jhr 83 end
484 : jhr 99 | _ => err(cxt, [S "Invalid argument type for tensor construction"])
485 : jhr 83 (* end case *)
486 : jhr 81 end
487 : jhr 86 | PT.E_Real e => (case checkExpr (env, cxt, e)
488 :     of (e', Ty.T_Int) =>
489 : jhr 1116 (AST.E_Apply(BV.i2r, [], [e'], Ty.realTy), Ty.realTy)
490 : jhr 99 | _ => err(cxt, [S "argument of real conversion must be int"])
491 : jhr 86 (* end case *))
492 : jhr 1116 | PT.E_Id d => let
493 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
494 :     Util.instantiate(Var.typeOf(BV.identity))
495 :     in
496 : jhr 1687 if U.equalType(Ty.T_Tensor(checkShape(cxt, [d,d])), rngTy)
497 : jhr 1116 then (AST.E_Apply(BV.identity, tyArgs, [], rngTy), rngTy)
498 :     else raise Fail "impossible"
499 :     end
500 :     | PT.E_Zero dd => let
501 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
502 :     Util.instantiate(Var.typeOf(BV.zero))
503 :     in
504 : jhr 1687 if U.equalType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
505 : jhr 1116 then (AST.E_Apply(BV.zero, tyArgs, [], rngTy), rngTy)
506 :     else raise Fail "impossible"
507 :     end
508 : jhr 70 (* end case *))
509 :    
510 : jhr 81 (* typecheck a list of expressions returning a list of AST expressions and a list
511 :     * of types of the expressions.
512 :     *)
513 :     and checkExprList (env, cxt, exprs) = let
514 :     fun chk (e, (es, tys)) = let
515 :     val (e, ty) = checkExpr (env, cxt, e)
516 :     in
517 :     (e::es, ty::tys)
518 :     end
519 :     in
520 :     List.foldr chk ([], []) exprs
521 :     end
522 :    
523 : jhr 72 fun checkVarDecl (env, cxt, kind, d) = (case d
524 : jhr 86 of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
525 : jhr 72 | PT.VD_Decl(ty, x, e) => let
526 : jhr 81 val ty = checkTy (cxt, ty)
527 : jhr 72 val x' = Var.new (x, kind, ty)
528 :     val (e', ty') = checkExpr (env, cxt, e)
529 :     in
530 : jhr 1687 case coerceType (ty, ty', e')
531 : jhr 1971 of SOME e' => (x, x', e')
532 : jhr 1687 | NONE => err(cxt, [
533 : jhr 99 S "type of variable ", A x,
534 :     S " does not match type of initializer\n",
535 :     S " expected: ", TY ty, S "\n",
536 : jhr 1116 S " but found: ", TY ty'
537 : jhr 99 ])
538 : jhr 1687 (* end case *)
539 : jhr 72 end
540 :     (* end case *))
541 :    
542 : jhr 70 (* typecheck a statement and translate it to AST *)
543 : jhr 71 fun checkStmt (env, cxt, s) = (case s
544 : jhr 86 of PT.S_Mark m => checkStmt (withEnvAndContext (env, cxt, m))
545 : jhr 72 | PT.S_Block stms => let
546 :     fun chk (_, [], stms) = AST.S_Block(List.rev stms)
547 :     | chk (env, s::ss, stms) = let
548 :     val (s', env') = checkStmt (env, cxt, s)
549 :     in
550 : jhr 81 chk (env', ss, s'::stms)
551 : jhr 72 end
552 :     in
553 : jhr 1116 (chk (blockScope env, stms, []), env)
554 : jhr 72 end
555 :     | PT.S_Decl vd => let
556 : jhr 1116 val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
557 : jhr 72 in
558 : jhr 1116 checkForRedef (env, cxt, x);
559 :     (AST.S_Decl(AST.VD_Decl(x', e)), insertLocal(env, cxt, x, x'))
560 : jhr 72 end
561 :     | PT.S_IfThen(e, s) => let
562 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
563 : jhr 81 val (s', _) = checkStmt (env, cxt, s)
564 : jhr 72 in
565 :     (* check that condition has bool type *)
566 :     case ty
567 :     of Ty.T_Bool => ()
568 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
569 : jhr 72 (* end case *);
570 :     (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
571 :     end
572 :     | PT.S_IfThenElse(e, s1, s2) => let
573 : jhr 228 val (e', ty) = checkExpr (env, cxt, e)
574 : jhr 81 val (s1', _) = checkStmt (env, cxt, s1)
575 :     val (s2', _) = checkStmt (env, cxt, s2)
576 : jhr 72 in
577 :     (* check that condition has bool type *)
578 :     case ty
579 :     of Ty.T_Bool => ()
580 : jhr 99 | _ => err(cxt, [S "condition not boolean type"])
581 : jhr 72 (* end case *);
582 :     (AST.S_IfThenElse(e', s1', s2'), env)
583 :     end
584 : jhr 228 | PT.S_Assign(x, e) => (case Env.findVar (#env env, x)
585 : jhr 99 of NONE => err(cxt, [
586 :     S "undefined variable ", A x
587 :     ])
588 : jhr 72 | SOME x' => let
589 : jhr 99 (* FIXME: check for polymorphic variables *)
590 :     val ([], ty) = Var.typeOf x'
591 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
592 : jhr 1975 (* check for promotion *)
593 :     val e' = (case coerceType(ty, ty', e')
594 :     of SOME e' => e'
595 :     | NONE => err(cxt, [
596 :     S "type of assigned variable ", A x,
597 :     S " does not match type of rhs\n",
598 :     S " expected: ", TY ty, S "\n",
599 :     S " but found: ", TY ty'
600 :     ])
601 :     (* end case *))
602 : jhr 72 in
603 :     (* check that x' is mutable *)
604 :     case Var.kindOf x'
605 : jhr 511 of Var.StrandStateVar => ()
606 :     | Var.StrandOutputVar => ()
607 : jhr 72 | Var.LocalVar => ()
608 : jhr 99 | _ => err(cxt, [
609 :     S "assignment to immutable variable ", A x
610 :     ])
611 : jhr 72 (* end case *);
612 :     (AST.S_Assign(x', e'), env)
613 :     end
614 :     (* end case *))
615 : jhr 1296 | PT.S_OpAssign(x, rator, e) => (case Env.findVar (#env env, x)
616 :     of SOME x' => let
617 :     val e1' = AST.E_Var x'
618 :     val ty1 = Var.monoTypeOf x'
619 :     val (e2', ty2) = checkExpr(env, cxt, e)
620 :     val ovldList = Env.findFunc (#env env, rator)
621 :     val (rhs, _) = resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
622 :     in
623 :     (AST.S_Assign(x', rhs), env)
624 :     end
625 :     | NONE => err(cxt, [S "undeclared variable ", A x, S " on lhs of ", A rator])
626 :     (* end case *))
627 : jhr 511 | PT.S_New(strand, args) => let
628 : jhr 228 val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
629 : jhr 81 val (args', tys') = ListPair.unzip argsAndTys'
630 : jhr 72 in
631 : jhr 228 case #scope env
632 :     of MethodScope => ()
633 :     | InitScope => ()
634 : jhr 511 | _ => err(cxt, [S "invalid scope for new strand"])
635 : jhr 228 (* end case *);
636 : jhr 511 (* FIXME: check that strand is defined and has the argument types match *)
637 :     (AST.S_New(strand, args'), env)
638 : jhr 72 end
639 : jhr 228 | PT.S_Die => (
640 :     case #scope env
641 : jhr 235 of MethodScope => ()
642 :     | _ => err(cxt, [S "\"die\" statment outside of method"])
643 : jhr 228 (* end case *);
644 :     (AST.S_Die, env))
645 :     | PT.S_Stabilize => (
646 :     case #scope env
647 : jhr 235 of MethodScope => ()
648 :     | _ => err(cxt, [S "\"stabilize\" statment outside of method"])
649 : jhr 228 (* end case *);
650 :     (AST.S_Stabilize, env))
651 : jhr 1640 | PT.S_Print args => let
652 :     fun chkArg e = let
653 :     val (e', ty) = checkExpr (env, cxt, e)
654 :     in
655 :     if TU.isValueType ty
656 :     then ()
657 :     else err(cxt, [
658 :     S "expected value type in print, but found ", TY ty
659 :     ]);
660 :     e'
661 :     end
662 :     val args' = List.map chkArg args
663 :     in
664 :     (AST.S_Print args', env)
665 :     end
666 : jhr 70 (* end case *))
667 :    
668 : jhr 82 fun checkParams (env, cxt, params) = let
669 :     fun chkParam (env, cxt, param) = (case param
670 : jhr 86 of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
671 : jhr 82 | PT.P_Param(ty, x) => let
672 : jhr 511 val x' = Var.new(x, AST.StrandParam, checkTy (cxt, ty))
673 : jhr 82 in
674 : jhr 1116 checkForRedef (env, cxt, x);
675 :     (x', insertLocal(env, cxt, x, x'))
676 : jhr 82 end
677 :     (* end case *))
678 :     fun chk (param, (xs, env)) = let
679 :     val (x, env) = chkParam (env, cxt, param)
680 :     in
681 :     (x::xs, env)
682 :     end
683 :     in
684 :     (* FIXME: need to check for multiple occurences of the same parameter name! *)
685 :     List.foldr chk ([], env) params
686 :     end
687 :    
688 :     fun checkMethod (env, cxt, meth) = (case meth
689 : jhr 86 of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
690 : jhr 82 | PT.M_Method(name, body) => let
691 : jhr 228 val (body, _) = checkStmt(methodScope env, cxt, body)
692 : jhr 82 in
693 :     AST.M_Method(name, body)
694 :     end
695 :     (* end case *))
696 :    
697 : jhr 511 fun checkStrand (env, cxt, {name, params, state, methods}) = let
698 :     (* check the strand parameters *)
699 : jhr 82 val (params, env) = checkParams (env, cxt, params)
700 : jhr 511 (* check the strand state variable definitions *)
701 : jhr 82 val (vds, env) = let
702 : jhr 164 fun checkStateVar ((isOut, vd), (vds, env)) = let
703 : jhr 511 val kind = if isOut then AST.StrandOutputVar else AST.StrandStateVar
704 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, kind, vd)
705 : jhr 82 in
706 : jhr 228 (* check that output variables have value types *)
707 :     if isOut andalso not(TU.isValueType(Var.monoTypeOf x'))
708 :     then err(cxt, [
709 :     S "output variable ", V x', S " has non-value type ",
710 :     TY(Var.monoTypeOf x')
711 :     ])
712 :     else ();
713 : jhr 1116 checkForRedef (env, cxt, x);
714 :     (AST.VD_Decl(x', e')::vds, insertLocal(env, cxt, x, x'))
715 : jhr 82 end
716 :     val (vds, env) = List.foldl checkStateVar ([], env) state
717 :     in
718 :     (List.rev vds, env)
719 :     end
720 : jhr 511 (* check the strand methods *)
721 : jhr 82 val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
722 : jhr 1444 (* get the list of methods defined by the user *)
723 :     val methodNames = List.map (fn (AST.M_Method(name, _)) => name) methods
724 : jhr 1116 (* if the stabilize method is not provided, add one *)
725 : jhr 1640 val methods = if List.exists (fn StrandUtil.Stabilize => true | _ => false) methodNames
726 : jhr 1116 then methods
727 : jhr 1640 else methods @ [AST.M_Method(StrandUtil.Stabilize, AST.S_Block[])]
728 : jhr 82 in
729 : jhr 1444 (* FIXME: should check for duplicate method definitions *)
730 : jhr 1640 if not(List.exists (fn StrandUtil.Update => true | _ => false) methodNames)
731 : jhr 1116 then err(cxt, [S "strand ", A name, S " is missing an update method"])
732 :     else ();
733 : jhr 511 AST.D_Strand{name = name, params = params, state = vds, methods = methods}
734 : jhr 82 end
735 :    
736 : jhr 89 fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
737 : jhr 511 | checkCreate (env, cxt, PT.C_Create(strand, args)) = let
738 : jhr 228 val (args, tys) = checkExprList (env, cxt, args)
739 : jhr 89 in
740 : jhr 511 (* FIXME: check against strand definition *)
741 :     AST.C_Create(strand, args)
742 : jhr 89 end
743 :    
744 : jhr 1116 fun checkIters (env0, cxt, iters) = let
745 :     (* check an iteration range specification from the initially clause. We do the checking
746 :     * of the expressions using env0, which does not have any of the iteration variables in
747 :     * it (the iteration is rectangular), but we also accumulate the iteration bindings,
748 :     * which are used to create the final environment for checking the create call.
749 :     *)
750 :     fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
751 :     | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
752 :     val (e1', ty1) = checkExpr (env, cxt, e1)
753 :     val (e2', ty2) = checkExpr (env, cxt, e2)
754 :     val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
755 : jhr 89 in
756 : jhr 1116 case (ty1, ty2)
757 :     of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), (x, x'))
758 :     | _ => err(cxt, [
759 :     S "range expressions must have integer type\n",
760 :     S " but found: ", TY ty1, S " .. ", TY ty2
761 :     ])
762 :     (* end case *)
763 : jhr 89 end
764 : jhr 1116 fun chk ([], iters, bindings) =
765 :     (List.rev iters, List.foldl (fn ((x, x'), env) => insertLocal(env, cxt, x, x')) env0 bindings)
766 :     | chk (iter::rest, iters, bindings) = let
767 :     val (iter, binding) = checkIter (env0, cxt, iter)
768 :     in
769 :     chk (rest, iter::iters, binding::bindings)
770 :     end
771 : jhr 89 in
772 : jhr 1116 chk (iters, [], [])
773 : jhr 89 end
774 :    
775 : jhr 71 fun checkDecl (env, cxt, d) = (case d
776 : jhr 86 of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
777 : jhr 1301 | PT.D_Input(ty, x, desc, optExp) => let
778 :     (* FIXME: need to do something with the description *)
779 : jhr 71 val ty = checkTy(cxt, ty)
780 :     val x' = Var.new(x, Var.InputVar, ty)
781 :     val dcl = (case optExp
782 : jhr 1301 of NONE => AST.D_Input(x', desc, NONE)
783 : jhr 71 | SOME e => let
784 : jhr 228 val (e', ty') = checkExpr (env, cxt, e)
785 : jhr 71 in
786 : jhr 1971 case coerceType (ty, ty', e')
787 :     of SOME e' => AST.D_Input(x', desc, SOME e')
788 :     | NONE => err(cxt, [
789 :     S "definition of ", V x', S " has wrong type\n",
790 :     S " expected: ", TY ty, S "\n",
791 :     S " but found: ", TY ty'
792 :     ])
793 :     (* end case *)
794 : jhr 71 end
795 :     (* end case *))
796 :     in
797 : jhr 228 (* check that input variables have value types *)
798 :     if not(TU.isValueType ty)
799 :     then err(cxt, [S "input variable ", V x', S " has non-value type ", TY ty])
800 :     else ();
801 : jhr 1116 checkForRedef (env, cxt, x);
802 :     (dcl, insertGlobal(env, cxt, x, x'))
803 : jhr 71 end
804 : jhr 72 | PT.D_Var vd => let
805 : jhr 228 val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
806 : jhr 72 in
807 : jhr 1116 checkForRedef (env, cxt, x);
808 :     (AST.D_Var(AST.VD_Decl(x', e')), insertGlobal(env, cxt, x, x'))
809 : jhr 72 end
810 : jhr 511 | PT.D_Strand arg => (checkStrand(strandScope env, cxt, arg), env)
811 : jhr 89 | PT.D_InitialArray(create, iterators) => let
812 : jhr 228 val env = initScope env
813 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
814 :     val create = checkCreate (env', cxt, create)
815 :     in
816 :     (AST.D_InitialArray(create, iterators), env)
817 :     end
818 :     | PT.D_InitialCollection(create, iterators) => let
819 : jhr 228 val env = initScope env
820 : jhr 89 val (iterators, env') = checkIters (env, cxt, iterators)
821 :     val create = checkCreate (env', cxt, create)
822 :     in
823 :     (AST.D_InitialCollection(create, iterators), env)
824 :     end
825 : jhr 70 (* end case *))
826 :    
827 : jhr 1301 (* reorder the declarations so that the input variables come first *)
828 :     fun reorderDecls dcls = let
829 :     fun isInput (AST.D_Input _) = true
830 :     | isInput _ = false
831 :     val (inputs, others) = List.partition isInput dcls
832 :     in
833 :     inputs @ others
834 :     end
835 :    
836 : jhr 86 fun check errStrm (PT.Program{span, tree}) = let
837 :     val cxt = (errStrm, span)
838 : jhr 1301 fun chk (env, [], dcls') = AST.Program(reorderDecls(List.rev dcls'))
839 : jhr 81 | chk (env, dcl::dcls, dcls') = let
840 : jhr 86 val (dcl', env) = checkDecl (env, cxt, dcl)
841 : jhr 81 in
842 :     chk (env, dcls, dcl'::dcls')
843 :     end
844 :     in
845 : jhr 1116 chk ({scope=GlobalScope, bindings=AtomMap.empty, env=Basis.env}, tree, [])
846 : jhr 81 end
847 : jhr 70
848 : jhr 69 end

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