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

SCM Repository

[diderot] View of /branches/pure-cfg/src/compiler/typechecker/typechecker.sml
ViewVC logotype

View of /branches/pure-cfg/src/compiler/typechecker/typechecker.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 895 - (download) (annotate)
Wed Apr 20 17:20:44 2011 UTC (8 years, 2 months ago) by jhr
File size: 23556 byte(s)
  Added check for variable redefinition in the same scope
(* typechecker.sml
 *
 * COPYRIGHT (c) 2010 The Diderot Project (http://diderot-language.cs.uchicago.edu)
 * All rights reserved.
 *
 * TODO:
 *	check that variables are not redefined in the same scope
 *	int --> real type promotion
 *	sequence operations
 *)

structure Typechecker : sig

    exception Error

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

  end = struct

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

  (* standard method names *)
    val stabilizeAtom = Atom.atom "stabilize"
    val updateAtom = Atom.atom "update"

    datatype scope = GlobalScope | 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 *)
    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 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')
	  }

    exception Error

    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 Error)

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

    fun err (cxt, toks) = let
	  fun tok2str (S s) = s
	    | tok2str (A a) = Atom.toString a
	    | tok2str (V x) = Var.nameOf x
	    | tok2str (TY ty) = TU.toString ty
	    | tok2str (TYS []) = "()"
	    | tok2str (TYS[ty]) = TU.toString ty
	    | tok2str (TYS tys) = String.concat[
		  "(", String.concatWith " * " (List.map TU.toString 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 muse 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 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) => Ty.T_Sequence(checkTy(cxt, ty), checkDim (cxt, dim))
	  (* 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 *))

  (* 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
	  fun tryCandidates [] = err(cxt, [
		  S "unable to resolve overloaded operator \"", A rator, S "\"\n",
		  S "  argument type is: ", TYS argTys, S "\n"
		])
	    | tryCandidates (x::xs) = let
		val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf x)
		in
		  if U.tryMatchTypes(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.matchType(ty1, ty2)
			  then (AST.E_Cond(cond', e1', e2', ty1), ty1)
			  else err (cxt, [
			      S "type 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 BasisVars.op_inner)
			    val resTy = Ty.T_Tensor(Ty.Shape(dd1@dd2))
			    in
			      if U.matchDim(d1, d2)
			      andalso U.matchTypes(domTy, [ty1, ty2])
			      andalso U.matchType(rngTy, resTy)
				then (AST.E_Apply(BasisVars.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 (case Env.findFunc (#env env, rator)
		       of [rator] => let
			    val (tyArgs, Ty.T_Fun(domTy, rngTy)) = Util.instantiate(Var.typeOf rator)
			    in
			      if U.matchTypes(domTy, [ty1, ty2])
				then (AST.E_Apply(rator, tyArgs, [e1', e2'], rngTy), rngTy)
				else 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
			| ovldList => resolveOverload (cxt, rator, [ty1, ty2], [e1', e2'], ovldList)
		      (* end case *))
		end
	    | PT.E_UnaryOp(rator, e) => let
		val (e', ty) = checkExpr(env, cxt, e)
		in
 		  case Env.findFunc (#env env, rator)
		   of [rator] => let
			val (tyArgs, Ty.T_Fun([domTy], rngTy)) = U.instantiate(Var.typeOf rator)
			in
			  if U.matchType(domTy, ty)
			    then (AST.E_Apply(rator, tyArgs, [e'], rngTy), rngTy)
			    else err (cxt, [
				S "type error for unary operator \"", V rator, S "\"\n",
				S "  expected:  ", TY domTy, S "\n",
				S "  but found: ", TY ty
			      ])
			end
		    | ovldList => resolveOverload (cxt, rator, [ty], [e'], ovldList)
		  (* 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.matchType(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.matchType(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)
		in
		  raise Fail "E_Subscript not yet implemented" (* FIXME *)
		end
	    | PT.E_Apply(f, args) => let
		val (args, tys) = checkExprList (env, cxt, args)
		in
		  case Env.findFunc (#env env, f)
		   of [] => err(cxt, [S "unknown function ", A f])
		    | [f] =>
			if (inStrand env) andalso (Basis.isRestricted f)
			  then err(cxt, [S "use of restricted operation ", V f, S " in strand body"])
			  else (case Util.instantiate(Var.typeOf f)
			     of (tyArgs, Ty.T_Fun(domTy, rngTy)) =>
				  if U.matchTypes(domTy, tys)
				    then (AST.E_Apply(f, tyArgs, args, rngTy), rngTy)
				    else err(cxt, [
					S "type error in application of ", V f, S "\n",
					S "  expected:  ", TYS domTy, S "\n",
					S "  but found: ", TYS tys
				      ])
			      | _ => err(cxt, [S "application of non-function ", V f])
			    (* end case *))
		    | ovldList => resolveOverload (cxt, f, tys, args, ovldList)
		  (* 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, tys) = checkExprList (env, cxt, args)
		in
		  raise Fail "E_Sequence not yet implemented" (* FIXME *)
		end
	    | PT.E_Cons args => let
		val (args, ty::tys) = checkExprList (env, cxt, args)
		in
		  case 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 *)
			fun chkTy ty' = U.matchType(ty, ty')
			val resTy = Ty.T_Tensor(Ty.Shape(Ty.DimConst(List.length args) :: dd))
			in
			  if List.all chkTy tys
			    then (AST.E_Cons args, resTy)
			    else err(cxt, [S "arguments of tensor construction must have same type"])
			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(BasisVars.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(BasisVars.identity))
		in
		  if U.matchType(Ty.T_Tensor(checkShape(cxt, [d,d])), rngTy)
		    then (AST.E_Apply(BasisVars.identity, tyArgs, [], rngTy), rngTy)
		    else raise Fail "impossible"
		end
	    | PT.E_Zero dd => let
		val (tyArgs, Ty.T_Fun(_, rngTy)) =
		      Util.instantiate(Var.typeOf(BasisVars.zero))
		in
		  if U.matchType(Ty.T_Tensor(checkShape(cxt, dd)), rngTy)
		    then (AST.E_Apply(BasisVars.zero, tyArgs, [], rngTy), rngTy)
		    else raise Fail "impossible"
		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
(* FIXME: this check is not flexible enough; should allow lhs type to support
 * fewer levels of differentiation than rhs provides.
 *)
		  if U.matchType(ty, ty')
		    then (x, x', e')
		    else 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
	  (* 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)
		      in
			if U.matchType(ty, ty')
			  then (x, x', e')
			  else 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'
			    ]);
		      (* 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_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))
	  (* 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
			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
(* FIXME: need to check for multiple occurences of the same parameter name! *)
	    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 set of methods defined by the user *)
	  val methodNames = List.foldl
		(fn (AST.M_Method(name, _), names) => AtomSet.add(names, name))
		  AtomSet.empty
		    methods
	(* if the stabilize method is not provided, add one *)
	  val methods = if AtomSet.member(methodNames, stabilizeAtom)
		then methods
		else methods @ [AST.M_Method(stabilizeAtom, AST.S_Block[])]
	  in
	    if not(AtomSet.member(methodNames, updateAtom))
	      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, optExp) => let
		val ty = checkTy(cxt, ty)
		val x' = Var.new(x, Var.InputVar, ty)
		val dcl = (case optExp
		       of NONE => AST.D_Input(x', NONE)
			| SOME e => let
			    val (e', ty') = checkExpr (env, cxt, e)
			    in
			      if U.matchType (ty, ty')
				then AST.D_Input(x', SOME e')
				else err(cxt, [
				    S "definition of ", V x', S " has wrong type\n",
				    S "  expected:  ", TY ty, S "\n",
				    S "  but found: ", TY ty'
				  ])
			    end
		      (* end case *))
		in
		(* check that input variables have value types *)
		  if not(TU.isValueType ty)
		    then err(cxt, [S "input variable ", V x', S " has non-value 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_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 *))

    fun check errStrm (PT.Program{span, tree}) = let
	  val cxt = (errStrm, span)
	  fun chk (env, [], dcls') = AST.Program(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

  end

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