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

SCM Repository

[diderot] Annotation of /branches/vis15/src/compiler/typechecker/check-expr.sml
ViewVC logotype

Annotation of /branches/vis15/src/compiler/typechecker/check-expr.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3428 - (view) (download)

1 : jhr 3396 (* check-expr.sml
2 :     *
3 :     * The typechecker for expressions.
4 :     *
5 :     * This code is part of the Diderot Project (http://diderot-language.cs.uchicago.edu)
6 :     *
7 :     * COPYRIGHT (c) 2015 The University of Chicago
8 :     * All rights reserved.
9 :     *)
10 :    
11 :     structure CheckExpr : sig
12 :    
13 : jhr 3407 (* type check an expression *)
14 :     val check : Env.t * Env.context * ParseTree.expr -> (AST.expr * Types.ty)
15 : jhr 3396
16 : jhr 3410 (* type check a list of expressions *)
17 :     val checkList : Env.t * Env.context * ParseTree.expr list -> (AST.expr list * Types.ty list)
18 :    
19 : jhr 3424 (* type check an iteration expression (i.e., "x 'in' expr"), returning the iterator
20 :     * and the environment extended with a binding for x.
21 :     *)
22 :     val checkIter : Env.t * Env.context * ParseTree.iterator -> ((AST.var * AST.expr) * Env.t)
23 :    
24 : jhr 3410 (* type check a dimension that is given by a constant expression *)
25 :     val checkDim : Env.t * Env.context * ParseTree.expr -> IntLit.t option
26 :    
27 :     (* type check a tensor shape, where the dimensions are given by constant expressions *)
28 :     val checkShape : Env.t * Env.context * ParseTree.expr list -> Types.shape
29 :    
30 : jhr 3407 (* `resolveOverload (cxt, rator, tys, args, candidates)` resolves the application of
31 :     * the overloaded operator `rator` to `args`, where `tys` are the types of the arguments
32 :     * and `candidates` is the list of candidate definitions.
33 :     *)
34 :     val resolveOverload : Env.context * Atom.atom * Types.ty list * AST.expr list * Var.t list
35 :     -> (AST.expr * Types.ty)
36 :    
37 : jhr 3396 end = struct
38 :    
39 :     structure PT = ParseTree
40 :     structure L = Literal
41 :     structure E = Env
42 :     structure Ty = Types
43 :     structure BV = BasisVars
44 : jhr 3405 structure TU = TypeUtil
45 : jhr 3396
46 :     (* an expression to return when there is a type error *)
47 : jhr 3405 val bogusExp = AST.E_Lit(L.Int 0)
48 :     val bogusExpTy = (bogusExp, Ty.T_Error)
49 : jhr 3396
50 : jhr 3405 fun err arg = (TypeError.error arg; bogusExpTy)
51 : jhr 3396 val warn = TypeError.warning
52 :    
53 : jhr 3402 datatype token = datatype TypeError.token
54 : jhr 3396
55 : jhr 3407 (* mark a variable use with its location *)
56 : jhr 3413 fun useVar (cxt : Env.context, x) = (x, #2 cxt)
57 : jhr 3407
58 :     (* resolve overloading: we use a simple scheme that selects the first operator in the
59 :     * list that matches the argument types.
60 :     *)
61 :     fun resolveOverload (_, rator, _, _, []) = raise Fail(concat[
62 :     "resolveOverload: \"", Atom.toString rator, "\" has no candidates"
63 :     ])
64 :     | resolveOverload (cxt, rator, argTys, args, candidates) = let
65 :     (* FIXME: we could be more efficient by just checking for coercion matchs the first pass
66 :     * and remembering those that are not pure EQ matches.
67 :     *)
68 :     (* try to match candidates while allowing type coercions *)
69 :     fun tryMatchCandidates [] = err(cxt, [
70 :     S "unable to resolve overloaded operator ", A rator, S "\n",
71 :     S " argument type is: ", TYS argTys, S "\n"
72 :     ])
73 :     | tryMatchCandidates (x::xs) = let
74 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf x)
75 :     in
76 :     case Unify.tryMatchArgs (domTy, args, argTys)
77 :     of SOME args' => (AST.E_Prim(x, tyArgs, args', rngTy), rngTy)
78 :     | NONE => tryMatchCandidates xs
79 :     (* end case *)
80 :     end
81 :     fun tryCandidates [] = tryMatchCandidates candidates
82 :     | tryCandidates (x::xs) = let
83 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf x)
84 :     in
85 :     if Unify.tryEqualTypes(domTy, argTys)
86 :     then (AST.E_Prim(x, tyArgs, args, rngTy), rngTy)
87 :     else tryCandidates xs
88 :     end
89 :     in
90 :     tryCandidates candidates
91 :     end
92 :    
93 : jhr 3396 (* check the type of a literal *)
94 :     fun checkLit lit = (case lit
95 :     of (L.Int _) => (AST.E_Lit lit, Ty.T_Int)
96 :     | (L.Real _) => (AST.E_Lit lit, Ty.realTy)
97 :     | (L.String s) => (AST.E_Lit lit, Ty.T_String)
98 :     | (L.Bool _) => (AST.E_Lit lit, Ty.T_Bool)
99 :     (* end case *))
100 :    
101 : jhr 3405 (* type check a dot product, which has the constraint:
102 :     * ALL[sigma1, d1, sigma2] . tensor[sigma1, d1] * tensor[d1, sigma2] -> tensor[sigma1, sigma2]
103 :     * and similarly for fields.
104 :     *)
105 :     fun chkInnerProduct (cxt, e1, ty1, e2, ty2) = let
106 :     (* check the shape of the two arguments to verify that the inner constraint matches *)
107 :     fun chkShape (Ty.Shape(dd1 as _::_), Ty.Shape(d2::dd2)) = let
108 :     val (dd1, d1) = let
109 :     fun splitLast (prefix, [d]) = (List.rev prefix, d)
110 :     | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
111 :     | splitLast (_, []) = raise Fail "impossible"
112 :     in
113 :     splitLast ([], dd1)
114 :     end
115 :     in
116 :     if Unify.equalDim(d1, d2)
117 :     then SOME(Ty.Shape(dd1@dd2))
118 :     else NONE
119 :     end
120 :     | chkShape _ = NONE
121 :     fun error () = err (cxt, [
122 :     S "type error for arguments of binary operator '•'\n",
123 :     S " found: ", TYS[ty1, ty2], S "\n"
124 :     ])
125 :     in
126 :     case (TU.prune ty1, TU.prune ty2)
127 :     (* tensor * tensor inner product *)
128 :     of (Ty.T_Tensor s1, Ty.T_Tensor s2) => (case chkShape(s1, s2)
129 :     of SOME shp => let
130 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_inner_tt)
131 :     val resTy = Ty.T_Tensor shp
132 :     in
133 :     if Unify.equalTypes(domTy, [ty1, ty2]) andalso Unify.equalType(rngTy, resTy)
134 : jhr 3407 then (AST.E_Prim(BV.op_inner_tt, tyArgs, [e1, e2], rngTy), rngTy)
135 : jhr 3405 else error()
136 :     end
137 :     | NONE => error()
138 :     (* end case *))
139 :     (* tensor * field inner product *)
140 :     | (Ty.T_Tensor s1, Ty.T_Field{diff, dim, shape=s2}) => (case chkShape(s1, s2)
141 :     of SOME shp => let
142 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_inner_tf)
143 :     val resTy = Ty.T_Field{diff=diff, dim=dim, shape=shp}
144 :     in
145 :     if Unify.equalTypes(domTy, [ty1, ty2])
146 :     andalso Unify.equalType(rngTy, resTy)
147 : jhr 3407 then (AST.E_Prim(BV.op_inner_tf, tyArgs, [e1, e2], rngTy), rngTy)
148 : jhr 3405 else error()
149 :     end
150 :     | NONE => error()
151 :     (* end case *))
152 :     (* field * tensor inner product *)
153 :     | (Ty.T_Field{diff, dim, shape=s1}, Ty.T_Tensor s2) => (case chkShape(s1, s2)
154 :     of SOME shp => let
155 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_inner_ft)
156 :     val resTy = Ty.T_Field{diff=diff, dim=dim, shape=shp}
157 :     in
158 :     if Unify.equalTypes(domTy, [ty1, ty2])
159 :     andalso Unify.equalType(rngTy, resTy)
160 : jhr 3407 then (AST.E_Prim(BV.op_inner_ft, tyArgs, [e1, e2], rngTy), rngTy)
161 : jhr 3405 else error()
162 :     end
163 :     | NONE => error()
164 :     (* end case *))
165 :     (* field * field inner product *)
166 :     | (Ty.T_Field{diff=k1, dim=dim1, shape=s1}, Ty.T_Field{diff=k2, dim=dim2, shape=s2}) => (
167 :     case chkShape(s1, s2)
168 :     of SOME shp => let
169 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_inner_ff)
170 :     val resTy = Ty.T_Field{diff=k1, dim=dim1, shape=shp}
171 :     in
172 :     (* FIXME: the resulting differentiation should be the minimum of k1 and k2 *)
173 :     if Unify.equalDim(dim1, dim2)
174 :     andalso Unify.equalTypes(domTy, [ty1, ty2])
175 :     andalso Unify.equalType(rngTy, resTy)
176 : jhr 3407 then (AST.E_Prim(BV.op_inner_ff, tyArgs, [e1, e2], rngTy), rngTy)
177 : jhr 3405 else error()
178 :     end
179 :     | NONE => error()
180 :     (* end case *))
181 :     | (ty1, ty2) => error()
182 :     (* end case *)
183 :     end
184 :    
185 :     (* type check a colon product, which has the constraint:
186 :     * ALL[sigma1, d1, d2, sigma2] . tensor[sigma1, d1, d2] * tensor[d2, d1, sigma2] -> tensor[sigma1, sigma2]
187 :     * and similarly for fields.
188 :     *)
189 :     fun chkColonProduct (cxt, e1, ty1, e2, ty2) = let
190 :     (* check the shape of the two arguments to verify that the inner constraint matches *)
191 :     fun chkShape (Ty.Shape(dd1 as _::_::_), Ty.Shape(d21::d22::dd2)) = let
192 :     val (dd1, d11, d12) = let
193 :     fun splitLast2 (prefix, [d1, d2]) = (List.rev prefix, d1, d2)
194 :     | splitLast2 (prefix, d::dd) = splitLast2 (d::prefix, dd)
195 :     | splitLast2 (_, []) = raise Fail "impossible"
196 :     in
197 :     splitLast2 ([], dd1)
198 :     end
199 :     in
200 :     if Unify.equalDim(d11, d21) andalso Unify.equalDim(d12, d22)
201 :     then SOME(Ty.Shape(dd1@dd2))
202 :     else NONE
203 :     end
204 :     | chkShape _ = NONE
205 :     fun error () = err (cxt, [
206 :     S "type error for arguments of binary operator \":\"\n",
207 :     S " found: ", TYS[ty1, ty2], S "\n"
208 :     ])
209 :     in
210 :     case (TU.prune ty1, TU.prune ty2)
211 :     (* tensor * tensor colon product *)
212 :     of (Ty.T_Tensor s1, Ty.T_Tensor s2) => (case chkShape(s1, s2)
213 :     of SOME shp => let
214 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_colon_tt)
215 :     val resTy = Ty.T_Tensor shp
216 :     in
217 :     if Unify.equalTypes(domTy, [ty1, ty2])
218 :     andalso Unify.equalType(rngTy, resTy)
219 : jhr 3407 then (AST.E_Prim(BV.op_colon_tt, tyArgs, [e1, e2], rngTy), rngTy)
220 : jhr 3405 else error()
221 :     end
222 :     | NONE => error()
223 :     (* end case *))
224 :     (* field * tensor colon product *)
225 :     | (Ty.T_Field{diff, dim, shape=s1}, Ty.T_Tensor s2) => (case chkShape(s1, s2)
226 :     of SOME shp => let
227 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_colon_ft)
228 :     val resTy = Ty.T_Field{diff=diff, dim=dim, shape=shp}
229 :     in
230 :     if Unify.equalTypes(domTy, [ty1, ty2]) andalso Unify.equalType(rngTy, resTy)
231 : jhr 3407 then (AST.E_Prim(BV.op_colon_ft, tyArgs, [e1, e2], rngTy), rngTy)
232 : jhr 3405 else error()
233 :     end
234 :     | NONE => error()
235 :     (* end case *))
236 :     (* tensor * field colon product *)
237 :     | (Ty.T_Tensor s1, Ty.T_Field{diff=diff, dim=dim, shape=s2}) => (case chkShape(s1, s2)
238 :     of SOME shp => let
239 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_colon_tf)
240 :     val resTy = Ty.T_Field{diff=diff, dim=dim, shape=shp}
241 :     in
242 :     if Unify.equalTypes(domTy, [ty1, ty2]) andalso Unify.equalType(rngTy, resTy)
243 : jhr 3407 then (AST.E_Prim(BV.op_colon_tf, tyArgs, [e1, e2], rngTy), rngTy)
244 : jhr 3405 else error()
245 :     end
246 :     | NONE => error()
247 :     (* end case *))
248 :     (* field * field colon product *)
249 :     | (Ty.T_Field{diff=k1, dim=dim1, shape=s1}, Ty.T_Field{diff=k2, dim=dim2, shape=s2}) => (
250 :     case chkShape(s1, s2)
251 :     of SOME shp => let
252 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf BV.op_colon_ff)
253 :     val resTy = Ty.T_Field{diff=k1, dim=dim1, shape=shp}
254 :     in
255 :     (* FIXME: the resulting differentiation should be the minimum of k1 and k2 *)
256 :     if Unify.equalDim(dim1, dim2)
257 :     andalso Unify.equalTypes(domTy, [ty1, ty2])
258 :     andalso Unify.equalType(rngTy, resTy)
259 : jhr 3407 then (AST.E_Prim(BV.op_colon_ff, tyArgs, [e1, e2], rngTy), rngTy)
260 : jhr 3405 else error()
261 :     end
262 :     | NONE => error()
263 :     (* end case *))
264 :     | (ty1, ty2) => error()
265 :     (* end case *)
266 :     end
267 :    
268 : jhr 3396 (* check the type of an expression *)
269 :     fun check (env, cxt, e) = (case e
270 : jhr 3405 of PT.E_Mark m => check (E.withEnvAndContext (env, cxt, m))
271 : jhr 3396 | PT.E_Cond(e1, cond, e2) => let
272 :     val eTy1 = check (env, cxt, e1)
273 :     val eTy2 = check (env, cxt, e2)
274 :     in
275 : jhr 3402 case check(env, cxt, cond)
276 : jhr 3396 of (cond', Ty.T_Bool) => (case Util.coerceType2(eTy1, eTy2)
277 : jhr 3405 of SOME(e1', e2', ty) => (AST.E_Cond(cond', e1', e2', ty), ty)
278 : jhr 3396 | NONE => err (cxt, [
279 :     S "types do not match in conditional expression\n",
280 :     S " true branch: ", TY(#2 eTy1), S "\n",
281 :     S " false branch: ", TY(#2 eTy2)
282 :     ])
283 : jhr 3398 (* end case *))
284 : jhr 3396 | (_, ty') => err (cxt, [S "expected bool type, but found ", TY ty'])
285 :     (* end case *)
286 :     end
287 :     | PT.E_Range(e1, e2) => (case (check (env, cxt, e1), check (env, cxt, e2))
288 :     of ((e1', Ty.T_Int), (e2', Ty.T_Int)) => let
289 : jhr 3398 val resTy = Ty.T_Sequence(Ty.T_Int, NONE)
290 : jhr 3396 in
291 : jhr 3407 (AST.E_Prim(BV.range, [], [e1', e2'], resTy), resTy)
292 : jhr 3396 end
293 :     | ((_, Ty.T_Int), (_, ty2)) =>
294 :     err (cxt, [S "expected type 'int' on rhs of '..', but found ", TY ty2])
295 :     | ((_, ty1), (_, Ty.T_Int)) =>
296 :     err (cxt, [S "expected type 'int' on lhs of '..', but found ", TY ty1])
297 :     | ((_, ty1), (_, ty2)) => err (cxt, [
298 :     S "arguments of '..' must have type 'int', found ",
299 :     TY ty1, S " and ", TY ty2
300 :     ])
301 :     (* end case *))
302 :     | PT.E_OrElse(e1, e2) =>
303 :     checkCondOp (env, cxt, e1, "||", e2,
304 :     fn (e1', e2') => AST.E_Cond(e1', AST.E_Lit(L.Bool true), e2', Ty.T_Bool))
305 :     | PT.E_AndAlso(e1, e2) =>
306 :     checkCondOp (env, cxt, e1, "&&", e2,
307 :     fn (e1', e2') => AST.E_Cond(e1', e2', AST.E_Lit(L.Bool false), Ty.T_Bool))
308 :     | PT.E_BinOp(e1, rator, e2) => let
309 :     val (e1', ty1) = check (env, cxt, e1)
310 :     val (e2', ty2) = check (env, cxt, e2)
311 :     in
312 :     if Atom.same(rator, BasisNames.op_dot)
313 : jhr 3405 then chkInnerProduct (cxt, e1', ty1, e2', ty2)
314 : jhr 3396 else if Atom.same(rator, BasisNames.op_colon)
315 : jhr 3405 then chkColonProduct (cxt, e1', ty1, e2', ty2)
316 :     else (case Env.findFunc (env, rator)
317 : jhr 3396 of Env.PrimFun[rator] => let
318 : jhr 3405 val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf rator)
319 : jhr 3396 in
320 : jhr 3402 case Unify.matchArgs(domTy, [e1', e2'], [ty1, ty2])
321 : jhr 3407 of SOME args => (AST.E_Prim(rator, tyArgs, args, rngTy), rngTy)
322 : jhr 3396 | NONE => err (cxt, [
323 : jhr 3418 S "type error for binary operator ", V rator, S "\n",
324 : jhr 3396 S " expected: ", TYS domTy, S "\n",
325 :     S " but found: ", TYS[ty1, ty2]
326 :     ])
327 :     (* end case *)
328 :     end
329 :     | Env.PrimFun ovldList =>
330 :     resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
331 :     | _ => raise Fail "impossible"
332 :     (* end case *))
333 :     end
334 : jhr 3398 | PT.E_UnaryOp(rator, e) => let
335 : jhr 3405 val eTy = check(env, cxt, e)
336 : jhr 3398 in
337 : jhr 3405 case Env.findFunc (env, rator)
338 : jhr 3398 of Env.PrimFun[rator] => let
339 : jhr 3405 val (tyArgs, Ty.T_Fun([domTy], rngTy)) = TU.instantiate(Var.typeOf rator)
340 : jhr 3398 in
341 : jhr 3405 case Util.coerceType (domTy, eTy)
342 : jhr 3410 of SOME e' => (AST.E_Prim(rator, tyArgs, [e'], rngTy), rngTy)
343 : jhr 3398 | NONE => err (cxt, [
344 : jhr 3418 S "type error for unary operator ", V rator, S "\n",
345 : jhr 3398 S " expected: ", TY domTy, S "\n",
346 : jhr 3405 S " but found: ", TY (#2 eTy)
347 : jhr 3398 ])
348 :     (* end case *)
349 :     end
350 : jhr 3405 | Env.PrimFun ovldList => resolveOverload (cxt, rator, [#2 eTy], [#1 eTy], ovldList)
351 : jhr 3398 | _ => raise Fail "impossible"
352 :     (* end case *)
353 :     end
354 : jhr 3407 | PT.E_Apply(e, args) => let
355 :     fun stripMark (_, PT.E_Mark{span, tree}) = stripMark(span, tree)
356 :     | stripMark (span, e) = (span, e)
357 :     val (args, tys) = checkList (env, cxt, args)
358 :     fun appTyError (f, paramTys, argTys) = err(cxt, [
359 :     S "type error in application of ", V f, S "\n",
360 :     S " expected: ", TYS paramTys, S "\n",
361 :     S " but found: ", TYS argTys
362 :     ])
363 :     fun checkPrimApp f = if Var.isPrim f
364 :     then (case TU.instantiate(Var.typeOf f)
365 :     of (tyArgs, Ty.T_Fun(domTy, rngTy)) => (
366 :     case Unify.matchArgs (domTy, args, tys)
367 :     of SOME args => (AST.E_Prim(f, tyArgs, args, rngTy), rngTy)
368 :     | NONE => appTyError (f, domTy, tys)
369 :     (* end case *))
370 :     | _ => err(cxt, [S "application of non-function/field ", V f])
371 :     (* end case *))
372 :     else raise Fail "unexpected user function"
373 :     (* check the application of a user-defined function *)
374 :     fun checkFunApp (cxt, f) = if Var.isPrim f
375 :     then raise Fail "unexpected primitive function"
376 :     else (case Var.monoTypeOf f
377 :     of Ty.T_Fun(domTy, rngTy) => (
378 :     case Unify.matchArgs (domTy, args, tys)
379 :     of SOME args => (AST.E_Apply(useVar(cxt, f), args, rngTy), rngTy)
380 :     | NONE => appTyError (f, domTy, tys)
381 :     (* end case *))
382 :     | _ => err(cxt, [S "application of non-function/field ", V f])
383 :     (* end case *))
384 :     fun checkFieldApp (e1', ty1) = (case (args, tys)
385 :     of ([e2'], [ty2]) => let
386 :     val (tyArgs, Ty.T_Fun([fldTy, domTy], rngTy)) =
387 :     TU.instantiate(Var.typeOf BV.op_probe)
388 :     fun tyError () = err (cxt, [
389 :     S "type error for field application\n",
390 :     S " expected: ", TYS[fldTy, domTy], S "\n",
391 :     S " but found: ", TYS[ty1, ty2]
392 :     ])
393 :     in
394 :     if Unify.equalType(fldTy, ty1)
395 :     then (case Util.coerceType(domTy, (e2', ty2))
396 : jhr 3410 of SOME e2' => (AST.E_Prim(BV.op_probe, tyArgs, [e1', e2'], rngTy), rngTy)
397 : jhr 3407 | NONE => tyError()
398 :     (* end case *))
399 :     else tyError()
400 :     end
401 :     | _ => err(cxt, [S "badly formed field application"])
402 :     (* end case *))
403 :     in
404 :     case stripMark(#2 cxt, e)
405 :     of (span, PT.E_Var f) => (case Env.findVar (env, f)
406 :     of SOME f' => checkFieldApp (
407 :     AST.E_Var(useVar((#1 cxt, span), f')),
408 :     Var.monoTypeOf f')
409 :     | NONE => (case Env.findFunc (env, f)
410 :     of Env.PrimFun[] => err(cxt, [S "unknown function ", A f])
411 :     | Env.PrimFun[f'] => checkPrimApp f'
412 :     | Env.PrimFun ovldList =>
413 :     resolveOverload ((#1 cxt, span), f, tys, args, ovldList)
414 :     | Env.UserFun f' => checkFunApp((#1 cxt, span), f')
415 :     (* end case *))
416 :     (* end case *))
417 :     | _ => checkFieldApp (check (env, cxt, e))
418 :     (* end case *)
419 :     end
420 : jhr 3424 | PT.E_Subscript(e, indices) => let
421 :     fun expectedTensor ty = err(cxt, [
422 :     S "expected tensor type for slicing, but found ", TY ty
423 : jhr 3398 ])
424 : jhr 3424 fun chkIndex e = let
425 :     val eTy as (_, ty) = check(env, cxt, e)
426 :     in
427 :     if Unify.equalType(ty, Ty.T_Int)
428 :     then eTy
429 :     else err (cxt, [
430 :     S "expected type 'int' for index, but found ", TY ty
431 :     ])
432 :     end
433 :     in
434 :     case (check(env, cxt, e), indices)
435 :     of ((e', Ty.T_Error), _) => (
436 :     List.app (ignore o Option.map chkIndex) indices;
437 :     bogusExpTy)
438 :     | ((e1', ty1 as Ty.T_Sequence(elemTy, optDim)), [SOME e2]) => let
439 :     val (e2', ty2) = chkIndex e2
440 :     val rator = if isSome optDim
441 :     then BV.subscript
442 :     else BV.dynSubscript
443 :     val (tyArgs, Ty.T_Fun(domTy, rngTy)) = TU.instantiate(Var.typeOf rator)
444 :     in
445 :     if Unify.equalTypes(domTy, [ty1, ty2])
446 :     then let
447 :     val exp = AST.E_Prim(rator, tyArgs, [e1', e2'], rngTy)
448 :     in
449 :     (exp, rngTy)
450 :     end
451 :     else raise Fail "unexpected unification failure"
452 :     end
453 :     | ((e', ty as Ty.T_Sequence _), [NONE]) => expectedTensor ty
454 :     | ((e', ty as Ty.T_Sequence _), _) => expectedTensor ty
455 : jhr 3427 | ((e', ty as Ty.T_Tensor shape), _) => let
456 :     val indices' = List.map (Option.map (#1 o chkIndex)) indices
457 :     val order = List.length indices'
458 :     val expectedTy = TU.mkTensorTy order
459 :     val resultTy = TU.slice(expectedTy, List.map Option.isSome indices')
460 :     in
461 :     if Unify.equalType(ty, expectedTy)
462 :     then (AST.E_Slice(e', indices', resultTy), resultTy)
463 :     else err (cxt, [
464 :     S "type error in slice operation\n",
465 :     S " expected: ", S(Int.toString order), S "-order tensor\n",
466 :     S " but found: ", TY ty
467 :     ])
468 :     end
469 : jhr 3424 | ((_, ty), _) => expectedTensor ty
470 :     (* end case *)
471 :     end
472 : jhr 3398 | PT.E_Select(e, field) => (case check(env, cxt, e)
473 : jhr 3405 of (e', Ty.T_Named strand) => (case Env.findStrand(env, strand)
474 :     of SOME sEnv => (case StrandEnv.findStateVar(sEnv, field)
475 :     of SOME x' => let
476 :     val ty = Var.monoTypeOf x'
477 :     in
478 : jhr 3407 (AST.E_Select(e', useVar(cxt, x')), ty)
479 : jhr 3405 end
480 :     | NONE => err(cxt, [
481 : jhr 3418 S "strand ", A strand,
482 :     S " does not have state variable ", A field
483 : jhr 3405 ])
484 :     (* end case *))
485 : jhr 3418 | NONE => err(cxt, [S "unknown strand ", A strand])
486 : jhr 3398 (* end case *))
487 : jhr 3428 | (e', Ty.T_Error) => bogusExpTy
488 : jhr 3398 | (_, ty) => err (cxt, [
489 :     S "expected strand type, but found ", TY ty,
490 : jhr 3418 S " in selection of ", A field
491 : jhr 3398 ])
492 :     (* end case *))
493 : jhr 3396 | PT.E_Real e => (case check (env, cxt, e)
494 :     of (e', Ty.T_Int) =>
495 : jhr 3407 (AST.E_Prim(BV.i2r, [], [e'], Ty.realTy), Ty.realTy)
496 : jhr 3428 | (e', Ty.T_Error) => bogusExpTy
497 : jhr 3396 | (_, ty) => err(cxt, [
498 :     S "argument of 'real' must have type 'int', but found ",
499 :     TY ty
500 :     ])
501 :     (* end case *))
502 :     | PT.E_Load nrrd => let
503 : jhr 3418 val (tyArgs, Ty.T_Fun(_, rngTy)) = TU.instantiate(Var.typeOf(BV.fn_load))
504 : jhr 3396 in
505 : jhr 3407 case chkStringConstExpr (env, cxt, nrrd)
506 :     of SOME nrrd => (AST.E_LoadNrrd(tyArgs, nrrd, rngTy), rngTy)
507 :     | NONE => (bogusExp, rngTy)
508 :     (* end case *)
509 : jhr 3396 end
510 :     | PT.E_Image nrrd => let
511 : jhr 3418 val (tyArgs, Ty.T_Fun(_, rngTy)) = TU.instantiate(Var.typeOf(BV.fn_image))
512 : jhr 3396 in
513 : jhr 3407 case chkStringConstExpr (env, cxt, nrrd)
514 :     of SOME nrrd => (AST.E_LoadNrrd(tyArgs, nrrd, rngTy), rngTy)
515 :     | NONE => (bogusExp, rngTy)
516 :     (* end case *)
517 : jhr 3396 end
518 : jhr 3405 | PT.E_Var x => (case E.findVar (env, x)
519 : jhr 3407 of SOME x' => (AST.E_Var(useVar(cxt, x')), Var.monoTypeOf x')
520 : jhr 3396 | NONE => err(cxt, [S "undeclared variable ", A x])
521 :     (* end case *))
522 : jhr 3421 | PT.E_Kernel(kern, dim) => (case E.findVar (env, kern)
523 :     of SOME kern' => (case Var.monoTypeOf kern'
524 :     of ty as Ty.T_Kernel(Ty.DiffConst k) => let
525 :     val k' = Int.fromLarge dim handle Overflow => 1073741823
526 :     val e = AST.E_Var(useVar(cxt, kern'))
527 :     in
528 :     if (k = k')
529 :     then (e, ty)
530 :     else let
531 :     val ty' = Ty.T_Kernel(Ty.DiffConst k')
532 :     in
533 :     (AST.E_Coerce{srcTy = ty, dstTy = ty', e = e}, ty')
534 :     end
535 :     end
536 :     | _ => err(cxt, [S "expected kernel, but found ", S(Var.kindToString kern')])
537 :     (* end case *))
538 :     | NONE => err(cxt, [S "unknown kernel ", A kern])
539 :     (* end case *))
540 : jhr 3396 | PT.E_Lit lit => checkLit lit
541 :     | PT.E_Id d => let
542 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
543 : jhr 3405 TU.instantiate(Var.typeOf(BV.identity))
544 : jhr 3396 in
545 : jhr 3407 if Unify.equalType(Ty.T_Tensor(checkShape(env, cxt, [d, d])), rngTy)
546 :     then (AST.E_Prim(BV.identity, tyArgs, [], rngTy), rngTy)
547 : jhr 3396 else raise Fail "impossible"
548 :     end
549 :     | PT.E_Zero dd => let
550 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
551 : jhr 3405 TU.instantiate(Var.typeOf(BV.zero))
552 : jhr 3396 in
553 : jhr 3407 if Unify.equalType(Ty.T_Tensor(checkShape(env, cxt, dd)), rngTy)
554 :     then (AST.E_Prim(BV.zero, tyArgs, [], rngTy), rngTy)
555 : jhr 3396 else raise Fail "impossible"
556 :     end
557 :     | PT.E_NaN dd => let
558 :     val (tyArgs, Ty.T_Fun(_, rngTy)) =
559 : jhr 3405 TU.instantiate(Var.typeOf(BV.nan))
560 : jhr 3396 in
561 : jhr 3407 if Unify.equalType(Ty.T_Tensor(checkShape(env, cxt, dd)), rngTy)
562 :     then (AST.E_Prim(BV.nan, tyArgs, [], rngTy), rngTy)
563 : jhr 3396 else raise Fail "impossible"
564 :     end
565 : jhr 3422 | PT.E_Sequence exps => (case checkList (env, cxt, exps)
566 :     (* FIXME: need kind for concrete types here! *)
567 :     of ([], _) => let
568 :     val ty = Ty.T_Sequence(Ty.T_Var(MetaVar.newTyVar()), SOME(Ty.DimConst 0))
569 :     in
570 :     (AST.E_Seq([], ty), ty)
571 :     end
572 :     | (args, tys) => (case Util.coerceTypes(List.map TU.pruneHead tys)
573 :     of SOME ty => if TU.isValueType ty
574 :     then let
575 :     fun doExp eTy = valOf(Util.coerceType (ty, eTy))
576 :     val resTy = Ty.T_Sequence(ty, SOME(Ty.DimConst(List.length args)))
577 :     val args = ListPair.map doExp (args, tys)
578 :     in
579 :     (AST.E_Seq(args, resTy), resTy)
580 :     end
581 :     else err(cxt, [S "sequence expression of non-value argument type"])
582 :     | NONE => err(cxt, [S "arguments of sequence expression must have same type"])
583 :     (* end case *))
584 :     (* end case *))
585 : jhr 3428 | PT.E_SeqComp comp => chkComprehension (env, cxt, comp)
586 : jhr 3396 | PT.E_Cons args => let
587 :     (* Note that we are guaranteed that args is non-empty *)
588 :     val (args, tys) = checkList (env, cxt, args)
589 :     (* extract the first non-error type in tys *)
590 :     val ty = (case List.find (fn Ty.T_Error => false | _ => true) tys
591 :     of NONE => Ty.T_Error
592 :     | SOME ty => ty
593 :     (* end case *))
594 : jhr 3405 (* process the arguments checking that they all have the expected type *)
595 :     fun chkArgs (ty, shape) = let
596 :     val Ty.Shape dd = TU.pruneShape shape (* NOTE: this may fail if we allow user polymorphism *)
597 :     val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
598 :     fun chkArgs (arg::args, argTy::tys, args') = (
599 :     case Util.coerceType(ty, (arg, argTy))
600 : jhr 3410 of SOME arg' => chkArgs (args, tys, arg'::args')
601 : jhr 3405 | NONE => (
602 :     TypeError.error(cxt, [
603 :     S "arguments of tensor construction must have same type"
604 :     ]);
605 :     chkArgs (args, tys, bogusExp::args'))
606 :     (* end case *))
607 : jhr 3408 | chkArgs (_, _, args') = (AST.E_Tensor(List.rev args', resTy), resTy)
608 : jhr 3405 in
609 :     chkArgs (args, tys, [])
610 :     end
611 : jhr 3396 in
612 : jhr 3405 case TU.pruneHead ty
613 : jhr 3407 of Ty.T_Int => chkArgs(Ty.realTy, Ty.Shape[]) (* coerce integers to reals *)
614 : jhr 3405 | ty as Ty.T_Tensor shape => chkArgs(ty, shape)
615 : jhr 3396 | _ => err(cxt, [S "Invalid argument type for tensor construction"])
616 :     (* end case *)
617 :     end
618 :     | PT.E_Deprecate(msg, e) => (
619 :     warn (cxt, [S msg]);
620 : jhr 3402 check (env, cxt, e))
621 : jhr 3396 (* end case *))
622 :    
623 :     (* check a conditional operator (e.g., || or &&) *)
624 :     and checkCondOp (env, cxt, e1, rator, e2, mk) = (
625 :     case (check(env, cxt, e1), check(env, cxt, e2))
626 :     of ((e1', Ty.T_Bool), (e2', Ty.T_Bool)) => (mk(e1', e2'), Ty.T_Bool)
627 :     | ((_, Ty.T_Bool), (_, ty2)) =>
628 : jhr 3405 err (cxt, [S "expected type 'bool' on rhs of '", S rator, S "', but found ", TY ty2])
629 : jhr 3396 | ((_, ty1), (_, Ty.T_Bool)) =>
630 : jhr 3405 err (cxt, [S "expected type 'bool' on lhs of '", S rator, S "', but found ", TY ty1])
631 : jhr 3396 | ((_, ty1), (_, ty2)) => err (cxt, [
632 : jhr 3405 S "arguments of '", S rator, S "' must have type 'bool', but found ",
633 : jhr 3396 TY ty1, S " and ", TY ty2
634 :     ])
635 :     (* end case *))
636 :    
637 : jhr 3424 and chkComprehension (env, cxt, PT.COMP_Mark m) =
638 :     chkComprehension(E.withEnvAndContext(env, cxt, m))
639 :     | chkComprehension (env, cxt, PT.COMP_Comprehension(e, [iter])) = let
640 :     val (iter', env') = checkIter (E.blockScope env, cxt, iter)
641 :     val (e', ty) = check (env', cxt, e)
642 :     val resTy = Ty.T_Sequence(ty, NONE)
643 :     in
644 :     (AST.E_Comprehension(e', iter', resTy), resTy)
645 :     end
646 :     | chkComprehension _ = raise Fail "impossible"
647 :    
648 :     and checkIter (env, cxt, PT.I_Mark m) = checkIter (E.withEnvAndContext (env, cxt, m))
649 :     | checkIter (env, cxt, PT.I_Iterator({span, tree=x}, e)) = (
650 :     case check (env, cxt, e)
651 :     of (e', ty as Ty.T_Sequence(elemTy, _)) => let
652 :     val x' = Var.new(x, Error.location(#1 cxt, span), Var.LocalVar, elemTy)
653 :     in
654 :     ((x', e'), E.insertLocal(env, cxt, x, x'))
655 :     end
656 :     | (e', ty) => let
657 :     val x' = Var.new(x, Error.UNKNOWN, Var.IterVar, Ty.T_Error)
658 :     in
659 :     TypeError.error (cxt, [
660 :     S "expected sequence type in iteration, but found '", TY ty, S "'"
661 :     ]);
662 :     ((x', bogusExp), E.insertLocal(env, cxt, x, x'))
663 :     end
664 :     (* end case *))
665 :    
666 : jhr 3396 (* typecheck a list of expressions returning a list of AST expressions and a list
667 :     * of the types of the expressions.
668 :     *)
669 :     and checkList (env, cxt, exprs) = let
670 :     fun chk (e, (es, tys)) = let
671 : jhr 3402 val (e, ty) = check (env, cxt, e)
672 : jhr 3396 in
673 :     (e::es, ty::tys)
674 :     end
675 :     in
676 :     List.foldr chk ([], []) exprs
677 :     end
678 :    
679 : jhr 3407 (* check a string that is specified as a constant expression *)
680 :     and chkStringConstExpr (env, cxt, PT.E_Mark m) =
681 :     chkStringConstExpr (E.withEnvAndContext (env, cxt, m))
682 :     | chkStringConstExpr (env, cxt, e) = (case check (env, cxt, e)
683 :     of (e', Ty.T_String) => (case ConstExpr.eval (cxt, e')
684 :     of SOME(ConstExpr.String s) => SOME s
685 :     | SOME(ConstExpr.Expr e) => raise Fail "FIXME"
686 :     | NONE => NONE
687 :     | _ => raise Fail "impossible: wrong type for constant expr"
688 :     (* end case *))
689 :     | (_, ty) => (
690 :     TypeError.error (cxt, [
691 :     S "expected constant expression of type 'string', but found '",
692 :     TY ty, S "'"
693 :     ]);
694 :     NONE)
695 :     (* end case *))
696 :    
697 :     (* check a dimension that is given by a constant expression *)
698 :     and checkDim (env, cxt, dim) = (case check (env, cxt, dim)
699 :     of (e', Ty.T_Int) => (case ConstExpr.eval (cxt, e')
700 :     of SOME(ConstExpr.Int d) => SOME d
701 :     | SOME(ConstExpr.Expr e) => (
702 :     TypeError.error (cxt, [S "unable to evaluate constant dimension expression"]);
703 :     NONE)
704 :     | NONE => NONE
705 :     | _ => raise Fail "impossible: wrong type for constant expr"
706 :     (* end case *))
707 :     | (_, ty) => (
708 :     TypeError.error (cxt, [
709 :     S "expected constant expression of type 'int', but found '",
710 :     TY ty, S "'"
711 :     ]);
712 :     NONE)
713 :     (* end case *))
714 :    
715 :     (* check a tensor shape, where the dimensions are given by constant expressions *)
716 :     and checkShape (env, cxt, shape) = let
717 :     fun checkDim' e = (case checkDim (env, cxt, e)
718 :     of SOME d => (
719 :     if (d <= 1)
720 :     then TypeError.error (cxt, [
721 :     S "invalid tensor-shape dimension; must be > 1, but found ",
722 :     S (IntLit.toString d)
723 :     ])
724 :     else ();
725 :     Ty.DimConst(IntInf.toInt d))
726 :     | NONE => Ty.DimConst ~1
727 :     (* end case *))
728 :     in
729 :     Ty.Shape(List.map checkDim' shape)
730 :     end
731 :    
732 : jhr 3396 end

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