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

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