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 2149 - (download) (annotate)
Sun Feb 17 18:22:12 2013 UTC (6 years, 6 months ago) by jhr
File size: 33708 byte(s)
  Fixed it so that type errors are no longer reported as uncaught exceptions.  Note that we
  still only handle one error at a time.
(* typechecker.sml
 *
 * COPYRIGHT (c) 2013 The Diderot Project (http://diderot-language.cs.uchicago.edu)
 * All rights reserved.
 *
 * TODO:
 *	check for unreachable code and prune it (see simplify/simplify.sml)
 *	error recovery so that we can detect multiple errors in a single compile
 *	check that functions have a return on all paths
 *	check that strands have at least one output variable.
 *)

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

    datatype scope
      = GlobalScope
      | FunctionScope of Ty.ty
      | StrandScope
      | MethodScope
      | InitScope

    type env = {
	scope : scope,
	bindings : Error.location AtomMap.map,
	env : Env.env
      }

    type context = Error.err_stream * Error.span

  (* start a new scope *)
(* QUESTION: do we want to restrict access to globals from a function? *)
    fun functionScope ({scope, bindings, env}, ty) =
	  {scope=FunctionScope ty, bindings=AtomMap.empty, env=env}
    fun strandScope {scope, bindings, env} =
	  {scope=StrandScope, bindings=AtomMap.empty, env=env}
    fun methodScope {scope, bindings, env} =
	  {scope=MethodScope, 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 insertFunc ({scope, bindings, env}, cxt, f, f') = {
	    scope=scope,
	    bindings = AtomMap.insert(bindings, f, Error.location cxt),
	    env=Env.insertFunc(env, f, Env.UserFun f')
	  }
    fun insertLocal ({scope, bindings, env}, cxt, x, x') = {
	    scope=scope,
	    bindings = AtomMap.insert(bindings, x, Error.location cxt),
	    env=Env.insertLocal(env, x, x')
	  }
    fun insertGlobal ({scope, bindings, env}, cxt, x, x') = {
	    scope=scope,
	    bindings = AtomMap.insert(bindings, x, Error.location cxt),
	    env=Env.insertGlobal(env, x, x')
	  }

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

    fun error ((errStrm, span), msg) = (
	  Error.errorAt(errStrm, span, msg);
	  raise TypeError)

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

    fun tysToString tys = String.concat[
	    "(", String.concatWith " * " (List.map TU.toString tys), ")"
	  ]

    fun err (cxt, toks) = let
	  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
	    error(cxt, List.map tok2str toks)
	  end

    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
	    | 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' => (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_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' => 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' => 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 => let
		val (args, ty::tys) = checkExprList (env, cxt, args)
		in
                  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)
                          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
	    | 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_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 *))

  (* typecheck a statement and translate it to AST *)
    fun checkStmt (env, cxt, s) = (case s
	   of PT.S_Mark m => checkStmt (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') = checkStmt (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', _) = checkStmt (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', _) = checkStmt (env, cxt, s1)
		val (s2', _) = checkStmt (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_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 => ()
			  | Var.LocalVar => ()
			  | _ => err(cxt, [
				S "assignment to immutable variable ", A x
			      ])
			(* 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
			(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
		val argsAndTys' = List.map (fn e => checkExpr(env, cxt, e)) args
		val (args', tys') = ListPair.unzip argsAndTys'
		in
		  case #scope env
		   of MethodScope => ()
		    | InitScope => ()
		    | _ => err(cxt, [S "invalid scope for new strand"])
		  (* end case *);
(* FIXME: check that strand is defined and has the argument types match *)
		  (AST.S_New(strand, args'), env)
		end
	    | PT.S_Die => (
		case #scope env
		 of MethodScope => ()
		  | _ => err(cxt, [S "\"die\" statment outside of method"])
		(* end case *);
		(AST.S_Die, env))
	    | PT.S_Stabilize => (
		case #scope env
		 of MethodScope => ()
		  | _ => err(cxt, [S "\"stabilize\" statment outside of method"])
		(* end case *);
		(AST.S_Stabilize, env))
	    | PT.S_Return e => let
		val (e', ty) = checkExpr (env, cxt, e)
		in
		  case #scope env
		   of FunctionScope ty' => (case coerceType(ty', ty, e')
			 of SOME e' => (AST.S_Return e', env)
			  | NONE => err(cxt, [
				S "type of return expression does not match function's return type\n",
				S "  expected: ", TY ty', S "\n",
				S "  but found: ", TY ty
			      ])
			(* end case *))
		    | _ => err(cxt, [S "\"return\" statment outside of function"])
		  (* 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 *))

    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
(* FIXME: should use an empty bindings list for the parameters *)
			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, 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 (env, cxt, params)
	(* check the strand state variable definitions *)
	  val (vds, env) = let
		fun checkStateVar ((isOut, vd), (vds, env)) = let
		      val kind = if isOut then AST.StrandOutputVar else AST.StrandStateVar
		      val (x, x', e') = checkVarDecl (env, cxt, kind, vd)
		      in
		      (* check that output variables have value types *)
			if isOut andalso not(TU.isValueType(Var.monoTypeOf x'))
			  then err(cxt, [
			      S "output variable ", V x', S " has non-value type ",
			      TY(Var.monoTypeOf x')
			    ])
			  else ();
			checkForRedef (env, cxt, x);
			(AST.VD_Decl(x', e')::vds, insertLocal(env, cxt, x, x'))
		      end
		val (vds, env) = List.foldl checkStateVar ([], env) state
		in
		  (List.rev vds, env)
		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, add one *)
          val methods = if List.exists (fn StrandUtil.Stabilize => true | _ => false) methodNames
		then methods
		else methods @ [AST.M_Method(StrandUtil.Stabilize, AST.S_Block[])]
	  in
(* 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.D_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 (args, tys) = checkExprList (env, cxt, args)
	  in
(* FIXME: check against strand definition *)
	    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

    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
			      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);
		  (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);
		  (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 (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
(* FIXME: we need to check that there is a return on all control-flow paths *)
			| PT.FB_Stmt s => #1(checkStmt(functionScope (env', ty'), 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 the f? *)
		  (AST.D_Func(f', params', body'), insertFunc(env, cxt, f, f'))
		end
	    | PT.D_Strand arg => (checkStrand(strandScope env, cxt, arg), env)
	    | PT.D_InitialArray(create, iterators) => let
		val env = initScope env
		val (iterators, env') = checkIters (env, cxt, iterators)
		val create = checkCreate (env', cxt, create)
		in
		  (AST.D_InitialArray(create, iterators), env)
		end
	    | PT.D_InitialCollection(create, iterators) => let
		val env = initScope env
		val (iterators, env') = checkIters (env, cxt, iterators)
		val create = checkCreate (env', cxt, create)
		in
		  (AST.D_InitialCollection(create, iterators), env)
		end
	  (* end case *))

  (* 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') = AST.Program(reorderDecls(List.rev dcls'))
	    | chk (env, dcl::dcls, dcls') = let
		val (dcl', env) = checkDecl (env, cxt, dcl)
		in
		  chk (env, dcls, dcl'::dcls')
		end
	  in
	    chk ({scope=GlobalScope, bindings=AtomMap.empty, env=Basis.env}, tree, [])
	  end
	    handle TypeError => AST.Program[]

  end

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