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

SCM Repository

[diderot] View of /branches/vis12/src/compiler/typechecker/typechecker.sml
ViewVC logotype

View of /branches/vis12/src/compiler/typechecker/typechecker.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3150 - (download) (annotate)
Fri Mar 27 16:49:51 2015 UTC (4 years, 3 months ago) by jhr
File size: 60062 byte(s)
  minor edits
(* typechecker.sml
 *
 * COPYRIGHT (c) 2015 The Diderot Project (http://diderot-language.cs.uchicago.edu)
 * All rights reserved.
 *
 * TODO:
 *      prune unreachable code?? (see simplify/simplify.sml)
 *      error recovery so that we can detect multiple errors in a single compile
 *      check that the args of strand creation have the same type and number as the params
 *)

structure Typechecker : sig

    val check : Error.err_stream -> ParseTree.program -> AST.program

  end = struct

    structure BV = BasisVars
    structure PT = ParseTree
    structure Ty = Types
    structure TU = TypeUtil
    structure U = Util

  (* exception to abort typechecking when we hit an error.  Eventually, we should continue
   * checking for more errors and not use this.
   *)
    exception TypeError

  (* variable properties to support unused variable warning *)
    val {getFn=isUsed, setFn=markUsed} = Var.newFlag()
    val {setFn=(setLoc : AST.var * Error.location -> unit), getFn=getLoc, ...} =
          Var.newProp(fn x => raise Fail("no location for " ^ Var.nameOf x))

    datatype scope
      = GlobalScope
      | FunctionScope of Ty.ty * Atom.atom
      | StrandScope
      | MethodScope of StrandUtil.method_name
      | InitScope

    fun scopeToString GlobalScope = "global scope"
      | scopeToString (FunctionScope(_, f)) = "function " ^ Atom.toString f
      | scopeToString StrandScope = "strand initialization"
      | scopeToString (MethodScope m) = "method " ^ StrandUtil.nameToString m
      | scopeToString InitScope = "initialization"

    type env = {
        scope : scope,                          (* current scope *)
        bindings : Error.location AtomMap.map,  (* map from atoms to innermost binding location *)
        env : Env.env                           (* variable environment *)
      }

    type context = Error.err_stream * Error.span

  (* start a new scope *)
    fun functionScope ({scope, bindings, env}, ty, f) =
          {scope=FunctionScope(ty, f), bindings=AtomMap.empty, env=env}
    fun strandScope {scope, bindings, env} =
          {scope=StrandScope, bindings=AtomMap.empty, env=env}
    fun methodScope ({scope, bindings, env}, name) =
          {scope=MethodScope name, bindings=AtomMap.empty, env=env}
    fun initScope {scope, bindings, env} =
          {scope=InitScope, bindings=AtomMap.empty, env=env}
    fun blockScope {scope, bindings, env} =
          {scope=scope, bindings=AtomMap.empty, env=env}

    fun inStrand {scope=StrandScope, bindings, env} = true
      | inStrand {scope=MethodScope _, ...} = true
      | inStrand _ = false

    fun insertStrand ({scope, bindings, env}, cxt, s as AST.Strand{name, ...}) = {
            scope=scope,
            bindings = AtomMap.insert(bindings, name, Error.location cxt),
            env=Env.insertStrand(env, s)
          }
    fun insertFunc ({scope, bindings, env}, cxt, f, f') =  let
          val loc = Error.location cxt
          in
            setLoc(f', loc);
            {
              scope = scope,
              bindings = AtomMap.insert(bindings, f, loc),
              env = Env.insertFunc(env, f, Env.UserFun f')
            }
          end
    fun insertLocal ({scope, bindings, env}, cxt, x, x') = let
          val loc = Error.location cxt
          in
            setLoc(x', loc);
            {
              scope = scope,
              bindings = AtomMap.insert(bindings, x, loc),
              env = Env.insertLocal(env, x, x')
            }
          end
    fun insertGlobal ({scope, bindings, env}, cxt, x, x') = let
          val loc = Error.location cxt
          in
            setLoc(x', loc);
            {
              scope = scope,
              bindings = AtomMap.insert(bindings, x, loc),
              env = Env.insertGlobal(env, x, x')
            }
          end

    fun withContext ((errStrm, _), {span, tree}) =
          ((errStrm, span), tree)
    fun withEnvAndContext (env, (errStrm, _), {span, tree}) =
          (env, (errStrm, span), tree)

    datatype token
      = S of string | A of Atom.atom
      | V of AST.var | TY of Types.ty | TYS of Types.ty list

    local
      fun tysToString tys = String.concat[
              "(", String.concatWith " * " (List.map TU.toString tys), ")"
            ]
      fun tok2str (S s) = s
        | tok2str (A a) = concat["'", Atom.toString a, "'"]
        | tok2str (V x) = concat["'", Var.nameOf x, "'"]
        | tok2str (TY ty) = TU.toString ty
        | tok2str (TYS []) = "()"
        | tok2str (TYS[ty]) = TU.toString ty
        | tok2str (TYS tys) = tysToString tys
    in
    fun warn ((errStrm, span), toks) = Error.warningAt(errStrm, span, List.map tok2str toks)
    fun err ((errStrm, span), toks) = (
          Error.errorAt(errStrm, span, List.map tok2str toks);
(* FIXME: add error recovery *)
          raise TypeError)
    end (* local *)

  (* check for redefinition of an identifier in the same scope *)
(* TODO: check for shadowing too? *)
    fun checkForRedef (env : env, cxt : context, x) = (case AtomMap.find(#bindings env, x)
           of SOME loc => err (cxt, [
                  S "redefinition of ", A x, S ", previous definition at ",
                  S(Error.locToString loc)
                ])
            | NONE => ()
          (* end case *))

    val realZero = AST.E_Lit(Literal.Float(FloatLit.zero true))

  (* check a differentiation level, which must be >= 0 *)
    fun checkDiff (cxt, k) =
          if (k < 0)
            then err (cxt, [S "differentiation must be >= 0"])
            else Ty.DiffConst(IntInf.toInt k)

  (* check a sequence dimension, which must be > 0 *)
    fun checkSeqDim (cxt, d) =
          if (d < 0)
            then err (cxt, [S "invalid dimension; must be positive"])
            else Ty.DimConst(IntInf.toInt d)

  (* check a dimension, which must be 1, 2 or 3 *)
    fun checkDim (cxt, d) =
          if (d < 1) orelse (3 < d)
            then err (cxt, [S "invalid dimension; must be 1, 2, or 3"])
            else Ty.DimConst(IntInf.toInt d)

  (* check a shape *)
    fun checkShape (cxt, shape) =  let
          fun checkDim d =
                if (d <= 1)
                  then err (cxt, [S "invalid tensor-shape dimension; must be > 1"])
                  else Ty.DimConst(IntInf.toInt d)
          in
            Ty.Shape(List.map checkDim shape)
          end

  (* check the well-formedness of a type and translate it to an AST type *)
    fun checkTy (cxt, ty) = (case ty
           of PT.T_Mark m => checkTy(withContext(cxt, m))
            | PT.T_Bool => Ty.T_Bool
            | PT.T_Int => Ty.T_Int
            | PT.T_Real => Ty.realTy
(* FIXME: should look up the strand name in the environment! *)
            | PT.T_Strand strand => raise Fail "Strand types not supported in this branch!"
            | PT.T_String => Ty.T_String
            | PT.T_Vec n => (* NOTE: the parser guarantees that 2 <= n <= 4 *)
                Ty.vecTy(IntInf.toInt n)
            | PT.T_Kernel k => Ty.T_Kernel(checkDiff(cxt, k))
            | PT.T_Field{diff, dim, shape} => Ty.T_Field{
                  diff = checkDiff (cxt, diff),
                  dim = checkDim (cxt, dim),
                  shape = checkShape (cxt, shape)
                }
            | PT.T_Tensor shape => Ty.T_Tensor(checkShape(cxt, shape))
            | PT.T_Image{dim, shape} => Ty.T_Image{
                  dim = checkDim (cxt, dim),
                  shape = checkShape (cxt, shape)
                }
            | PT.T_Seq(ty, dim) => let
                val ty = checkTy(cxt, ty)
                in
                  if TU.isFixedSizeType ty
                    then Ty.T_Sequence(ty, checkSeqDim (cxt, dim))
                    else err(cxt, [S "elements of sequence types must be fixed-size types"])
                end
            | PT.T_DynSeq ty => let
                val ty = checkTy(cxt, ty)
                in
                  if TU.isFixedSizeType ty
                    then Ty.T_DynSequence(ty)
                    else err(cxt, [S "elements of sequence types must be fixed-size types"])
                end
          (* end case *))

    fun checkLit lit = (case lit
           of (Literal.Int _) => (AST.E_Lit lit, Ty.T_Int)
            | (Literal.Float _) => (AST.E_Lit lit, Ty.realTy)
            | (Literal.String s) => (AST.E_Lit lit, Ty.T_String)
            | (Literal.Bool _) => (AST.E_Lit lit, Ty.T_Bool)
          (* end case *))

    fun coerceExp (Ty.T_Tensor(Ty.Shape[]), Ty.T_Int, AST.E_Lit(Literal.Int n)) =
          AST.E_Lit(Literal.Float(FloatLit.fromInt n))
      | coerceExp (ty1, ty2, e) = AST.E_Coerce{srcTy=ty2, dstTy=ty1, e=e}

    fun coerceType (dstTy, srcTy, e) = (case U.matchType(dstTy, srcTy)
           of U.EQ => SOME e
            | U.COERCE => SOME(coerceExp (dstTy, srcTy, e))
            | U.FAIL => NONE
          (* end case *))

    fun realType (ty as Ty.T_Tensor(Ty.Shape[])) = ty
      | realType (ty as Ty.T_Int) = Ty.realTy
      | realType ty = ty

  (* resolve overloading: we use a simple scheme that selects the first operator in the
   * list that matches the argument types.
   *)
    fun resolveOverload (_, rator, _, _, []) = raise Fail(concat[
            "resolveOverload: \"", Atom.toString rator, "\" has no candidates"
          ])
      | resolveOverload (cxt, rator, argTys, args, candidates) = let
(* FIXME: we could be more efficient by just checking for coercion matchs the first pass
 * and remembering those that are not pure EQ matches.
 *)
        (* try to match candidates while allowing type coercions *)
          fun tryMatchCandidates [] = err(cxt, [
                  S "unable to resolve overloaded operator ", A rator, S "\n",
                  S "  argument type is: ", TYS argTys, S "\n"
                ])
            | tryMatchCandidates (x::xs) = let
                val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
                in
                  case U.tryMatchArgs (domTy, args, argTys)
                   of SOME args' => (AST.E_Apply(x, tyArgs, args', rngTy), rngTy)
                    | NONE => tryMatchCandidates xs
                  (* end case *)
                end
          fun tryCandidates [] = tryMatchCandidates candidates
            | tryCandidates (x::xs) = let
                val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
                in
                  if U.tryEqualTypes(domTy, argTys)
                    then (AST.E_Apply(x, tyArgs, args, rngTy), rngTy)
                    else tryCandidates xs
                end
          in
            tryCandidates candidates
          end

  (* typecheck an expression and translate it to AST *)
    fun checkExpr (env : env, cxt, e) = (case e
           of PT.E_Mark m => checkExpr (withEnvAndContext (env, cxt, m))
            | PT.E_Var x => (case Env.findVar (#env env, x)
                 of SOME x' => (
                      markUsed (x', true);
                      (AST.E_Var x', Var.monoTypeOf x'))
                  | NONE => err(cxt, [S "undeclared variable ", A x])
                (* end case *))
            | PT.E_Lit lit => checkLit lit
            | PT.E_OrElse(e1, e2) => let
                val (e1', ty1) = checkExpr(env, cxt, e1)
                val (e2', ty2) = checkExpr(env, cxt, e2)
                in
                  case (ty1, ty2)
                   of (Ty.T_Bool, Ty.T_Bool) =>
                        (AST.E_Cond(e1', AST.E_Lit(Literal.Bool true), e2', Ty.T_Bool), Ty.T_Bool)
                    | _ => err (cxt, [S "arguments to \"||\" must have bool type"])
                  (* end case *)
                end
            | PT.E_AndAlso(e1, e2) => let
                val (e1', ty1) = checkExpr(env, cxt, e1)
                val (e2', ty2) = checkExpr(env, cxt, e2)
                in
                  case (ty1, ty2)
                   of (Ty.T_Bool, Ty.T_Bool) =>
                        (AST.E_Cond(e1', e2', AST.E_Lit(Literal.Bool false), Ty.T_Bool), Ty.T_Bool)
                    | _ => err (cxt, [S "arguments to \"&&\" must have bool type"])
                  (* end case *)
                end
            | PT.E_Cond(e1, cond, e2) => let
                val (e1', ty1) = checkExpr(env, cxt, e1)
                val (e2', ty2) = checkExpr(env, cxt, e2)
                in
                  case checkExpr(env, cxt, cond)
                   of (cond', Ty.T_Bool) =>
                        if U.equalType(ty1, ty2)
                          then (AST.E_Cond(cond', e1', e2', ty1), ty1)
                          else err (cxt, [
                              S "types do not match in conditional expression\n",
                              S "  true branch:  ", TY ty1, S "\n",
                              S "  false branch: ", TY ty2
                            ])
                    | (_, ty') => err (cxt, [S "expected bool type, but found ", TY ty'])
                  (* end case *)
                end
            | PT.E_BinOp(e1, rator, e2) => let
                val (e1', ty1) = checkExpr(env, cxt, e1)
                val (e2', ty2) = checkExpr(env, cxt, e2)
                in
                  if Atom.same(rator, BasisNames.op_dot)
                    (* we have to handle inner product as a special case, because out type
                     * system cannot express the constraint that the type is
                     *     ALL[sigma1, d1, sigma2] . tensor[sigma1, d1] * tensor[d1, sigma2] -> tensor[sigma1, sigma2]
                     *)
                    then (case (TU.prune ty1, TU.prune ty2)
                       of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_)), Ty.T_Tensor(s2 as Ty.Shape(d2::dd2))) => let
                            val (dd1, d1) = let
                                  fun splitLast (prefix, [d]) = (List.rev prefix, d)
                                    | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
                                    | splitLast (_, []) = raise Fail "impossible"
                                  in
                                    splitLast ([], dd1)
                                  end
                            val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_inner)
                            val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
                            in
                              if U.equalDim(d1, d2)
                              andalso U.equalTypes(domTy, [ty1, ty2])
                              andalso U.equalType(rngTy, resTy)
                                then (AST.E_Apply(BV.op_inner, tyArgs, [e1', e2'], rngTy), rngTy)
                                else err (cxt, [
                                    S "type error for arguments of binary operator \"•\"\n",
                                    S "  found: ", TYS[ty1, ty2], S "\n"
                                  ])
                            end
                       | (ty1, ty2) => err (cxt, [
                              S "type error for arguments of binary operator \"•\"\n",
                              S "  found: ", TYS[ty1, ty2], S "\n"
                            ])
                      (* end case *))
                  else if Atom.same(rator, BasisNames.op_colon)
                    then (case (TU.prune ty1, TU.prune ty2)
                       of (Ty.T_Tensor(s1 as Ty.Shape(dd1 as _::_::_)), Ty.T_Tensor(s2 as Ty.Shape(d21::d22::dd2))) => let
                            val (dd1, d11, d12) = let
                                  fun splitLast (prefix, [d1, d2]) = (List.rev prefix, d1, d2)
                                    | splitLast (prefix, d::dd) = splitLast (d::prefix, dd)
                                    | splitLast (_, []) = raise Fail "impossible"
                                  in
                                    splitLast ([], dd1)
                                  end
                            val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf BV.op_colon)
                            val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
                            in
                              if U.equalDim(d11, d21) andalso U.equalDim(d12, d22)
                              andalso U.equalTypes(domTy, [ty1, ty2])
                              andalso U.equalType(rngTy, resTy)
                                then (AST.E_Apply(BV.op_colon, tyArgs, [e1', e2'], rngTy), rngTy)
                                else err (cxt, [
                                    S "type error for arguments of binary operator \":\"\n",
                                    S "  found: ", TYS[ty1, ty2], S "\n"
                                  ])
                            end
                       | (ty1, ty2) => err (cxt, [
                              S "type error for arguments of binary operator \":\"\n",
                              S "  found: ", TYS[ty1, ty2], S "\n"
                            ])
                      (* end case *))
                    else (case Env.findFunc (#env env, rator)
                       of Env.PrimFun[rator] => let
                            val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
                            in
                              case U.matchArgs(domTy, [e1', e2'], [ty1, ty2])
                               of SOME args => (AST.E_Apply(rator, tyArgs, args, rngTy), rngTy)
                                | NONE => err (cxt, [
                                      S "type error for binary operator \"", V rator, S "\"\n",
                                      S "  expected:  ", TYS domTy, S "\n",
                                      S "  but found: ", TYS[ty1, ty2]
                                    ])
                              (* end case *)
                            end
                        | Env.PrimFun ovldList =>
                            resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
                        | _ => raise Fail "impossible"
                      (* end case *))
                end
            | PT.E_UnaryOp(rator, e) => let
                val (e', ty) = checkExpr(env, cxt, e)
                in
                  case Env.findFunc (#env env, rator)
                   of Env.PrimFun[rator] => let
                        val (tyArgs, Ty.T_Fun([domTy], rngTy)) = U.instantiate(Var.typeOf rator)
                        in
                          case coerceType (domTy, ty, e')
                           of SOME e' => (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
                            | NONE => err (cxt, [
                                  S "type error for unary operator \"", V rator, S "\"\n",
                                  S "  expected:  ", TY domTy, S "\n",
                                  S "  but found: ", TY ty
                                ])
                          (* end case *)
                        end
                    | Env.PrimFun ovldList => resolveOverload (cxt, rator, [ty], [e'], ovldList)
                    | _ => raise Fail "impossible"
                  (* end case *)
                end
            | PT.E_Slice(e, indices) => let
                val (e', ty) = checkExpr (env, cxt, e)
                fun checkIndex NONE = NONE
                  | checkIndex (SOME e) = let
                      val (e', ty) = checkExpr (env, cxt, e)
                      in
                        if U.equalType(ty, Ty.T_Int)
                          then (SOME e')
                          else err (cxt, [
                              S "type error in index expression\n",
                              S "  expected int, but found: ", TY ty
                            ])
                      end
                val indices' = List.map checkIndex indices
                val order = List.length indices'
                val expectedTy = TU.mkTensorTy order
                val resultTy = TU.slice(expectedTy, List.map Option.isSome indices')
                in
                  if U.equalType(ty, expectedTy)
                    then ()
                    else err (cxt, [
                        S "type error in slice operation\n",
                        S "  expected:  ", S(Int.toString order), S "-order tensor\n",
                        S "  but found: ", TY ty
                      ]);
                  (AST.E_Slice(e', indices', resultTy), resultTy)
                end
            | PT.E_Select(e, fld) => raise Fail "strand selection is not supported in this branch"
            | PT.E_Subscript(e1, e2) => let
                val (e1', ty1) = checkExpr (env, cxt, e1)
                val (e2', ty2) = checkExpr (env, cxt, e2)
                fun chkIndex () = if U.equalType(ty2, Ty.T_Int)
                        then ()
                        else err (cxt, [
                            S "expected int type for subscript index\n",
                            S "  but found: ", TY ty2
                          ])
                fun finish rator = let
                      val (tyArgs, Ty.T_Fun(domTy, rngTy)) = U.instantiate(Var.typeOf rator)
                      in
                        if U.equalTypes(domTy, [ty1, ty2])
                          then let
                            val exp = AST.E_Apply(rator, tyArgs, [e1', e2'], rngTy)
                            in
                              (exp, rngTy)
                            end
                          else raise Fail "unexpected unification failure"
                      end
                in
                  case TU.pruneHead ty1
                   of Ty.T_DynSequence _ => (
                        chkIndex ();
                        finish BV.dynSubscript)
                    | Ty.T_Sequence _ => (
                        chkIndex ();
                        finish BV.subscript)
                    | _ => err (cxt, [
                          S "expected sequence type for subscript\n",
                          S "  but found: ", TY ty1
                        ])
                  (* end case *)
                end
            | PT.E_Apply(e, args) => let
                fun stripMark (PT.E_Mark{tree, ...}) = stripMark tree
                  | stripMark e = e
                val (args, tys) = checkExprList (env, cxt, args)
                fun checkFunApp f = (case Util.instantiate(Var.typeOf f)
                       of (tyArgs, Ty.T_Fun(domTy, rngTy)) => (
                            case U.matchArgs (domTy, args, tys)
                             of SOME args => (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
                              | NONE => err(cxt, [
                                    S "type error in application of ", V f, S "\n",
                                    S "  expected:  ", TYS domTy, S "\n",
                                    S "  but found: ", TYS tys
                                  ])
                            (* end case *))
                        | _ => err(cxt, [S "application of non-function ", V f])
                      (* end case *))
                fun checkFieldApp (e1', ty1) = (case (args, tys)
                       of ([e2'], [ty2]) => let
                            val (tyArgs, Ty.T_Fun([fldTy, domTy], rngTy)) =
                                  Util.instantiate(Var.typeOf BV.op_probe)
                            fun tyError () = err (cxt, [
                                    S "type error for field application\n",
                                    S "  expected:  ", TYS[fldTy, domTy], S "\n",
                                    S "  but found: ", TYS[ty1, ty2]
                                  ])
                            in
                              if U.equalType(fldTy, ty1)
                                then (case coerceType(domTy, ty2, e2')
                                   of SOME e2' => (AST.E_Apply(BV.op_probe, tyArgs, [e1', e2'], rngTy), rngTy)
                                    | NONE => tyError()
                                  (* end case *))
                                else tyError()
                            end
                        | _ => err(cxt, [S "badly formed field application"])
                      (* end case *))
                in
                  case stripMark e
                   of PT.E_Var f => (case Env.findVar (#env env, f)
                         of SOME f' => (
                              markUsed (f', true);
                              checkFieldApp (AST.E_Var f', Var.monoTypeOf f'))
                          | NONE => (case Env.findFunc (#env env, f)
                               of Env.PrimFun[] => err(cxt, [S "unknown function ", A f])
                                | Env.PrimFun[f'] =>
                                    if (inStrand env) andalso (Basis.isRestricted f')
                                      then err(cxt, [
                                          S "use of restricted operation ", V f',
                                          S " in strand body"
                                        ])
                                      else checkFunApp f'
                                | Env.PrimFun ovldList =>
                                    resolveOverload (cxt, f, tys, args, ovldList)
                                | Env.UserFun f' => (
                                    markUsed (f', true);
                                    checkFunApp f')
                              (* end case *))
                          (* end case *))
                    | _ => checkFieldApp (checkExpr (env, cxt, e))
                  (* end case *)
                end
            | PT.E_Tuple args => let
                val (args, tys) = checkExprList (env, cxt, args)
                in
                  raise Fail "E_Tuple not yet implemented" (* FIXME *)
                end
            | PT.E_Sequence args => (case checkExprList (env, cxt, args)
(* FIXME: need kind for concrete types here! *)
                 of ([], _) => let
                      val ty = Ty.T_Sequence(Ty.T_Var(MetaVar.newTyVar()), Ty.DimConst 0)
                      in
                        (AST.E_Seq([], ty), ty)
                      end
                  | (args, ty::tys) =>
                      if TU.isFixedSizeType(TU.pruneHead ty)
                        then let
                          fun chkTy ty' = U.equalType(ty, ty')
                          val resTy = Ty.T_Sequence(ty, Ty.DimConst(List.length args))
                          in
                            if List.all chkTy tys
                              then (AST.E_Seq(args, resTy), resTy)
                              else err(cxt, [S "arguments of sequence expression must have same type"])
                          end
                        else err(cxt, [S "sequence expression of non-value argument type"])
                (* end case *))
            | PT.E_SeqComp(e1, x, e2) => raise Fail "comprehensions not supported in this branch"
            | PT.E_Cons args => let
                val (args, tys as ty::_) = checkExprList (env, cxt, args)
                in
                  case realType(TU.pruneHead ty)
                   of ty as Ty.T_Tensor shape => let
                        val Ty.Shape dd = TU.pruneShape shape (* NOTE: this may fail if we allow user polymorphism *)
                        val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
                        fun chkArgs (arg::args, argTy::tys, args') = (case coerceType(ty, argTy, arg)
                               of SOME arg' => chkArgs (args, tys, arg'::args')
                                | NONE => err(cxt, [S "arguments of tensor construction must have same type"])
                              (* end case *))
                          | chkArgs ([], [], args') = (AST.E_Cons(List.rev args'), resTy)
                        in
                          chkArgs (args, tys, [])
                        end
                    | _ => err(cxt, [S "Invalid argument type for tensor construction"])
                  (* end case *)
                end
            | PT.E_Real e => (case checkExpr (env, cxt, e)
                 of (e', Ty.T_Int) =>
                      (AST.E_Apply(BV.i2r, [], [e'], Ty.realTy), Ty.realTy)
                  | _ => err(cxt, [S "argument of real conversion must be int"])
                (* end case *))
            | PT.E_Id d => let
                val (tyArgs, Ty.T_Fun(_, rngTy)) =
                      Util.instantiate(Var.typeOf(BV.identity))
                in
                  if U.equalType(Ty.T_Tensor(checkShape(cxt, [d,d])), rngTy)
                    then (AST.E_Apply(BV.identity, tyArgs, [], rngTy), rngTy)
                    else raise Fail "impossible"
                end
            | PT.E_Zero dd => let
                val (tyArgs, Ty.T_Fun(_, rngTy)) =
                      Util.instantiate(Var.typeOf(BV.zero))
                in
                  if U.equalType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
                    then (AST.E_Apply(BV.zero, tyArgs, [], rngTy), rngTy)
                    else raise Fail "impossible"
                end
            | PT.E_NaN dd => let
                val (tyArgs, Ty.T_Fun(_, rngTy)) =
                      Util.instantiate(Var.typeOf(BV.nan))
                in
                  if U.equalType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
                    then (AST.E_Apply(BV.nan, tyArgs, [], rngTy), rngTy)
                    else raise Fail "impossible"
                end
            | PT.E_Image nrrd => let
                val (tyArgs, Ty.T_Fun(_, rngTy)) = Util.instantiate(Var.typeOf(BV.fn_image))
                in
                  (AST.E_LoadNrrd(tyArgs, nrrd, rngTy), rngTy)
                end
            | PT.E_Load nrrd => let
                val (tyArgs, Ty.T_Fun(_, rngTy)) = Util.instantiate(Var.typeOf(BV.fn_load))
                in
                  (AST.E_LoadNrrd(tyArgs, nrrd, rngTy), rngTy)
                end
          (* end case *))

  (* typecheck a list of expressions returning a list of AST expressions and a list
   * of types of the expressions.
   *)
    and checkExprList (env, cxt, exprs) = let
          fun chk (e, (es, tys)) = let
                val (e, ty) = checkExpr (env, cxt, e)
                in
                  (e::es, ty::tys)
                end
          in
            List.foldr chk ([], []) exprs
          end

    fun checkVarDecl (env, cxt, kind, d) = (case d
           of PT.VD_Mark m => checkVarDecl (env, (#1 cxt, #span m), kind, #tree m)
            | PT.VD_Decl(ty, x, e) => let
                val ty = checkTy (cxt, ty)
                val x' = Var.new (x, kind, ty)
                val (e', ty') = checkExpr (env, cxt, e)
                in
                  case coerceType (ty, ty', e')
                   of SOME e' => (x, x', e')
                    | NONE => err(cxt, [
                        S "type of variable ", A x,
                        S " does not match type of initializer\n",
                        S "  expected: ", TY ty, S "\n",
                        S "  but found: ", TY ty'
                      ])
                  (* end case *)
                end
          (* end case *))

  (* check for unreachable code and non-return statements in the tail position of a function.
   * Note that unreachable code is typechecked and included in the AST.  It is pruned away
   * by simplify.
   *)
    fun chkCtlFlow (cxt, scope, stm) = let
          val (inFun, inUpdate, funName) = (case scope
                 of FunctionScope(_, f) => (true, false, Atom.toString f)
                  | MethodScope StrandUtil.Update => (false, true, "")
                  | _ => (false, false, "")
                (* end case *))
        (* checks a statement for correct control flow; it returns false if control may
         * flow from the statement to the next in a sequence and true if control cannot
         * flow to the next statement.
         *)
          fun chk ((errStrm, _), hasSucc, isJoin, unreachable, PT.S_Mark{span, tree}) =
                chk((errStrm, span), hasSucc, isJoin, unreachable, tree)
            | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Block(stms as _::_)) = let
                fun chk' ([], escapes) = escapes
                  | chk' ([stm], escapes) =
                      chk(cxt, hasSucc, isJoin, escapes orelse unreachable, stm) orelse escapes
                  | chk' (stm::stms, escapes) = let
                      val escapes = chk(cxt, true, false, escapes orelse unreachable, stm) orelse escapes
                      in
                        chk'(stms, escapes)
                      end
                in
                  chk' (stms, false)
                end
            | chk (cxt, hasSucc, isJoin, unreachable, PT.S_IfThen(_, stm)) = (
                if inFun andalso not hasSucc andalso not unreachable
                  then err(cxt, [
                        S "Missing return statement in tail position of function ", S funName
                    ])
                  else ();
                ignore (chk (cxt, hasSucc, true, unreachable, stm));
                false)
            | chk (cxt, hasSucc, isJoin, unreachable, PT.S_IfThenElse(_, stm1, stm2)) = let
                val escapes = chk (cxt, hasSucc, true, unreachable, stm1)
                val escapes = chk (cxt, hasSucc, true, unreachable, stm2) andalso escapes
                in
                  if escapes andalso hasSucc andalso not unreachable
                    then (
                      warn(cxt, [S "unreachable statements after \"if-then-else\" statement"]);
                      true)
                    else escapes
                end
            | chk (cxt, _, _, _, PT.S_New _) = (
                if not inUpdate
                  then err(cxt, [S "\"new\" statement outside of update method"])
                  else ();
                false)
            | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Die) = (
                if not inUpdate
                  then err(cxt, [S "\"die\" statment outside of update method"])
                else if hasSucc andalso not isJoin andalso not unreachable
                  then warn(cxt, [S "statements following \"die\" statment are unreachable"])
                  else ();
                true)
            | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Stabilize) = (
                if not inUpdate
                  then err(cxt, [S "\"stabilize\" statment outside of update method"])
                else if hasSucc andalso not isJoin andalso not unreachable
                  then warn(cxt, [S "statements following \"stabilize\" statment are unreachable"])
                  else ();
                true)
            | chk (cxt, hasSucc, isJoin, unreachable, PT.S_Return _) = (
                if not inFun
                  then err(cxt, [S "\"return\" statment outside of function body"])
                else if hasSucc andalso not isJoin andalso not unreachable
                  then warn(cxt, [S "statements following \"return\" statment are unreachable"])
                  else ();
                true)
            | chk (cxt, hasSucc, isJoin, unreachable, _) = (
                if inFun andalso not hasSucc andalso not unreachable
                  then err(cxt, [
                        S "Missing return statement in tail position of function ", S funName
                    ])
                  else ();
                false)
          in
            ignore (chk (cxt, false, false, false, stm))
          end

  (* check the creation of a new strand; either in a "new" statement or in an "initially"
   * block.
   *)
    fun checkStrandCreate (env, cxt, strand, args) = let
          val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
          val (args', tys') = ListPair.unzip argsAndTys'
          in
          (* check that strand is defined and that the argument types match *)
            case Env.findStrand (#env env, strand)
             of SOME(AST.Strand{params, ...}) => let
                  val paramTys = List.map Var.monoTypeOf params
                  in
                    case U.matchArgs (paramTys, args', tys')
                     of SOME args' => (strand, args', env)
                      | NONE => err(cxt, [
                          S "type error in new ", A strand, S "\n",
                          S "  expected:  ", TYS paramTys, S "\n",
                          S "  but found: ", TYS tys'
                        ])
                    (* end case *)
                  end
              | NONE => err(cxt, [S "unknown strand ", A strand])
            (* end case *)
          end

  (* typecheck a statement and translate it to AST *)
    fun checkStmt (env : env, cxt : context, stm) = let
          fun chkStmt (env : env, cxt : context, s) = (case s
                 of PT.S_Mark m => chkStmt (withEnvAndContext (env, cxt, m))
                  | PT.S_Block stms => let
                      fun chk (_, [], stms) = AST.S_Block(List.rev stms)
                        | chk (env, s::ss, stms) = let
                            val (s', env') = chkStmt (env, cxt, s)
                            in
                              chk (env', ss, s'::stms)
                            end
                      in
                        (chk (blockScope env, stms, []), env)
                      end
                  | PT.S_Decl vd => let
                      val (x, x', e) = checkVarDecl (env, cxt, Var.LocalVar, vd)
                      in
                        checkForRedef (env, cxt, x);
                        (AST.S_Decl(AST.VD_Decl(x', e)), insertLocal(env, cxt, x, x'))
                      end
                  | PT.S_IfThen(e, s) => let
                      val (e', ty) = checkExpr (env, cxt, e)
                      val (s', _) = chkStmt (env, cxt, s)
                      in
                      (* check that condition has bool type *)
                        case ty
                         of Ty.T_Bool => ()
                          | _ => err(cxt, [S "condition not boolean type"])
                        (* end case *);
                        (AST.S_IfThenElse(e', s', AST.S_Block[]), env)
                      end
                  | PT.S_IfThenElse(e, s1, s2) => let
                      val (e', ty) = checkExpr (env, cxt, e)
                      val (s1', _) = chkStmt (env, cxt, s1)
                      val (s2', _) = chkStmt (env, cxt, s2)
                      in
                      (* check that condition has bool type *)
                        case ty
                         of Ty.T_Bool => ()
                          | _ => err(cxt, [S "condition not boolean type"])
                        (* end case *);
                        (AST.S_IfThenElse(e', s1', s2'), env)
                      end
                  | PT.S_Foreach(vd, s) => raise Fail "foreach not supported in this branch"  
                  | PT.S_Assign(x, e) => (case Env.findVar (#env env, x)
                       of NONE => err(cxt, [
                              S "undefined variable ", A x
                            ])
                        | SOME x' => let
(* FIXME: check for polymorphic variables *)
                            val ([], ty) = Var.typeOf x'
                            val (e', ty') = checkExpr (env, cxt, e)
                          (* check for promotion *)
                            val e' = (case coerceType(ty, ty', e')
                                   of SOME e' => e'
                                    | NONE => err(cxt, [
                                          S "type of assigned variable ", A x,
                                          S " does not match type of rhs\n",
                                          S "  expected: ", TY ty, S "\n",
                                          S "  but found: ", TY ty'
                                        ])
                                  (* end case *))
                            in
                            (* check that x' is mutable *)
                              case Var.kindOf x'
                               of Var.StrandStateVar => ()
                                | Var.StrandOutputVar => markUsed (x', true)
                                | Var.LocalVar => ()
                                | _ => err(cxt, [
                                      S "assignment to immutable variable ", A x,
                                      S " in ", S(scopeToString(#scope env))
                                    ])
                              (* end case *);
                              (AST.S_Assign(x', e'), env)
                            end
                      (* end case *))
                  | PT.S_OpAssign(x, rator, e) => (case Env.findVar (#env env, x)
                       of SOME x' => let
                            val e1' = AST.E_Var x'
                            val ty1 = Var.monoTypeOf x'
                            val (e2', ty2) = checkExpr(env, cxt, e)
                            val Env.PrimFun ovldList = Env.findFunc (#env env, rator)
                            val (rhs, _) = resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
                            in
                            (* check that x' is mutable *)
                              case Var.kindOf x'
                               of Var.StrandStateVar => ()
                                | Var.StrandOutputVar => markUsed (x', true)
                                | Var.LocalVar => ()
                                | _ => err(cxt, [
                                      S "assignment to immutable variable ", A x,
                                      S " in ", S(scopeToString(#scope env))
                                    ])
                              (* end case *);
                              (AST.S_Assign(x', rhs), env)
                            end
                        | NONE => err(cxt, [S "undeclared variable ", A x, S " on lhs of ", A rator])
                      (* end case *))
                  | PT.S_New(strand, args) => let
                    (* note that scope has already been checked in chkCtlFlow *)
                      val (strand, args, env) = checkStrandCreate (env, cxt, strand, args)
                      in
                        Env.recordProp (#env env, StrandUtil.NewStrands);
                        (AST.S_New(strand, args), env)
                      end
                  | PT.S_Die => (
                    (* note that scope has already been checked in chkCtlFlow *)
                      Env.recordProp (#env env, StrandUtil.StrandsMayDie);
                      (AST.S_Die, env))
                  | PT.S_Stabilize => (AST.S_Stabilize, env) (* note that scope has already been checked in chkCtlFlow *)
                  | PT.S_Return e => let
                      val (e', ty) = checkExpr (env, cxt, e)
                      in
                        case #scope env
                         of FunctionScope(ty', f) => (case coerceType(ty', ty, e')
                               of SOME e' => (AST.S_Return e', env)
                                | NONE => err(cxt, [
                                      S "type of return expression does not match return type of function ",
                                      A f, S "\n",
                                      S "  expected: ", TY ty', S "\n",
                                      S "  but found: ", TY ty
                                    ])
                              (* end case *))
                          | _ => (AST.S_Return e', env) (* this error condition has already been checked *)
                        (* end case *)
                      end
                  | PT.S_Print args => let
                      fun chkArg e = let
                            val (e', ty) = checkExpr (env, cxt, e)
                            in
                              if TU.isValueType ty
                                then ()
                                else err(cxt, [
                                    S "expected value type in print, but found ", TY ty
                                 ]);
                              e'
                            end
                      val args' = List.map chkArg args
                      in
                        (AST.S_Print args', env)
                      end
                (* end case *))
          in
            chkCtlFlow (cxt, #scope env, stm);
            chkStmt (env, cxt, stm)
          end (* checkStmt *)

    fun checkParams (env, cxt, params) = let
          fun chkParam (env, cxt, param) = (case param
                 of PT.P_Mark m => chkParam (withEnvAndContext (env, cxt, m))
                  | PT.P_Param(ty, x) => let
                      val x' = Var.new(x, AST.StrandParam, checkTy (cxt, ty))
                      in
                        checkForRedef (env, cxt, x);
                        (x', insertLocal(env, cxt, x, x'))
                      end
                (* end case *))
          fun chk (param, (xs, env)) = let
                val (x, env) = chkParam (env, cxt, param)
                in
                  (x::xs, env)
                end
          in
            List.foldr chk ([], env) params
          end

    fun checkMethod (env, cxt, meth) = (case meth
           of PT.M_Mark m => checkMethod (withEnvAndContext (env, cxt, m))
            | PT.M_Method(name, body) => let
                val (body, _) = checkStmt(methodScope (env, name), cxt, body)
                in
                  AST.M_Method(name, body)
                end
          (* end case *))

    fun checkStrand (env, cxt, {name, params, state, methods}) = let
        (* check the strand parameters *)
          val (params, env) = checkParams (strandScope env, cxt, params)
        (* check the strand state variable definitions *)
          val (vds, hasOutput, env) = let
                fun checkStateVar ((isOut, vd), (vds, hasOut, env)) = let
                      val kind = if isOut then AST.StrandOutputVar else AST.StrandStateVar
                      val (x, x', e') = checkVarDecl (env, cxt, kind, vd)
                      in
                      (* check that strand variables have value types *)
                        if not(TU.isValueType(Var.monoTypeOf x'))
                          then err(cxt, [
                              S "strand variable ", V x', S " has non-value type ",
                              TY(Var.monoTypeOf x')
                            ])
                          else ();
                        checkForRedef (env, cxt, x);
                        (AST.VD_Decl(x', e')::vds, hasOut orelse isOut, insertLocal(env, cxt, x, x'))
                      end
                val (vds, hasOutput, env) = List.foldl checkStateVar ([], false, env) state
                in
                  (List.rev vds, hasOutput, env)
                end
        (* define a dummy strand definition so that recursive mentions of this strand will
         * typecheck.
         *)
          val env = let
                val strand = AST.Strand{name = name, params = params, state = vds, methods = []}
                in
                  insertStrand(env, cxt, strand)
                end
        (* check the strand methods *)
          val methods = List.map (fn m => checkMethod (env, cxt, m)) methods
        (* get the list of methods defined by the user *)
          val methodNames = List.map (fn (AST.M_Method(name, _)) => name) methods
        (* if the stabilize method is not provided then add one, otherwise record the property *)
(* FIXME: perhaps we can get away without creating a dummy stabilize method! *)
          val methods = if List.exists (fn StrandUtil.Stabilize => true | _ => false) methodNames
                then (
                  Env.recordProp (#env env, StrandUtil.HasStabilizeMethod);
                  methods)
                else methods @ [AST.M_Method(StrandUtil.Stabilize, AST.S_Block[])]
          in
(* FIXME: once there are global outputs, then it should be okay to have not strand outputs! *)
        (* check that there is at least one output variable *)
            if not hasOutput
              then err(cxt, [S "strand ", A name, S " does not have any outputs"])
              else ();
(* FIXME: should check for duplicate method definitions *)
            if not(List.exists (fn StrandUtil.Update => true | _ => false) methodNames)
              then err(cxt, [S "strand ", A name, S " is missing an update method"])
              else ();
            AST.Strand{name = name, params = params, state = vds, methods = methods}
          end

    fun checkCreate (env, cxt, PT.C_Mark m) = checkCreate (withEnvAndContext (env, cxt, m))
      | checkCreate (env, cxt, PT.C_Create(strand, args)) = let
          val (strand, args, env) = checkStrandCreate (env, cxt, strand, args)
          in
            AST.C_Create(strand, args)
          end

    fun checkIters (env0, cxt, iters) = let
        (* check an iteration range specification from the initially clause.  We do the checking
         * of the expressions using env0, which does not have any of the iteration variables in
         * it (the iteration is rectangular), but we also accumulate the iteration bindings,
         * which are used to create the final environment for checking the create call.
         *)
          fun checkIter (env, cxt, PT.I_Mark m) = checkIter (withEnvAndContext (env, cxt, m))
            | checkIter (env, cxt, PT.I_Range(x, e1, e2)) = let
                val (e1', ty1) = checkExpr (env, cxt, e1)
                val (e2', ty2) = checkExpr (env, cxt, e2)
                val x' = Var.new(x, Var.LocalVar, Ty.T_Int)
                in
                  case (ty1, ty2)
                   of (Ty.T_Int, Ty.T_Int) => (AST.I_Range(x', e1', e2'), (x, x'))
                    | _ => err(cxt, [
                          S "range expressions must have integer type\n",
                          S "  but found: ", TY ty1, S " .. ", TY ty2
                        ])
                  (* end case *)
                end
          fun chk ([], iters, bindings) =
                (List.rev iters, List.foldl (fn ((x, x'), env) => insertLocal(env, cxt, x, x')) env0 bindings)
            | chk (iter::rest, iters, bindings) = let
                val (iter, binding) = checkIter (env0, cxt, iter)
                in
                  chk (rest, iter::iters, binding::bindings)
                end
          in
            chk (iters, [], [])
          end

  (* check that an initializer expression is a compile-time constant and report an error, if not *)
    fun checkInitializer (cxt, e) = let
          fun isConstExp e = (case e
                 of AST.E_Var x => false
                  | AST.E_Lit _ => true
                  | AST.E_Tuple args => List.all isConstExp args
                  | AST.E_Apply(rator, _, args, _) =>
                      (Basis.allowedInConstExp rator) andalso (List.all isConstExp args)
                  | AST.E_Cons args => List.all isConstExp args
                  | AST.E_Seq(args, _) => List.all isConstExp args
                  | AST.E_Slice _ => false
                  | AST.E_Cond _ => false (* we disallow conditionals so that the inputInit CFG is simple *)
                  | AST.E_LoadNrrd _ => true
                  | AST.E_Coerce{e, ...} => isConstExp e
                (* end case *))
          in
            if isConstExp e
              then ()
              else err(cxt, [S "initializer is not a constant expression"])
          end

    fun checkDecl (env, cxt, d) = (case d
           of PT.D_Mark m => checkDecl (withEnvAndContext (env, cxt, m))
            | PT.D_Input(ty, x, desc, optExp) => let
(* FIXME: need to do something with the description *)
                val ty = checkTy(cxt, ty)
                val x' = Var.new(x, Var.InputVar, ty)
                val dcl = (case optExp
                       of NONE => AST.D_Input(x', desc, NONE)
                        | SOME e => let
                            val (e', ty') = checkExpr (env, cxt, e)
                            in
                              checkInitializer (cxt, e');
                              case coerceType (ty, ty', e')
                               of SOME e' => AST.D_Input(x', desc, SOME e')
                                | NONE => err(cxt, [
                                      S "definition of ", V x', S " has wrong type\n",
                                      S "  expected:  ", TY ty, S "\n",
                                      S "  but found: ", TY ty'
                                    ])
                              (* end case *)
                            end
                      (* end case *))
                in
                (* check that input variables have valid types *)
                  if not(TU.isValueType ty orelse TU.isImageType ty)
                    then err(cxt, [S "input variable ", V x', S " has invalid type ", TY ty])
                    else ();
                  checkForRedef (env, cxt, x);
                  Env.recordProp (#env env, StrandUtil.HasGlobals);
                  Env.recordProp (#env env, StrandUtil.HasInputs);
                  (dcl, insertGlobal(env, cxt, x, x'))
                end
            | PT.D_Var vd => let
                val (x, x', e') = checkVarDecl (env, cxt, Var.GlobalVar, vd)
                in
                  checkForRedef (env, cxt, x);
                  Env.recordProp (#env env, StrandUtil.HasGlobals);
                  (AST.D_Var(AST.VD_Decl(x', e')), insertGlobal(env, cxt, x, x'))
                end
            | PT.D_Func(ty, f, params, body) => let
                val ty' = checkTy(cxt, ty)
                val env' = functionScope (env, ty', f)
                val (params', env') = checkParams (env', cxt, params)
                val body' = (case body
                       of PT.FB_Expr e => let
                            val (e', ty) = checkExpr (env', cxt, e)
                            in
                              case coerceType(ty', ty, e')
                               of SOME e' => AST.S_Return e'
                                | NONE => err(cxt, [
                                      S "type of function body does not match return type\n",
                                      S "  expected: ", TY ty', S "\n",
                                      S "  but found: ", TY ty
                                    ])
                              (* end case *)
                            end
                        | PT.FB_Stmt s => #1(checkStmt(env', cxt, s))
                      (* end case *))
                val fnTy = Ty.T_Fun(List.map Var.monoTypeOf params', ty')
                val f' = Var.new (f, AST.FunVar, fnTy)
                in
(* QUESTION: should we check for redefinition of basis functions? *)
                  checkForRedef (env, cxt, f);
                  (AST.D_Func(f', params', body'), insertFunc(env, cxt, f, f'))
                end
            | PT.D_Strand arg => let
                val strand = checkStrand(strandScope env, cxt, arg)
                in
                  checkForRedef (env, cxt, #name arg);
                  (AST.D_Strand strand, insertStrand(env, cxt, strand))
                end
            | PT.D_InitialArray(create, iterators) => let
                val (iterators, env') = checkIters (initScope env, cxt, iterators)
                val create = checkCreate (env', cxt, create)
                in
                  if StrandUtil.hasProp StrandUtil.StrandsMayDie (Env.properties (#env env))
                    then err(cxt, [
                        S "initial strand grid conflicts with use of \"die\", use collection instead"
                      ])
                  else if StrandUtil.hasProp StrandUtil.NewStrands (Env.properties (#env env))
                    then err(cxt, [
                        S "initial strand grid conflicts with use of \"new\", use collection instead"
                      ])
                    else ();
                  Env.recordProp (#env env, StrandUtil.StrandArray);
                  (AST.D_InitialArray(create, iterators), env)
                end
            | PT.D_InitialCollection(create, iterators) => let
                val (iterators, env') = checkIters (initScope env, cxt, iterators)
                val create = checkCreate (env', cxt, create)
                in
                  (AST.D_InitialCollection(create, iterators), env)
                end
          (* end case *))

  (* check AST for unused variables.  Also check to make sure that there is a strand
   * definition and exactly one initially clause.
   *)
    fun checkForUnused (cxt, dcls) = let
          val hasStrand = ref false
          val hasInitially = ref false
          fun check dcl = let
                fun chkVar x = if not(isUsed x) andalso (Var.kindOf x <> AST.StrandOutputVar)
                      then warn (cxt, [
                          S(Var.kindToString x), S " ", V x, S " declared at ",
                          S(Error.locToString(getLoc x)), S " is unused"
                        ])
                      else ()
                fun chkVDcl (AST.VD_Decl(x, _)) = chkVar x
                fun chkStm stm = (case stm
                       of AST.S_Block stms => List.app chkStm stms
                        | AST.S_Decl vd => chkVDcl vd
                        | AST.S_IfThenElse(_, s1, s2) => (chkStm s1; chkStm s2)
                        | _ => ()
                      (* end case *))
                in
                  case dcl
                   of AST.D_Input(x, _, _) => chkVar x
                    | AST.D_Var vd => chkVDcl vd
                    | AST.D_Func(f, params, body) => (
                        chkVar f;
                        List.app chkVar params;
                        chkStm body)
                    | AST.D_Strand(AST.Strand{state, methods, ...}) => let
                        fun chkMeth (AST.M_Method(_, body)) = chkStm body
                        in
                          hasStrand := true;
                          List.app chkVDcl state;
                          List.app chkMeth methods
                        end
                    | AST.D_InitialArray _ => (
                        if !hasInitially then err(cxt, [S "multiple initially clauses in program"]) else ();
                        hasInitially := true)
                    | AST.D_InitialCollection _ => (
                        if !hasInitially then err(cxt, [S "multiple initially clauses in program"]) else ();
                        hasInitially := true)
                  (* end case *)
                end
          in
            List.app check dcls;
            if not(! hasStrand)
              then err (cxt, [S "program does not have any strands"])
              else ();
            if not(! hasInitially)
              then err (cxt, [S "program does not have an initially clause"])
              else ()
          end

  (* reorder the declarations so that the input variables come first *)
    fun reorderDecls dcls = let
          fun isInput (AST.D_Input _) = true
            | isInput _ = false
          val (inputs, others) = List.partition isInput dcls
          in
            inputs @ others
          end

    fun check errStrm (PT.Program{span, tree}) = let
          val cxt = (errStrm, span)
          fun chk (env, [], dcls') = reorderDecls(List.rev dcls')
            | chk (env, dcl::dcls, dcls') = let
                val (dcl', env) = checkDecl (env, cxt, dcl)
                in
                  chk (env, dcls, dcl'::dcls')
                end
          val env = Basis.env()
          val dcls' = chk ({scope=GlobalScope, bindings=AtomMap.empty, env=env}, tree, [])
                handle TypeError => []
          in
            checkForUnused (cxt, dcls') handle TypeError => ();
            AST.Program{
                props = Env.properties env,
                decls = dcls'
              }
          end

  end

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