TcUnify.lhs 61.3 KB
Newer Older
1 2 3 4 5 6 7 8
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section{Type subsumption and unification}

\begin{code}
module TcUnify (
	-- Full-blown subsumption
9
  tcSubExp, tcFunResTy, tcGen, 
10
  checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt, 
11 12

	-- Various unifications
13
  unifyType, unifyTypeList, unifyTheta,
14
  unifyKind, unifyKinds, unifyFunKind, 
15 16
  checkExpectedKind, 
  boxySubMatchType, boxyMatchTypes,
17 18 19

  --------------------------------
  -- Holes
20 21 22 23
  tcInfer, subFunTys, unBox, stripBoxyType, withBox, 
  boxyUnify, boxyUnifyList, zapToMonotype,
  boxySplitListTy, boxySplitTyConApp, boxySplitAppTy,
  wrapFunResCoercion
24 25 26 27
  ) where

#include "HsVersions.h"

28
import HsSyn		( ExprCoFn(..), idCoercion, isIdCoercion, (<.>) )
29
import TypeRep		( Type(..), PredType(..) )
30

31 32
import TcMType		( lookupTcTyVar, LookupTyVarResult(..),
                          tcInstSkolType, newKindVar, newMetaTyVar,
33
			  tcInstBoxy, newBoxyTyVar, newBoxyTyVarTys, readFilledBox, 
34
			  readMetaTyVar, writeMetaTyVar, newFlexiTyVarTy,
35
			  tcInstSkolTyVars, tcInstTyVar,
36 37 38 39 40
			  zonkTcKind, zonkType, zonkTcType,  zonkTcTyVarsAndFV, 
			  readKindVar, writeKindVar )
import TcSimplify	( tcSimplifyCheck )
import TcEnv		( tcGetGlobalTyVars, findGlobals )
import TcIface		( checkWiredInTyCon )
41
import TcRnMonad         -- TcType, amongst others
42
import TcType		( TcKind, TcType, TcTyVar, BoxyTyVar, TcTauType,
43 44 45 46 47
			  BoxySigmaType, BoxyRhoType, BoxyType, 
			  TcTyVarSet, TcThetaType, TcTyVarDetails(..), BoxInfo(..), 
			  SkolemInfo( GenSkol, UnkSkol ), MetaDetails(..), isImmutableTyVar,
			  pprSkolTvBinding, isTauTy, isTauTyCon, isSigmaTy, 
			  mkFunTy, mkFunTys, mkTyConApp, isMetaTyVar,
48
			  tcSplitForAllTys, tcSplitAppTy_maybe, tcSplitFunTys, mkTyVarTys,
49 50
			  tyVarsOfType, mkPhiTy, mkTyVarTy, mkPredTy, 
			  typeKind, mkForAllTys, mkAppTy, isBoxyTyVar,
51
			  tidyOpenType, tidyOpenTyVar, tidyOpenTyVars,
52 53 54
			  pprType, tidyKind, tidySkolemTyVar, isSkolemTyVar, tcView, 
			  TvSubst, mkTvSubst, zipTyEnv, substTy, emptyTvSubst, 
			  lookupTyVar, extendTvSubst )
55
import Kind		( Kind(..), SimpleKind, KindVar, isArgTypeKind,
56
			  openTypeKind, liftedTypeKind, mkArrowKind, defaultKind,
57 58
			  isOpenTypeKind, argTypeKind, isLiftedTypeKind, isUnliftedTypeKind,
			  isSubKind, pprKind, splitKindFunTys )
59 60 61
import TysPrim		( alphaTy, betaTy )
import Inst		( newDicts, instToId )
import TyCon		( TyCon, tyConArity, tyConTyVars, isSynTyCon )
62
import TysWiredIn	( listTyCon )
63
import Id		( Id, mkSysLocal )
64 65 66
import Var		( Var, varName, tyVarKind, isTcTyVar, tcTyVarDetails )
import VarSet		( emptyVarSet, mkVarSet, unitVarSet, unionVarSet, elemVarSet, varSetElems,
			  extendVarSet, intersectsVarSet )
67
import VarEnv
68
import Name		( Name, isSystemName )
69
import ErrUtils		( Message )
70
import Maybes		( expectJust, isNothing )
71
import BasicTypes	( Arity )
72
import UniqSupply	( uniqsFromSupply )
73
import Util		( notNull, equalLength )
74 75
import Outputable

76 77 78 79 80
-- Assertion imports
#ifdef DEBUG
import TcType		( isBoxyTy, isFlexi )
#endif
\end{code}
81

82 83 84 85 86 87 88
%************************************************************************
%*									*
\subsection{'hole' type variables}
%*									*
%************************************************************************

\begin{code}
89
tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
90
tcInfer tc_infer
91
  = do	{ box <- newBoxyTyVar openTypeKind
92 93
	; res <- tc_infer (mkTyVarTy box)
	; res_ty <- readFilledBox box	-- Guaranteed filled-in by now
94
	; return (res, res_ty) }
95 96 97 98 99
\end{code}		   


%************************************************************************
%*									*
100
	subFunTys
101 102 103 104
%*									*
%************************************************************************

\begin{code}
105 106 107 108 109 110 111 112 113 114 115 116
subFunTys :: SDoc  -- Somthing like "The function f has 3 arguments"
		   -- or "The abstraction (\x.e) takes 1 argument"
	  -> Arity		-- Expected # of args
	  -> BoxyRhoType	-- res_ty
	  -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
	  -> TcM (ExprCoFn, a)
-- Attempt to decompse res_ty to have enough top-level arrows to
-- match the number of patterns in the match group
-- 
-- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
-- and the inner call to thing_inside passes args: [a1,...,an], b
-- then co_fn :: (a1 -> ... -> an -> b) -> res_ty
117
--
118
-- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
119

120 121

{-	Error messages from subFunTys
122 123 124 125 126 127 128 129 130 131 132 133 134 135

   The abstraction `\Just 1 -> ...' has two arguments
   but its type `Maybe a -> a' has only one

   The equation(s) for `f' have two arguments
   but its type `Maybe a -> a' has only one

   The section `(f 3)' requires 'f' to take two arguments
   but its type `Int -> Int' has only one

   The function 'f' is applied to two arguments
   but its type `Int -> Int' has only one
-}

136 137 138

subFunTys error_herald n_pats res_ty thing_inside
  = loop n_pats [] res_ty
139
  where
140 141 142 143 144 145
	-- In 'loop', the parameter 'arg_tys' accumulates 
	-- the arg types so far, in *reverse order*
    loop n args_so_far res_ty
	| Just res_ty' <- tcView res_ty  = loop n args_so_far res_ty'

    loop n args_so_far res_ty
146 147
	| isSigmaTy res_ty 	-- Do this before checking n==0, because we 
				-- guarantee to return a BoxyRhoType, not a BoxySigmaType
148 149 150 151
	= do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ res_ty' ->
					 loop n args_so_far res_ty'
	     ; return (gen_fn <.> co_fn, res) }

152 153 154 155
    loop 0 args_so_far res_ty 
	= do { res <- thing_inside (reverse args_so_far) res_ty
	     ; return (idCoercion, res) }

156 157 158 159 160
    loop n args_so_far (FunTy arg_ty res_ty) 
	= do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
	     ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
	     ; return (co_fn', res) }

161 162 163 164 165 166 167 168 169 170
	-- res_ty might have a type variable at the head, such as (a b c),
	-- in which case we must fill in with (->).  Simplest thing to do
	-- is to use boxyUnify, but we catch failure and generate our own
	-- error message on failure
    loop n args_so_far res_ty@(AppTy _ _)
	= do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
	     ; (_, mb_unit) <- tryTcErrs $ boxyUnify res_ty (FunTy arg_ty' res_ty')
	     ; if isNothing mb_unit then bale_out args_so_far res_ty
	       else loop n args_so_far (FunTy arg_ty' res_ty') }

171 172 173 174 175 176 177 178 179 180 181 182 183 184
    loop n args_so_far (TyVarTy tv)
        | not (isImmutableTyVar tv)
	= do { cts <- readMetaTyVar tv 
	     ; case cts of
		 Indirect ty -> loop n args_so_far ty
		 Flexi -> do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
			     ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty
			     ; return (idCoercion, res) } }
	where
	  mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
	  kinds = openTypeKind : take n (repeat argTypeKind)
		-- Note argTypeKind: the args can have an unboxed type,
		-- but not an unboxed tuple.

185 186 187 188 189 190 191
    loop n args_so_far res_ty = bale_out args_so_far res_ty

    bale_out args_so_far res_ty
	= do { env0 <- tcInitTidyEnv
	     ; res_ty' <- zonkTcType res_ty
	     ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
	     ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
192

193
    mk_msg res_ty n_actual 
194
      = error_herald <> comma $$ 
195
	sep [ptext SLIT("but its type") <+> quotes (pprType res_ty), 
196 197
	     if n_actual == 0 then ptext SLIT("has none") 
	     else ptext SLIT("has only") <+> speakN n_actual]
198 199 200
\end{code}

\begin{code}
201
----------------------
202 203 204
boxySplitTyConApp :: TyCon			-- T :: k1 -> ... -> kn -> *
	          -> BoxyRhoType 		-- Expected type (T a b c)
		  -> TcM [BoxySigmaType]	-- Element types, a b c
205
  -- It's used for wired-in tycons, so we call checkWiredInTyCOn
206
  -- Precondition: never called with FunTyCon
207
  -- Precondition: input type :: *
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
boxySplitTyConApp tc orig_ty
  = do	{ checkWiredInTyCon tc 
	; loop (tyConArity tc) [] orig_ty }
  where
    loop n_req args_so_far ty 
      | Just ty' <- tcView ty = loop n_req args_so_far ty'

    loop n_req args_so_far (TyConApp tycon args)
      | tc == tycon
      = ASSERT( n_req == length args) 	-- ty::*
	return (args ++ args_so_far)

    loop n_req args_so_far (AppTy fun arg)
      = loop (n_req - 1) (arg:args_so_far) fun

    loop n_req args_so_far (TyVarTy tv)
      | not (isImmutableTyVar tv)
      = do { cts <- readMetaTyVar tv
	   ; case cts of
	       Indirect ty -> loop n_req args_so_far ty
	       Flexi 	   -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
				 ; return (arg_tys ++ args_so_far) }
231
	}
232 233 234
      where
	mk_res_ty arg_tys' = mkTyConApp tc arg_tys'
	arg_kinds = map tyVarKind (take n_req (tyConTyVars tc))
235

236
    loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc))) orig_ty
237

238 239 240 241
----------------------
boxySplitListTy :: BoxyRhoType -> TcM BoxySigmaType	-- Special case for lists
boxySplitListTy exp_ty = do { [elt_ty] <- boxySplitTyConApp listTyCon exp_ty
			    ; return elt_ty }
242

243

244
----------------------
245 246 247 248
boxySplitAppTy :: BoxyRhoType				-- Type to split: m a
	       -> TcM (BoxySigmaType, BoxySigmaType)	-- Returns m, a
-- Assumes (m: * -> k), where k is the kind of the incoming type
-- If the incoming type is boxy, then so are the result types; and vice versa
249

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
boxySplitAppTy orig_ty
  = loop orig_ty
  where
    loop ty 
      | Just ty' <- tcView ty = loop ty'

    loop ty 
      | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
      = return (fun_ty, arg_ty)

    loop (TyVarTy tv)
      | not (isImmutableTyVar tv)
      = do { cts <- readMetaTyVar tv
	   ; case cts of
	       Indirect ty -> loop ty
	       Flexi       -> do { [fun_ty,arg_ty] <- withMetaTvs tv kinds mk_res_ty
				 ; return (fun_ty, arg_ty) } }
      where
        mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
	tv_kind = tyVarKind tv
	kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
					 	-- m :: * -> k
		 liftedTypeKind]		-- arg type :: *
	-- The defaultKind is a bit smelly.  If you remove it,
	-- try compiling	f x = do { x }
	-- and you'll get a kind mis-match.  It smells, but
	-- not enough to lose sleep over.
	
    loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
279

280 281
------------------
boxySplitFailure actual_ty expected_ty
282 283 284
  = unifyMisMatch False False actual_ty expected_ty
	-- "outer" is False, so we don't pop the context
	-- which is what we want since we have not pushed one!
285
\end{code}
286 287


288 289 290
--------------------------------
-- withBoxes: the key utility function
--------------------------------
291

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
\begin{code}
withMetaTvs :: TcTyVar	-- An unfilled-in, non-skolem, meta type variable
	    -> [Kind] 	-- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
	    -> ([BoxySigmaType] -> BoxySigmaType)
					-- Constructs the type to assign 
					-- to the original var
	    -> TcM [BoxySigmaType]  	-- Return the fresh boxes

-- It's entirely possible for the [kind] to be empty.  
-- For example, when pattern-matching on True, 
-- we call boxySplitTyConApp passing a boolTyCon

-- Invariant: tv is still Flexi

withMetaTvs tv kinds mk_res_ty
  | isBoxyTyVar tv
  = do	{ box_tvs <- mapM (newMetaTyVar BoxTv) kinds
	; let box_tys = mkTyVarTys box_tvs
	; writeMetaTyVar tv (mk_res_ty box_tys)
	; return box_tys }

  | otherwise			-- Non-boxy meta type variable
  = do	{ tau_tys <- mapM newFlexiTyVarTy kinds
	; writeMetaTyVar tv (mk_res_ty tau_tys)	-- Write it *first*
						-- Sure to be a tau-type
	; return tau_tys }

withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
-- Allocate a *boxy* tyvar
withBox kind thing_inside
  = do	{ box_tv <- newMetaTyVar BoxTv kind
	; res <- thing_inside (mkTyVarTy box_tv)
	; ty  <- readFilledBox box_tv
  	; return (res, ty) }
\end{code}
327 328


329 330 331 332 333
%************************************************************************
%*									*
		Approximate boxy matching
%*									*
%************************************************************************
334

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
\begin{code}
boxySubMatchType 
	:: TcTyVarSet -> TcType	-- The "template"; the tyvars are skolems
	-> BoxyRhoType		-- Type to match (note a *Rho* type)
	-> TvSubst 		-- Substitution of the [TcTyVar] to BoxySigmaTypes

boxyMatchTypes 
	:: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
	-> [BoxySigmaType]	  -- Type to match
	-> TvSubst 		  -- Substitution of the [TcTyVar] to BoxySigmaTypes

-- Find a *boxy* substitution that makes the template look as much 
-- 	like the BoxySigmaType as possible.  
-- It's always ok to return an empty substitution; 
--	anything more is jam on the pudding
-- 
-- NB1: This is a pure, non-monadic function.  
--	It does no unification, and cannot fail
--
-- Note [Matching kinds]
-- 	The target type might legitimately not be a sub-kind of template.  
--	For example, suppose the target is simply a box with an OpenTypeKind, 
--	and the template is a type variable with LiftedTypeKind.  
--	Then it's ok (because the target type will later be refined).
--	We simply don't bind the template type variable.
--
--	It might also be that the kind mis-match is an error. For example,
--	suppose we match the template (a -> Int) against (Int# -> Int),
--	where the template type variable 'a' has LiftedTypeKind.  This
--	matching function does not fail; it simply doesn't bind the template.
--	Later stuff will fail.
-- 
-- Precondition: the arg lengths are equal
-- Precondition: none of the template type variables appear in the [BoxySigmaType]
-- Precondition: any nested quantifiers in either type differ from 
-- 		 the template type variables passed as arguments
--
-- Note [Sub-match]
-- ~~~~~~~~~~~~~~~~
-- Consider this
-- 	head :: [a] -> a
-- 	|- head xs : <rhobox>
-- We will do a boxySubMatchType between 	a ~ <rhobox>
-- But we *don't* want to match [a |-> <rhobox>] because 
--     (a)	The box should be filled in with a rho-type, but
-- 	but the returned substitution maps TyVars to boxy *sigma*
-- 	types
--     (b) In any case, the right final answer might be *either*
-- 	instantiate 'a' with a rho-type or a sigma type
-- 	   head xs : Int   vs   head xs : forall b. b->b
-- So the matcher MUST NOT make a choice here.   In general, we only
-- bind a template type variable in boxyMatchType, not in boxySubMatchType.
	
boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
  = go tmpl_ty boxy_ty
  where
    go t_ty b_ty 
	| Just t_ty' <- tcView t_ty = go t_ty' b_ty
	| Just b_ty' <- tcView b_ty = go t_ty b_ty'

    go (FunTy arg1 res1) (FunTy arg2 res2)
	= do_match arg1 arg2 (go res1 res2)
		-- Match the args, and sub-match the results

    go (TyVarTy _) b_ty = emptyTvSubst	-- Do not bind!  See Note [Sub-match]

    go t_ty b_ty = do_match t_ty b_ty emptyTvSubst	-- Otherwise we are safe to bind

    do_match t_ty b_ty subst = boxy_match tmpl_tvs t_ty emptyVarSet b_ty subst

------------
boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
  = ASSERT( length tmpl_tys == length boxy_tys )
    boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
	-- ToDo: add error context?

boxy_match_s tmpl_tvs [] boxy_tvs [] subst
  = subst
boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
  = boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys $
    boxy_match tmpl_tvs t_ty boxy_tvs b_ty subst

------------
boxy_match :: TcTyVarSet -> TcType	-- Template
	   -> TcTyVarSet 		-- boxy_tvs: do not bind template tyvars to any of these
	   -> BoxySigmaType		-- Match against this type
	   -> TvSubst
	   -> TvSubst

-- The boxy_tvs argument prevents this match:
--	[a]  forall b. a  ~  forall b. b
-- We don't want to bind the template variable 'a'
-- to the quantified type variable 'b'!

boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
  = go orig_tmpl_ty orig_boxy_ty
  where
    go t_ty b_ty 
	| Just t_ty' <- tcView t_ty = go t_ty' b_ty
	| Just b_ty' <- tcView b_ty = go t_ty b_ty'

    go (ForAllTy _ ty1) (ForAllTy tv2 ty2)
	= boxy_match tmpl_tvs ty1 (boxy_tvs `extendVarSet` tv2) ty2 subst

    go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
	| tc1 == tc2 = go_s tys1 tys2

    go (FunTy arg1 res1) (FunTy arg2 res2)
	= go_s [arg1,res1] [arg2,res2]

    go t_ty b_ty
	| Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
	  Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
	  typeKind t2 `isSubKind` typeKind t1	-- Maintain invariant
	= go_s [s1,t1] [s2,t2]

    go (TyVarTy tv) b_ty
 	| tv `elemVarSet` tmpl_tvs	-- Template type variable in the template
	, not (intersectsVarSet boxy_tvs (tyVarsOfType orig_boxy_ty))
	, typeKind b_ty `isSubKind` tyVarKind tv
	= extendTvSubst subst tv boxy_ty'
	where
	  boxy_ty' = case lookupTyVar subst tv of
			Nothing -> orig_boxy_ty
			Just ty -> ty `boxyLub` orig_boxy_ty

    go _ _ = subst	-- Always safe

    --------
    go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst


boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
-- Combine boxy information from the two types
-- If there is a conflict, return the first
boxyLub orig_ty1 orig_ty2
  = go orig_ty1 orig_ty2
  where
    go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
474
    go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
475 476 477 478 479 480 481 482 483 484 485 486 487 488
    go (TyConApp tc1 ts1) (TyConApp tc2 ts2) 
      | tc1 == tc2, length ts1 == length ts2
      = TyConApp tc1 (zipWith boxyLub ts1 ts2)

    go (TyVarTy tv1) ty2		-- This is the whole point; 
      | isTcTyVar tv1, isMetaTyVar tv1 	-- choose ty2 if ty2 is a box
      = ty2	

	-- Look inside type synonyms, but only if the naive version fails
    go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
	       | Just ty2' <- tcView ty1 = go ty1 ty2'

    -- For now, we don't look inside ForAlls, PredTys
    go ty1 ty2 = orig_ty1	-- Default
489 490 491
\end{code}


492 493
%************************************************************************
%*									*
494
		Subsumption checking
495 496 497
%*									*
%************************************************************************

498 499 500 501 502
All the tcSub calls have the form
	
		tcSub expected_ty offered_ty
which checks
		offered_ty <= expected_ty
503

504
That is, that a value of type offered_ty is acceptable in
505 506 507
a place expecting a value of type expected_ty.

It returns a coercion function 
508 509
	co_fn :: offered_ty -> expected_ty
which takes an HsExpr of type offered_ty into one of type
510 511 512
expected_ty.

\begin{code}
513
-----------------
514 515
tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM ExprCoFn	-- Locally used only
	-- (tcSub act exp) checks that 
516
	--	act <= exp
517
tcSubExp actual_ty expected_ty
518 519 520 521 522 523 524 525
  = addErrCtxtM (unifyCtxt actual_ty expected_ty)
		(tc_sub True actual_ty actual_ty expected_ty expected_ty)

tcFunResTy :: Name -> BoxySigmaType -> BoxySigmaType -> TcM ExprCoFn	-- Locally used only
tcFunResTy fun actual_ty expected_ty
  = addErrCtxtM (checkFunResCtxt fun actual_ty expected_ty) $
		(tc_sub True actual_ty actual_ty expected_ty expected_ty)
		   
526
-----------------
527 528
tc_sub :: Outer			-- See comments with uTys
       -> BoxySigmaType		-- actual_ty, before expanding synonyms
529 530 531
       -> BoxySigmaType		-- 		..and after
       -> BoxySigmaType		-- expected_ty, before
       -> BoxySigmaType		-- 		..and after
532
       -> TcM ExprCoFn
533

534 535 536 537
tc_sub outer act_sty act_ty exp_sty exp_ty
  | Just exp_ty' <- tcView exp_ty = tc_sub False act_sty act_ty exp_sty exp_ty'
tc_sub outer act_sty act_ty exp_sty exp_ty
  | Just act_ty' <- tcView act_ty = tc_sub False act_sty act_ty' exp_sty exp_ty
538

539
-----------------------------------
540 541 542
-- Rule SBOXY, plus other cases when act_ty is a type variable
-- Just defer to boxy matching
-- This rule takes precedence over SKOL!
543 544
tc_sub outer act_sty (TyVarTy tv) exp_sty exp_ty
  = do	{ uVar outer False tv False exp_sty exp_ty
545
	; return idCoercion }
546 547

-----------------------------------
548
-- Skolemisation case (rule SKOL)
549 550 551 552 553 554 555 556 557
-- 	actual_ty:   d:Eq b => b->b
--	expected_ty: forall a. Ord a => a->a
--	co_fn e      /\a. \d2:Ord a. let d = eqFromOrd d2 in e

-- It is essential to do this *before* the specialisation case
-- Example:  f :: (Eq a => a->a) -> ...
--	     g :: Ord b => b->b
-- Consider  f g !

558
tc_sub outer act_sty act_ty exp_sty exp_ty
559 560
  | isSigmaTy exp_ty
  = do	{ (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ body_exp_ty ->
561
			     tc_sub False act_sty act_ty body_exp_ty body_exp_ty
562 563 564 565 566
	; return (gen_fn <.> co_fn) }
  where
    act_tvs = tyVarsOfType act_ty
		-- It's really important to check for escape wrt the free vars of
		-- both expected_ty *and* actual_ty
567 568

-----------------------------------
569
-- Specialisation case (rule ASPEC):
570 571 572 573
--	actual_ty:   forall a. Ord a => a->a
--	expected_ty: Int -> Int
--	co_fn e =    e Int dOrdInt

574
tc_sub outer act_sty actual_ty exp_sty expected_ty
575
  | isSigmaTy actual_ty
576 577 578 579 580
  = do	{ (tyvars, theta, tau) <- tcInstBoxy actual_ty
	; dicts <- newDicts InstSigOrigin theta
	; extendLIEs dicts
	; let inst_fn = CoApps (CoTyApps CoHole (mkTyVarTys tyvars)) 
			       (map instToId dicts)
581
	; co_fn <- tc_sub False tau tau exp_sty expected_ty
582
	; return (co_fn <.> inst_fn) }
583 584

-----------------------------------
585
-- Function case (rule F1)
586
tc_sub _ _ (FunTy act_arg act_res) _ (FunTy exp_arg exp_res)
587 588 589
  = tc_sub_funs act_arg act_res exp_arg exp_res

-- Function case (rule F2)
590
tc_sub outer act_sty act_ty@(FunTy act_arg act_res) exp_sty (TyVarTy exp_tv)
591 592 593
  | isBoxyTyVar exp_tv
  = do	{ cts <- readMetaTyVar exp_tv
	; case cts of
594
	    Indirect ty -> do { u_tys outer False act_sty act_ty True exp_sty ty
595 596 597 598 599 600 601 602
			      ; return idCoercion }
	    Flexi       -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
 			      ; tc_sub_funs act_arg act_res arg_ty res_ty } }
 where
    mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
    fun_kinds = [argTypeKind, openTypeKind]

-- Everything else: defer to boxy matching
603 604
tc_sub outer act_sty actual_ty exp_sty expected_ty
  = do	{ u_tys outer False act_sty actual_ty False exp_sty expected_ty
605
	; return idCoercion }
606 607 608


-----------------------------------
609 610
tc_sub_funs act_arg act_res exp_arg exp_res
  = do	{ uTys False act_arg False exp_arg
611
	; co_fn_res <- tc_sub False act_res act_res exp_res exp_res
612
	; wrapFunResCoercion [exp_arg] co_fn_res }
613 614

-----------------------------------
615 616 617 618 619 620 621 622 623 624 625
wrapFunResCoercion 
	:: [TcType]	-- Type of args
	-> ExprCoFn 	-- HsExpr a -> HsExpr b
	-> TcM ExprCoFn	-- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
wrapFunResCoercion arg_tys co_fn_res
  | isIdCoercion co_fn_res = return idCoercion
  | null arg_tys	   = return co_fn_res
  | otherwise 	       
  = do	{ us <- newUniqueSupply
	; let arg_ids = zipWith (mkSysLocal FSLIT("sub")) (uniqsFromSupply us) arg_tys
	; return (CoLams arg_ids (co_fn_res <.> (CoApps CoHole arg_ids))) }
626 627 628
\end{code}


629

630 631 632 633 634 635 636
%************************************************************************
%*									*
\subsection{Generalisation}
%*									*
%************************************************************************

\begin{code}
637
tcGen :: BoxySigmaType				-- expected_ty
638 639 640
      -> TcTyVarSet				-- Extra tyvars that the universally
						--	quantified tyvars of expected_ty
						-- 	must not be unified
641
      -> (BoxyRhoType -> TcM result)		-- spec_ty
642
      -> TcM (ExprCoFn, result)
643 644
	-- The expression has type: spec_ty -> expected_ty

645 646
tcGen expected_ty extra_tvs thing_inside	-- We expect expected_ty to be a forall-type
						-- If not, the call is a no-op
647 648 649 650 651
  = do	{	-- We want the GenSkol info in the skolemised type variables to 
		-- mention the *instantiated* tyvar names, so that we get a
		-- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
		-- Hence the tiresome but innocuous fixM
	  ((forall_tvs, theta, rho_ty), skol_info) <- fixM (\ ~(_, skol_info) ->
652
		do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
653 654 655 656 657 658 659 660 661 662 663
		   ; span <- getSrcSpanM
		   ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty) span
		   ; return ((forall_tvs, theta, rho_ty), skol_info) })

#ifdef DEBUG
	; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
				    text "expected_ty" <+> ppr expected_ty,
				    text "inst ty" <+> ppr forall_tvs <+> ppr theta <+> ppr rho_ty,
				    text "free_tvs" <+> ppr free_tvs,
				    text "forall_tvs" <+> ppr forall_tvs])
#endif
664 665

	-- Type-check the arg and unify with poly type
666
	; (result, lie) <- getLIE (thing_inside rho_ty)
667 668 669 670 671 672 673 674 675 676 677 678

	-- Check that the "forall_tvs" havn't been constrained
	-- The interesting bit here is that we must include the free variables
	-- of the expected_ty.  Here's an example:
	--	 runST (newVar True)
	-- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
	-- for (newVar True), with s fresh.  Then we unify with the runST's arg type
	-- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
	-- So now s' isn't unconstrained because it's linked to a.
	-- Conclusion: include the free vars of the expected_ty in the
	-- list of "free vars" for the signature check.

679
	; dicts <- newDicts (SigOrigin skol_info) theta
680
	; inst_binds <- tcSimplifyCheck sig_msg forall_tvs dicts lie
681

682 683
	; checkSigTyVarsWrt free_tvs forall_tvs
	; traceTc (text "tcGen:done")
684

685
	; let
686 687 688
	    -- This HsLet binds any Insts which came out of the simplification.
	    -- It's a bit out of place here, but using AbsBind involves inventing
	    -- a couple of new names which seems worse.
689 690 691
		dict_ids   = map instToId dicts
		co_fn = CoTyLams forall_tvs $ CoLams dict_ids $ CoLet inst_binds CoHole 
	; returnM (co_fn, result) }
692
  where
693
    free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
694
    sig_msg  = ptext SLIT("expected type of an expression")
695 696 697 698 699 700
\end{code}    

    

%************************************************************************
%*									*
701
		Boxy unification
702 703 704 705 706 707 708
%*									*
%************************************************************************

The exported functions are all defined as versions of some
non-exported generic functions.

\begin{code}
709 710 711
boxyUnify :: BoxyType -> BoxyType -> TcM ()
-- Acutal and expected, respectively
boxyUnify ty1 ty2 
712 713
  = addErrCtxtM (unifyCtxt ty1 ty2) $
    uTysOuter False ty1 False ty2
714 715 716 717 718 719 720 721 722 723 724 725 726 727

---------------
boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM ()
-- Arguments should have equal length
-- Acutal and expected types
boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2

---------------
unifyType :: TcTauType -> TcTauType -> TcM ()
-- No boxes expected inside these types
-- Acutal and expected types
unifyType ty1 ty2 	-- ty1 expected, ty2 inferred
  = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
    ASSERT2( not (isBoxyTy ty2), ppr ty2 )
728 729
    addErrCtxtM (unifyCtxt ty1 ty2) $
    uTysOuter True ty1 True ty2
730 731 732 733

---------------
unifyPred :: PredType -> PredType -> TcM ()
-- Acutal and expected types
734 735
unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
		  uPred True True p1 True p2
736 737

unifyTheta :: TcThetaType -> TcThetaType -> TcM ()
738
-- Acutal and expected types
739
unifyTheta theta1 theta2
740 741 742 743 744 745 746 747 748 749 750 751 752
  = do	{ checkTc (equalLength theta1 theta2)
		  (ptext SLIT("Contexts differ in length"))
	; uList unifyPred theta1 theta2 }

---------------
uList :: (a -> a -> TcM ())
       -> [a] -> [a] -> TcM ()
-- Unify corresponding elements of two lists of types, which
-- should be f equal length.  We charge down the list explicitly so that
-- we can complain if their lengths differ.
uList unify []         []	  = return ()
uList unify (ty1:tys1) (ty2:tys2) = do { unify ty1 ty2; uList unify tys1 tys2 }
uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
753 754
\end{code}

755
@unifyTypeList@ takes a single list of @TauType@s and unifies them
756 757 758 759
all together.  It is used, for example, when typechecking explicit
lists, when all the elts should be of the same type.

\begin{code}
760 761 762 763 764
unifyTypeList :: [TcTauType] -> TcM ()
unifyTypeList []		 = returnM ()
unifyTypeList [ty]		 = returnM ()
unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
				      ; unifyTypeList tys }
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
\end{code}

%************************************************************************
%*									*
\subsection[Unify-uTys]{@uTys@: getting down to business}
%*									*
%************************************************************************

@uTys@ is the heart of the unifier.  Each arg happens twice, because
we want to report errors in terms of synomyms if poss.  The first of
the pair is used in error messages only; it is always the same as the
second, except that if the first is a synonym then the second may be a
de-synonym'd version.  This way we get better error messages.

We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.

\begin{code}
782 783 784
type NoBoxes = Bool	-- True  <=> definitely no boxes in this type
			-- False <=> there might be boxes (always safe)

785 786 787 788 789 790 791 792 793
type Outer = Bool	-- True <=> this is the outer level of a unification
			--	    so that the types being unified are the
			--	    very ones we began with, not some sub
			--	    component or synonym expansion
-- The idea is that if Outer is true then unifyMisMatch should
-- pop the context to remove the "Expected/Acutal" context

uTysOuter, uTys
     :: NoBoxes -> TcType	-- ty1 is the *expected* type
794
     -> NoBoxes -> TcType	-- ty2 is the *actual* type
795
     -> TcM ()
796 797
uTysOuter nb1 ty1 nb2 ty2 = u_tys True nb1 ty1 ty1 nb2 ty2 ty2
uTys      nb1 ty1 nb2 ty2 = u_tys False nb1 ty1 ty1 nb2 ty2 ty2
798 799 800 801 802 803 804 805


--------------
uTys_s :: NoBoxes -> [TcType]	-- ty1 is the *actual* types
       -> NoBoxes -> [TcType]	-- ty2 is the *expected* types
       -> TcM ()
uTys_s nb1 []	 	nb2 []	       = returnM ()
uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { uTys nb1 ty1 nb2 ty2
806
					  ; uTys_s nb1 tys1 nb2 tys2 }
807 808 809
uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"

--------------
810 811
u_tys :: Outer
      -> NoBoxes -> TcType -> TcType	-- ty1 is the *actual* type
812 813 814
      -> NoBoxes -> TcType -> TcType	-- ty2 is the *expected* type
      -> TcM ()

815 816
u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
  = go outer ty1 ty2
817
  where 
818 819 820

	-- Always expand synonyms (see notes at end)
        -- (this also throws away FTVs)
821 822 823
    go outer ty1 ty2 
      | Just ty1' <- tcView ty1 = go False ty1' ty2
      | Just ty2' <- tcView ty2 = go False ty1 ty2'
824 825

	-- Variables; go for uVar
826 827
    go outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
    go outer ty1 (TyVarTy tyvar2) = uVar outer True  tyvar2 nb1 orig_ty1 ty1
828
				-- "True" means args swapped
829
	-- Predicates
830
    go outer (PredTy p1) (PredTy p2) = uPred outer nb1 p1 nb2 p2
831

832
	-- Type constructors must match
833
    go _ (TyConApp con1 tys1) (TyConApp con2 tys2)
834
      | con1 == con2 = uTys_s nb1 tys1 nb2 tys2
835
	-- See Note [TyCon app]
836

837
	-- Functions; just check the two parts
838
    go _ (FunTy fun1 arg1) (FunTy fun2 arg2)
839 840 841
      = do { uTys nb1 fun1 nb2 fun2
	   ; uTys nb1 arg1 nb2 arg2 }

842 843 844 845
	-- Applications need a bit of care!
	-- They can match FunTy and TyConApp, so use splitAppTy_maybe
	-- NB: we've already dealt with type variables and Notes,
	-- so if one type is an App the other one jolly well better be too
846 847 848
    go outer (AppTy s1 t1) ty2
      | Just (s2,t2) <- tcSplitAppTy_maybe ty2
      = do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
849 850 851

	-- Now the same, but the other way round
	-- Don't swap the types, because the error messages get worse
852 853 854
    go outer ty1 (AppTy s2 t2)
      | Just (s1,t1) <- tcSplitAppTy_maybe ty1
      = do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
855

856
    go _ ty1@(ForAllTy _ _) ty2@(ForAllTy _ _)
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
      | length tvs1 == length tvs2
      = do   { tvs <- tcInstSkolTyVars UnkSkol tvs1	-- Not a helpful SkolemInfo
	     ; let tys      = mkTyVarTys tvs
	           in_scope = mkInScopeSet (mkVarSet tvs)
 	           subst1   = mkTvSubst in_scope (zipTyEnv tvs1 tys)
	           subst2   = mkTvSubst in_scope (zipTyEnv tvs2 tys)
	     ; uTys nb1 (substTy subst1 body1) nb2 (substTy subst2 body2)

		-- If both sides are inside a box, we should not have
		-- a polytype at all.  This check comes last, because
		-- the error message is extremely unhelpful.
	     ; ifM (nb1 && nb2) (notMonoType ty1)
	     }
      where
	(tvs1, body1) = tcSplitForAllTys ty1
	(tvs2, body2) = tcSplitForAllTys ty2
873 874

	-- Anything else fails
875
    go outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
876 877

----------
878
uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
879
  | n1 == n2 = uTys nb1 t1 nb2 t2
880
uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
881
  | c1 == c2 = uTys_s nb1 tys1 nb2 tys2		-- Guaranteed equal lengths because the kinds check
882
uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
883 884
\end{code}

885 886 887 888 889 890 891 892 893 894
Note [Tycon app]
~~~~~~~~~~~~~~~~
When we find two TyConApps, the argument lists are guaranteed equal
length.  Reason: intially the kinds of the two types to be unified is
the same. The only way it can become not the same is when unifying two
AppTys (f1 a1):=:(f2 a2).  In that case there can't be a TyConApp in
the f1,f2 (because it'd absorb the app).  If we unify f1:=:f2 first,
which we do, that ensures that f1,f2 have the same kind; and that
means a1,a2 have the same kind.  And now the argument repeats.

895 896 897 898 899 900 901 902 903 904 905

Notes on synonyms
~~~~~~~~~~~~~~~~~
If you are tempted to make a short cut on synonyms, as in this
pseudocode...

\begin{verbatim}
-- NO	uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
-- NO     = if (con1 == con2) then
-- NO	-- Good news!  Same synonym constructors, so we can shortcut
-- NO	-- by unifying their arguments and ignoring their expansions.
906
-- NO	unifyTypepeLists args1 args2
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
-- NO    else
-- NO	-- Never mind.  Just expand them and try again
-- NO	uTys ty1 ty2
\end{verbatim}

then THINK AGAIN.  Here is the whole story, as detected and reported
by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
\begin{quotation}
Here's a test program that should detect the problem:

\begin{verbatim}
	type Bogus a = Int
	x = (1 :: Bogus Char) :: Bogus Bool
\end{verbatim}

The problem with [the attempted shortcut code] is that
\begin{verbatim}
	con1 == con2
\end{verbatim}
is not a sufficient condition to be able to use the shortcut!
You also need to know that the type synonym actually USES all
its arguments.  For example, consider the following type synonym
which does not use all its arguments.
\begin{verbatim}
	type Bogus a = Int
\end{verbatim}

If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
would fail, even though the expanded forms (both \tr{Int}) should
match.

Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
unnecessarily bind \tr{t} to \tr{Char}.

... You could explicitly test for the problem synonyms and mark them
somehow as needing expansion, perhaps also issuing a warning to the
user.
\end{quotation}


%************************************************************************
%*									*
\subsection[Unify-uVar]{@uVar@: unifying with a type variable}
%*									*
%************************************************************************

@uVar@ is called when at least one of the types being unified is a
variable.  It does {\em not} assume that the variable is a fixed point
of the substitution; rather, notice that @uVar@ (defined below) nips
back into @uTys@ if it turns out that the variable is already bound.

\begin{code}
960 961
uVar :: Outer
     -> Bool		-- False => tyvar is the "expected"
962 963
			-- True  => ty    is the "expected" thing
     -> TcTyVar
964
     -> NoBoxes		-- True <=> definitely no boxes in t2
965 966 967
     -> TcTauType -> TcTauType	-- printing and real versions
     -> TcM ()

968
uVar outer swapped tv1 nb2 ps_ty2 ty2
969 970 971 972 973 974 975 976 977
  = do 	{ let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
			| otherwise = brackets (equals <+> ppr ty2)
	; traceTc (text "uVar" <+> ppr swapped <+> 
			sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
				nest 2 (ptext SLIT(" :=: ")),
			     ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
	; details <- lookupTcTyVar tv1
	; case details of
	    IndirectTv ty1 
978 979
		| swapped   -> u_tys outer nb2  ps_ty2 ty2 True ty1    ty1	-- Swap back
		| otherwise -> u_tys outer True ty1    ty1 nb2  ps_ty2 ty2	-- Same order
980 981
			-- The 'True' here says that ty1 
			-- is definitely box-free
982
	    DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 ty2
983
	}
984 985

----------------
986 987
uUnfilledVar :: Outer
	     -> Bool 				-- Args are swapped
988 989 990
     	     -> TcTyVar -> TcTyVarDetails		-- Tyvar 1
     	     -> NoBoxes -> TcTauType -> TcTauType	-- Type 2
     	     -> TcM ()
991 992
-- Invariant: tyvar 1 is not unified with anything

993
uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 ty2
994
  | Just ty2' <- tcView ty2
995
  = 	-- Expand synonyms; ignore FTVs
996
    uUnfilledVar False swapped tv1 details1 nb2 ps_ty2 ty2'
997

998
uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 ty2@(TyVarTy tv2)
999 1000
	-- Same type variable => no-op
  | tv1 == tv2
1001
  = returnM ()
1002 1003 1004

	-- Distinct type variables
  | otherwise
1005
  = do	{ lookup2 <- lookupTcTyVar tv2
1006
	; case lookup2 of
1007 1008
	    IndirectTv ty2' -> uUnfilledVar  outer swapped tv1 details1 True ty2' ty2'
	    DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1009 1010
	}

1011
uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 non_var_ty2	-- ty2 is not a type variable
1012
  = case details1 of
1013 1014 1015 1016
	MetaTv (SigTv _) ref1 -> mis_match	-- Can't update a skolem with a non-type-variable
	MetaTv info ref1      -> uMetaVar swapped tv1 info ref1 nb2 ps_ty2 non_var_ty2
	skolem_details        -> mis_match
  where
1017
    mis_match = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1018

1019 1020 1021 1022 1023 1024 1025
----------------
uMetaVar :: Bool
	 -> TcTyVar -> BoxInfo -> IORef MetaDetails
	 -> NoBoxes -> TcType -> TcType
	 -> TcM ()
-- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
-- ty2 is not a type variable
1026

1027 1028 1029 1030 1031
uMetaVar swapped tv1 info1 ref1 nb2 ps_ty2 non_var_ty2
  = do	{ final_ty <- case info1 of
			BoxTv -> unBox ps_ty2			-- No occurs check
			other -> checkTauTvUpdate tv1 ps_ty2	-- Occurs check + monotype check
	; checkUpdateMeta swapped tv1 ref1 final_ty }
1032 1033

----------------
1034 1035
uUnfilledVars :: Outer
	      -> Bool 			-- Args are swapped
1036 1037 1038 1039 1040 1041 1042
      	      -> TcTyVar -> TcTyVarDetails	-- Tyvar 1
      	      -> TcTyVar -> TcTyVarDetails	-- Tyvar 2
      	      -> TcM ()
-- Invarant: The type variables are distinct, 
-- 	     Neither is filled in yet
--    	     They might be boxy or not

1043 1044
uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
  = unifyMisMatch outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1045

1046
uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1047
  = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2)
1048
uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1049 1050 1051
  = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1)

-- ToDo: this function seems too long for what it acutally does!
1052
uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
  = case (info1, info2) of
	(BoxTv,   BoxTv)   -> box_meets_box

	-- If a box meets a TauTv, but the fomer has the smaller kind
	-- then we must create a fresh TauTv with the smaller kind
	(_,       BoxTv)   | k1_sub_k2 -> update_tv2
			   | otherwise -> box_meets_box
	(BoxTv,   _    )   | k2_sub_k1 -> update_tv1
			   | otherwise -> box_meets_box

	-- Avoid SigTvs if poss
	(SigTv _, _      ) | k1_sub_k2 -> update_tv2
	(_,       SigTv _) | k2_sub_k1 -> update_tv1

	(_,   _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
				then update_tv1 	-- Same kinds
				else update_tv2
		 | k2_sub_k1 -> update_tv1
		 | otherwise -> kind_err 

1073 1074 1075 1076
	-- Update the variable with least kind info
	-- See notes on type inference in Kind.lhs
	-- The "nicer to" part only applies if the two kinds are the same,
	-- so we can choose which to do.
1077 1078 1079 1080 1081
  where
	-- Kinds should be guaranteed ok at this point
    update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
    update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)

1082 1083 1084 1085
    box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
				then fill_from tv2
				else fill_from tv1
		  | k2_sub_k1 = fill_from tv2
1086 1087
		  | otherwise = kind_err

1088 1089 1090 1091 1092 1093
	-- Update *both* tyvars with a TauTv whose name and kind
	-- are gotten from tv (avoid losing nice names is poss)
    fill_from tv = do { tv' <- tcInstTyVar tv
		      ; let tau_ty = mkTyVarTy tv'
		      ; updateMeta tv1 ref1 tau_ty
		      ; updateMeta tv2 ref2 tau_ty }
1094 1095 1096 1097 1098 1099 1100 1101

    kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2))	$
	       unifyKindMisMatch k1 k2

    k1 = tyVarKind tv1
    k2 = tyVarKind tv2
    k1_sub_k2 = k1 `isSubKind` k2
    k2_sub_k1 = k2 `isSubKind` k1
1102

1103
    nicer_to_update_tv1 = isSystemName (varName tv1)
1104 1105 1106 1107 1108
	-- Try to update sys-y type variables in preference to ones
	-- gotten (say) by instantiating a polymorphic function with
	-- a user-written type sig
	
----------------
1109
checkUpdateMeta :: Bool -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1110
-- Update tv1, which is flexi; occurs check is alrady done
1111 1112 1113 1114 1115
-- The 'check' version does a kind check too
-- We do a sub-kind check here: we might unify (a b) with (c d) 
--	where b::*->* and d::*; this should fail

checkUpdateMeta swapped tv1 ref1 ty2
1116
  = do	{ checkKinds swapped tv1 ty2
1117 1118 1119 1120 1121 1122 1123 1124
	; updateMeta tv1 ref1 ty2 }

updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
updateMeta tv1 ref1 ty2
  = ASSERT( isMetaTyVar tv1 )
    ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
    do	{ ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
	; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
1125
	; writeMutVar ref1 (Indirect ty2) }
1126

1127
----------------
1128 1129
checkKinds swapped tv1 ty2
-- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
1130 1131
-- ty2 has been zonked at this stage, which ensures that
-- its kind has as much boxity information visible as possible.
1132
  | tk2 `isSubKind` tk1 = returnM ()
1133 1134 1135 1136 1137 1138

  | otherwise
	-- Either the kinds aren't compatible
	--	(can happen if we unify (a b) with (c d))
	-- or we are unifying a lifted type variable with an
	-- 	unlifted type: e.g.  (id 3#) is illegal
1139
  = addErrCtxtM (unifyKindCtxt swapped tv1 ty2)	$
1140
    unifyKindMisMatch k1 k2
1141 1142 1143 1144 1145 1146
  where
    (k1,k2) | swapped   = (tk2,tk1)
	    | otherwise = (tk1,tk2)
    tk1 = tyVarKind tv1
    tk2 = typeKind ty2

1147 1148 1149 1150 1151 1152 1153 1154
----------------
checkTauTvUpdate :: TcTyVar -> TcType -> TcM TcType
--    (checkTauTvUpdate tv ty)
-- We are about to update the TauTv tv with ty.
-- Check (a) that tv doesn't occur in ty (occurs check)
--	 (b) that ty is a monotype
-- Furthermore, in the interest of (b), if you find an
-- empty box (BoxTv that is Flexi), fill it in with a TauTv
1155
-- 
1156 1157 1158 1159
-- Returns the (non-boxy) type to update the type variable with, or fails

checkTauTvUpdate orig_tv orig_ty
  = go orig_ty
1160
  where
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    go (TyConApp tc tys)
	| isSynTyCon tc  = go_syn tc tys
	| otherwise	 = do { tys' <- mappM go tys; return (TyConApp tc tys') }
    go (NoteTy _ ty2) 	 = go ty2	-- Discard free-tyvar annotations
    go (PredTy p)	 = do { p' <- go_pred p; return (PredTy p') }
    go (FunTy arg res)   = do { arg' <- go arg; res' <- go res; return (FunTy arg' res') }
    go (AppTy fun arg)	 = do { fun' <- go fun; arg' <- go arg; return (mkAppTy fun' arg') }
		-- NB the mkAppTy; we might have instantiated a
		-- type variable to a type constructor, so we need
		-- to pull the TyConApp to the top.
    go (ForAllTy tv ty) = notMonoType orig_ty		-- (b)

    go (TyVarTy tv)
	| orig_tv == tv = occurCheck tv orig_ty		-- (a)
	| isTcTyVar tv  = go_tyvar tv (tcTyVarDetails tv)
	| otherwise     = return (TyVarTy tv)
		 -- Ordinary (non Tc) tyvars
		 -- occur inside quantified types

    go_pred (ClassP c tys) = do { tys' <- mapM go tys; return (ClassP c tys') }
    go_pred (IParam n ty)  = do { ty' <- go ty;        return (IParam n ty') }

    go_tyvar tv (SkolemTv _) = return (TyVarTy tv)
    go_tyvar tv (MetaTv box ref)
	= do { cts <- readMutVar ref
	     ; case cts of
		  Indirect ty -> go ty 
		  Flexi -> case box of
1189
				BoxTv -> fillBoxWithTau tv ref
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
				other -> return (TyVarTy tv)
	     }

	-- go_syn is called for synonyms only
	-- See Note [Type synonyms and the occur check]
    go_syn tc tys
	| not (isTauTyCon tc)
	= notMonoType orig_ty	-- (b) again
	| otherwise
	= do { (msgs, mb_tys') <- tryTc (mapM go tys)
	     ; case mb_tys' of
		Just tys' -> return (TyConApp tc tys')
				-- Retain the synonym (the common case)
1203 1204
		Nothing   -> go (expectJust "checkTauTvUpdate" 
					(tcView (TyConApp tc tys)))
1205 1206
				-- Try again, expanding the synonym
	     }
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219

fillBoxWithTau :: BoxyTyVar -> IORef MetaDetails -> TcM TcType
-- (fillBoxWithTau tv ref) fills ref with a freshly allocated 
--  tau-type meta-variable, whose print-name is the same as tv
-- Choosing the same name is good: when we instantiate a function
-- we allocate boxy tyvars with the same print-name as the quantified
-- tyvar; and then we often fill the box with a tau-tyvar, and again
-- we want to choose the same name.
fillBoxWithTau tv ref 
  = do	{ tv' <- tcInstTyVar tv		-- Do not gratuitously forget
	; let tau = mkTyVarTy tv'	-- name of the type variable
	; writeMutVar ref (Indirect tau)
	; return tau }
1220 1221 1222 1223 1224 1225 1226 1227 1228
\end{code}

Note [Type synonyms and the occur check]
~~~~~~~~~~~~~~~~~~~~
Basically we want to update     tv1 := ps_ty2
because ps_ty2 has type-synonym info, which improves later error messages

But consider 
	type A a = ()
1229

1230 1231
	f :: (A a -> a -> ()) -> ()
	f = \ _ -> ()
1232

1233 1234
	x :: ()
	x = f (\ x p -> p x)
1235

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
In the application (p x), we try to match "t" with "A t".  If we go
ahead and bind t to A t (= ps_ty2), we'll lead the type checker into 
an infinite loop later.
But we should not reject the program, because A t = ().
Rather, we should bind t to () (= non_var_ty2).

\begin{code}
stripBoxyType :: BoxyType -> TcM TcType
-- Strip all boxes from the input type, returning a non-boxy type.
-- It's fine for there to be a polytype inside a box (c.f. unBox)
-- All of the boxes should have been filled in by now; 
-- hence we return a TcType
stripBoxyType ty = zonkType strip_tv ty
1249
  where