TcUnify.lhs 66.1 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
  checkExpectedKind, 
16
  preSubType, 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
import TcMType		( lookupTcTyVar, LookupTyVarResult(..),
32 33
                          tcInstSkolType, tcInstBoxyTyVar, newKindVar, newMetaTyVar,
			  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
			  tcSplitSigmaTy, tyVarsOfType, mkPhiTy, mkTyVarTy, mkPredTy, 
50
			  typeKind, mkForAllTys, mkAppTy, isBoxyTyVar,
51
			  exactTyVarsOfType, 
52
			  tidyOpenType, tidyOpenTyVar, tidyOpenTyVars,
53
			  pprType, tidyKind, tidySkolemTyVar, isSkolemTyVar, tcView, 
54 55
			  TvSubst, mkTvSubst, zipTyEnv, zipOpenTvSubst, emptyTvSubst, 
			  substTy, substTheta, 
56
			  lookupTyVar, extendTvSubst )
57
import Kind		( Kind(..), SimpleKind, KindVar, isArgTypeKind,
Simon Marlow's avatar
Simon Marlow committed
58 59
			  openTypeKind, liftedTypeKind, unliftedTypeKind, 
			  mkArrowKind, defaultKind,
60 61
			  isOpenTypeKind, argTypeKind, isLiftedTypeKind, isUnliftedTypeKind,
			  isSubKind, pprKind, splitKindFunTys )
62 63 64
import TysPrim		( alphaTy, betaTy )
import Inst		( newDicts, instToId )
import TyCon		( TyCon, tyConArity, tyConTyVars, isSynTyCon )
65
import TysWiredIn	( listTyCon )
66
import Id		( Id, mkSysLocal )
67 68
import Var		( Var, varName, tyVarKind, isTcTyVar, tcTyVarDetails )
import VarSet		( emptyVarSet, mkVarSet, unitVarSet, unionVarSet, elemVarSet, varSetElems,
69
			  extendVarSet, intersectsVarSet, extendVarSetList )
70
import VarEnv
71
import Name		( Name, isSystemName )
72
import ErrUtils		( Message )
73
import Maybes		( expectJust, isNothing )
74
import BasicTypes	( Arity )
75
import UniqSupply	( uniqsFromSupply )
76
import Util		( notNull, equalLength )
77 78
import Outputable

79 80 81 82 83
-- Assertion imports
#ifdef DEBUG
import TcType		( isBoxyTy, isFlexi )
#endif
\end{code}
84

85 86 87 88 89 90 91
%************************************************************************
%*									*
\subsection{'hole' type variables}
%*									*
%************************************************************************

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


%************************************************************************
%*									*
103
	subFunTys
104 105 106 107
%*									*
%************************************************************************

\begin{code}
108 109 110 111 112 113 114 115 116 117 118 119
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
120
--
121
-- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
122

123 124

{-	Error messages from subFunTys
125 126 127 128 129 130 131 132 133 134 135 136 137 138

   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
-}

139 140 141

subFunTys error_herald n_pats res_ty thing_inside
  = loop n_pats [] res_ty
142
  where
143 144 145 146 147 148
	-- 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
149 150
	| isSigmaTy res_ty 	-- Do this before checking n==0, because we 
				-- guarantee to return a BoxyRhoType, not a BoxySigmaType
151 152 153 154
	= 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) }

155 156 157 158
    loop 0 args_so_far res_ty 
	= do { res <- thing_inside (reverse args_so_far) res_ty
	     ; return (idCoercion, res) }

159 160 161 162 163
    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) }

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')
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
171
	     ; if isNothing mb_unit then bale_out args_so_far
172 173
	       else loop n args_so_far (FunTy arg_ty' res_ty') }

174 175 176 177 178 179 180 181 182 183 184 185 186 187
    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.

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
188
    loop n args_so_far res_ty = bale_out args_so_far
189

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
190
    bale_out args_so_far 
191 192 193 194
	= 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)) }
195

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

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

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
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) }
234
	}
235 236 237
      where
	mk_res_ty arg_tys' = mkTyConApp tc arg_tys'
	arg_kinds = map tyVarKind (take n_req (tyConTyVars tc))
238

239
    loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc))) orig_ty
240

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

246

247
----------------------
248 249 250 251
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
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 279 280 281
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
282

283 284
------------------
boxySplitFailure actual_ty expected_ty
285 286 287
  = 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!
288
\end{code}
289 290


291 292 293
--------------------------------
-- withBoxes: the key utility function
--------------------------------
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 327 328 329
\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}
330 331


332 333 334 335 336
%************************************************************************
%*									*
		Approximate boxy matching
%*									*
%************************************************************************
337

338
\begin{code}
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
preSubType :: [TcTyVar]		-- Quantified type variables
	   -> TcTyVarSet	-- Subset of quantified type variables
				-- that can be instantiated with boxy types
	    -> TcType		-- The rho-type part; quantified tyvars scopes over this
	    -> BoxySigmaType	-- Matching type from the context
	    -> TcM [TcType]	-- Types to instantiate the tyvars
-- Perform pre-subsumption, and return suitable types
-- to instantiate the quantified type varibles:
--	info from the pre-subsumption, if there is any
--	a boxy type variable otherwise
--
-- The 'btvs' are a subset of 'qtvs'.  They are the ones we can
-- instantiate to a boxy type variable, because they'll definitely be
-- filled in later.  This isn't always the case; sometimes we have type 
-- variables mentioned in the context of the type, but not the body; 
--		f :: forall a b. C a b => a -> a
-- Then we may land up with an unconstrained 'b', so we want to 
-- instantiate it to a monotype (non-boxy) type variable
	
preSubType qtvs btvs qty expected_ty
359 360 361
  = do { tys <- mapM inst_tv qtvs
	; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
	; return tys }
362 363 364 365 366 367 368 369 370
  where
    pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
    inst_tv tv	
	| Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
	| tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
				    ; return (mkTyVarTy tv') }
	| otherwise	       = do { tv' <- tcInstTyVar tv
				    ; return (mkTyVarTy tv') }

371 372 373 374 375
boxySubMatchType 
	:: TcTyVarSet -> TcType	-- The "template"; the tyvars are skolems
	-> BoxyRhoType		-- Type to match (note a *Rho* type)
	-> TvSubst 		-- Substitution of the [TcTyVar] to BoxySigmaTypes

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
-- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
-- "Boxy types: inference for higher rank types and impredicativity"

boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
  = go tmpl_ty emptyVarSet boxy_ty
  where
    go t_ty b_tvs b_ty
	| Just t_ty' <- tcView t_ty = go t_ty' b_tvs b_ty
	| Just b_ty' <- tcView b_ty = go t_ty b_tvs b_ty'

    go (TyVarTy _) b_tvs b_ty = emptyTvSubst	-- Rule S-ANY; no bindings
	-- Rule S-ANY covers (a) type variables and (b) boxy types
	-- in the template.  Both look like a TyVarTy.
	-- See Note [Sub-match] below

391 392 393 394 395 396 397 398 399 400 401
    go t_ty b_tvs b_ty
	| isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty 
	= go t_tau b_tvs b_ty				-- Rule S-SPEC
	| isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty 
	= go t_ty (extendVarSetList b_tvs tvs) b_ty	-- Rule S-SKOL
	-- NB: it's *important* to discard the theta part. Otherwise
	-- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
	-- and end up with a completely bogus binding (b |-> Bool), by lining
	-- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).  
	-- This pre-subsumption stuff can return too few bindings, but it 
	-- must *never* return bogus info.
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
							
    go (FunTy arg1 res1) b_tvs (FunTy arg2 res2)	-- Rule S-FUN
	= boxy_match tmpl_tvs arg1 b_tvs arg2 (go res1 b_tvs res2)
	-- Match the args, and sub-match the results

    go t_ty b_tvs b_ty = boxy_match tmpl_tvs t_ty b_tvs b_ty emptyTvSubst
	-- Otherwise defer to boxy matching
	-- This covers TyConApp, AppTy, PredTy
\end{code}

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.


\begin{code}
430 431 432 433 434
boxyMatchTypes 
	:: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
	-> [BoxySigmaType]	  -- Type to match
	-> TvSubst 		  -- Substitution of the [TcTyVar] to BoxySigmaTypes

435 436 437
-- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
-- "Boxy types: inference for higher rank types and impredicativity"

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 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
-- 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
--
-- 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
--
	
------------
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))
501
	, typeKind b_ty `isSubKind` tyVarKind tv  -- See Note [Matching kinds]
502
	= extendTvSubst subst tv boxy_ty'
503 504
	| otherwise
	= subst				-- Ignore others
505 506 507 508 509
	where
	  boxy_ty' = case lookupTyVar subst tv of
			Nothing -> orig_boxy_ty
			Just ty -> ty `boxyLub` orig_boxy_ty

510 511 512 513 514 515 516
    go _ _ = emptyTvSubst	-- It's important to *fail* by returning the empty substitution
	-- Example:  Tree a ~ Maybe Int
	-- We do not want to bind (a |-> Int) in pre-matching, because that can give very
	-- misleading error messages.  An even more confusing case is
	--	     a -> b ~ Maybe Int
	-- Then we do not want to bind (b |-> Int)!  It's always safe to discard bindings
	-- from this pre-matching phase.
517 518 519 520 521 522 523 524 525 526 527 528

    --------
    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)
529
    go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
530 531 532 533 534
    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; 
535 536
      | isTcTyVar tv1, isBoxyTyVar tv1 	-- choose ty2 if ty2 is a box
      = orig_ty2	
537 538 539 540 541 542 543

	-- 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
544 545
\end{code}

546 547 548 549 550 551 552 553 554 555 556 557 558
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.
559

560 561
%************************************************************************
%*									*
562
		Subsumption checking
563 564 565
%*									*
%************************************************************************

566 567 568 569 570
All the tcSub calls have the form
	
		tcSub expected_ty offered_ty
which checks
		offered_ty <= expected_ty
571

572
That is, that a value of type offered_ty is acceptable in
573 574 575
a place expecting a value of type expected_ty.

It returns a coercion function 
576 577
	co_fn :: offered_ty -> expected_ty
which takes an HsExpr of type offered_ty into one of type
578 579 580
expected_ty.

\begin{code}
581
-----------------
582 583
tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM ExprCoFn	-- Locally used only
	-- (tcSub act exp) checks that 
584
	--	act <= exp
585
tcSubExp actual_ty expected_ty
586 587 588 589 590 591 592 593
  = 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)
		   
594
-----------------
595 596
tc_sub :: Outer			-- See comments with uTys
       -> BoxySigmaType		-- actual_ty, before expanding synonyms
597 598 599
       -> BoxySigmaType		-- 		..and after
       -> BoxySigmaType		-- expected_ty, before
       -> BoxySigmaType		-- 		..and after
600
       -> TcM ExprCoFn
601

602 603 604 605
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
606

607
-----------------------------------
608 609 610
-- Rule SBOXY, plus other cases when act_ty is a type variable
-- Just defer to boxy matching
-- This rule takes precedence over SKOL!
611 612
tc_sub outer act_sty (TyVarTy tv) exp_sty exp_ty
  = do	{ uVar outer False tv False exp_sty exp_ty
613
	; return idCoercion }
614 615

-----------------------------------
616
-- Skolemisation case (rule SKOL)
617 618 619 620 621 622 623 624 625
-- 	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 !

626
tc_sub outer act_sty act_ty exp_sty exp_ty
627 628
  | isSigmaTy exp_ty
  = do	{ (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ body_exp_ty ->
629
			     tc_sub False act_sty act_ty body_exp_ty body_exp_ty
630 631 632
	; return (gen_fn <.> co_fn) }
  where
    act_tvs = tyVarsOfType act_ty
633 634
		-- It's really important to check for escape wrt 
		-- the free vars of both expected_ty *and* actual_ty
635 636

-----------------------------------
637
-- Specialisation case (rule ASPEC):
638 639 640 641
--	actual_ty:   forall a. Ord a => a->a
--	expected_ty: Int -> Int
--	co_fn e =    e Int dOrdInt

642
tc_sub outer act_sty actual_ty exp_sty expected_ty
643 644 645 646 647 648 649
-- Implements the new SPEC rule in the Appendix of the paper
-- "Boxy types: inference for higher rank types and impredicativity"
-- (This appendix isn't in the published version.)
-- The idea is to *first* do pre-subsumption, and then full subsumption
-- Example:	forall a. a->a  <=  Int -> (forall b. Int)
--   Pre-subsumpion finds a|->Int, and that works fine, whereas
--   just running full subsumption would fail.
650
  | isSigmaTy actual_ty
651 652 653 654 655 656 657 658 659 660 661 662 663 664
  = do	{ 	-- Perform pre-subsumption, and instantiate
	  	-- the type with info from the pre-subsumption; 
		-- boxy tyvars if pre-subsumption gives no info
	  let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
	      tau_tvs = exactTyVarsOfType tau
	; inst_tys <- preSubType tyvars tau_tvs tau expected_ty
	; let subst' = zipOpenTvSubst tyvars inst_tys
	      tau'   = substTy subst' tau

		-- Perform a full subsumption check
	; co_fn <- tc_sub False tau' tau' exp_sty expected_ty

		-- Deal with the dictionaries
	; dicts <- newDicts InstSigOrigin (substTheta subst' theta)
665
	; extendLIEs dicts
666
	; let inst_fn = CoApps (CoTyApps CoHole inst_tys) 
667 668
			       (map instToId dicts)
	; return (co_fn <.> inst_fn) }
669 670

-----------------------------------
671
-- Function case (rule F1)
672
tc_sub _ _ (FunTy act_arg act_res) _ (FunTy exp_arg exp_res)
673 674 675
  = tc_sub_funs act_arg act_res exp_arg exp_res

-- Function case (rule F2)
676
tc_sub outer act_sty act_ty@(FunTy act_arg act_res) exp_sty (TyVarTy exp_tv)
677 678 679
  | isBoxyTyVar exp_tv
  = do	{ cts <- readMetaTyVar exp_tv
	; case cts of
680
	    Indirect ty -> do { u_tys outer False act_sty act_ty True exp_sty ty
681 682 683 684 685 686 687 688
			      ; 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
689 690
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
691
	; return idCoercion }
692 693 694


-----------------------------------
695 696
tc_sub_funs act_arg act_res exp_arg exp_res
  = do	{ uTys False act_arg False exp_arg
697
	; co_fn_res <- tc_sub False act_res act_res exp_res exp_res
698
	; wrapFunResCoercion [exp_arg] co_fn_res }
699 700

-----------------------------------
701 702 703 704 705 706 707 708 709 710 711
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))) }
712 713 714
\end{code}


715

716 717 718 719 720 721 722
%************************************************************************
%*									*
\subsection{Generalisation}
%*									*
%************************************************************************

\begin{code}
723
tcGen :: BoxySigmaType				-- expected_ty
724 725 726
      -> TcTyVarSet				-- Extra tyvars that the universally
						--	quantified tyvars of expected_ty
						-- 	must not be unified
727
      -> (BoxyRhoType -> TcM result)		-- spec_ty
728
      -> TcM (ExprCoFn, result)
729 730
	-- The expression has type: spec_ty -> expected_ty

731 732
tcGen expected_ty extra_tvs thing_inside	-- We expect expected_ty to be a forall-type
						-- If not, the call is a no-op
733 734 735 736 737
  = 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) ->
738
		do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
739 740 741 742 743 744 745 746 747 748 749
		   ; 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
750 751

	-- Type-check the arg and unify with poly type
752
	; (result, lie) <- getLIE (thing_inside rho_ty)
753 754 755 756 757 758 759 760 761 762 763 764

	-- 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.

765
	; dicts <- newDicts (SigOrigin skol_info) theta
766
	; inst_binds <- tcSimplifyCheck sig_msg forall_tvs dicts lie
767

768 769
	; checkSigTyVarsWrt free_tvs forall_tvs
	; traceTc (text "tcGen:done")
770

771
	; let
772 773 774
	    -- 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.
775 776 777
		dict_ids   = map instToId dicts
		co_fn = CoTyLams forall_tvs $ CoLams dict_ids $ CoLet inst_binds CoHole 
	; returnM (co_fn, result) }
778
  where
779
    free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
780
    sig_msg  = ptext SLIT("expected type of an expression")
781 782 783 784 785 786
\end{code}    

    

%************************************************************************
%*									*
787
		Boxy unification
788 789 790 791 792 793 794
%*									*
%************************************************************************

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

\begin{code}
795 796 797
boxyUnify :: BoxyType -> BoxyType -> TcM ()
-- Acutal and expected, respectively
boxyUnify ty1 ty2 
798 799
  = addErrCtxtM (unifyCtxt ty1 ty2) $
    uTysOuter False ty1 False ty2
800 801 802 803 804 805 806 807 808 809 810 811 812 813

---------------
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 )
814 815
    addErrCtxtM (unifyCtxt ty1 ty2) $
    uTysOuter True ty1 True ty2
816 817 818 819

---------------
unifyPred :: PredType -> PredType -> TcM ()
-- Acutal and expected types
820 821
unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
		  uPred True True p1 True p2
822 823

unifyTheta :: TcThetaType -> TcThetaType -> TcM ()
824
-- Acutal and expected types
825
unifyTheta theta1 theta2
826 827 828 829 830 831 832 833 834 835 836 837 838
  = 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!"
839 840
\end{code}

841
@unifyTypeList@ takes a single list of @TauType@s and unifies them
842 843 844 845
all together.  It is used, for example, when typechecking explicit
lists, when all the elts should be of the same type.

\begin{code}
846 847 848 849 850
unifyTypeList :: [TcTauType] -> TcM ()
unifyTypeList []		 = returnM ()
unifyTypeList [ty]		 = returnM ()
unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
				      ; unifyTypeList tys }
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
\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}
868 869 870
type NoBoxes = Bool	-- True  <=> definitely no boxes in this type
			-- False <=> there might be boxes (always safe)

871 872 873 874 875 876 877 878 879
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
880
     -> NoBoxes -> TcType	-- ty2 is the *actual* type
881
     -> TcM ()
882 883
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
884 885 886 887 888 889 890 891


--------------
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
892
					  ; uTys_s nb1 tys1 nb2 tys2 }
893 894 895
uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"

--------------
896 897
u_tys :: Outer
      -> NoBoxes -> TcType -> TcType	-- ty1 is the *actual* type
898 899 900
      -> NoBoxes -> TcType -> TcType	-- ty2 is the *expected* type
      -> TcM ()

901 902
u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
  = go outer ty1 ty2
903
  where 
904 905 906

	-- Always expand synonyms (see notes at end)
        -- (this also throws away FTVs)
907 908 909
    go outer ty1 ty2 
      | Just ty1' <- tcView ty1 = go False ty1' ty2
      | Just ty2' <- tcView ty2 = go False ty1 ty2'
910 911

	-- Variables; go for uVar
912 913
    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
914
				-- "True" means args swapped
915
	-- Predicates
916
    go outer (PredTy p1) (PredTy p2) = uPred outer nb1 p1 nb2 p2
917

918
	-- Type constructors must match
919
    go _ (TyConApp con1 tys1) (TyConApp con2 tys2)
920
      | con1 == con2 = uTys_s nb1 tys1 nb2 tys2
921
	-- See Note [TyCon app]
922

923
	-- Functions; just check the two parts
924
    go _ (FunTy fun1 arg1) (FunTy fun2 arg2)
925 926 927
      = do { uTys nb1 fun1 nb2 fun2
	   ; uTys nb1 arg1 nb2 arg2 }

928 929 930 931
	-- 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
932 933 934
    go outer (AppTy s1 t1) ty2
      | Just (s2,t2) <- tcSplitAppTy_maybe ty2
      = do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
935 936 937

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

942
    go _ ty1@(ForAllTy _ _) ty2@(ForAllTy _ _)
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
      | 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
959 960

	-- Anything else fails
961
    go outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
962 963

----------
964
uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
965
  | n1 == n2 = uTys nb1 t1 nb2 t2
966
uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
967
  | c1 == c2 = uTys_s nb1 tys1 nb2 tys2		-- Guaranteed equal lengths because the kinds check
968
uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
969 970
\end{code}

971 972 973 974 975 976 977 978 979 980
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.

981 982 983 984 985 986 987 988 989 990 991

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.
992
-- NO	unifyTypepeLists args1 args2
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
-- 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}
1046 1047
uVar :: Outer
     -> Bool		-- False => tyvar is the "expected"
1048 1049
			-- True  => ty    is the "expected" thing
     -> TcTyVar
1050
     -> NoBoxes		-- True <=> definitely no boxes in t2
1051 1052 1053
     -> TcTauType -> TcTauType	-- printing and real versions
     -> TcM ()

1054
uVar outer swapped tv1 nb2 ps_ty2 ty2
1055 1056 1057 1058 1059 1060 1061 1062 1063
  = 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 
1064 1065
		| 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
1066 1067
			-- The 'True' here says that ty1 
			-- is definitely box-free
1068
	    DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 ty2
1069
	}
1070 1071

----------------
1072 1073
uUnfilledVar :: Outer
	     -> Bool 				-- Args are swapped
1074 1075 1076
     	     -> TcTyVar -> TcTyVarDetails		-- Tyvar 1
     	     -> NoBoxes -> TcTauType -> TcTauType	-- Type 2
     	     -> TcM ()
1077 1078
-- Invariant: tyvar 1 is not unified with anything

1079
uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 ty2
1080
  | Just ty2' <- tcView ty2
1081
  = 	-- Expand synonyms; ignore FTVs
1082
    uUnfilledVar False swapped tv1 details1 nb2 ps_ty2 ty2'
1083

1084 1085 1086 1087 1088 1089 1090 1091
uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 (TyVarTy tv2)
  | tv1 == tv2	-- Same type variable => no-op (but watch out for the boxy case)
  = case details1 of
	MetaTv BoxTv ref1  -- A boxy type variable meets itself;
			   -- this is box-meets-box, so fill in with a tau-type
	      -> do { tau_tv <- tcInstTyVar tv1
		    ; updateMeta tv1 ref1 (mkTyVarTy tau_tv) }
	other -> returnM ()	-- No-op
1092 1093 1094

	-- Distinct type variables
  | otherwise
1095
  = do	{ lookup2 <- lookupTcTyVar tv2
1096
	; case lookup2 of
1097 1098
	    IndirectTv ty2' -> uUnfilledVar  outer swapped tv1 details1 True ty2' ty2'
	    DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1099 1100
	}

1101
uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 non_var_ty2	-- ty2 is not a type variable
1102
  = case details1 of
1103 1104 1105 1106
	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
1107
    mis_match = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1108

1109 1110 1111 1112 1113 1114 1115
----------------
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
1116

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
uMetaVar swapped tv1 BoxTv ref1 nb2 ps_ty2 non_var_ty2
  = 	-- tv1 is a BoxTv.  So we must unbox ty2, to ensure
	-- that any boxes in ty2 are filled with monotypes
	-- 
	-- It should not be the case that tv1 occurs in ty2
	-- (i.e. no occurs check should be needed), but if perchance
	-- it does, the unbox operation will fill it, and the DEBUG
	-- checks for that.
    do 	{ final_ty <- unBox ps_ty2
#ifdef DEBUG
	; meta_details <- readMutVar ref1
	; case meta_details of
	    Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
			   return ()	-- This really should *not* happen
	    Flexi       -> return ()
#endif
	; checkUpdateMeta swapped tv1 ref1 final_ty }

1135
uMetaVar swapped tv1 info1 ref1 nb2 ps_ty2 non_var_ty2
1136
  = do	{ final_ty <- checkTauTvUpdate tv1 ps_ty2	-- Occurs check + monotype check
1137
	; checkUpdateMeta swapped tv1 ref1 final_ty }
1138 1139

----------------
1140 1141
uUnfilledVars :: Outer
	      -> Bool 			-- Args are swapped
1142 1143 1144 1145 1146 1147 1148
      	      -> 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

1149 1150
uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
  = unifyMisMatch outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1151

1152
uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1153
  = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2)
1154
uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1155 1156 1157
  = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1)

-- ToDo: this function seems too long for what it acutally does!
1158
uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
  = 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 

1179 1180 1181 1182
	-- 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.
1183 1184 1185 1186 1187
  where
	-- Kinds should be guaranteed ok at this point
    update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
    update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)

1188 1189 1190 1191
    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
1192 1193
		  | otherwise = kind_err

1194 1195 1196 1197 1198 1199
	-- 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 }
1200 1201 1202 1203 1204 1205 1206 1207

    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
1208

1209
    nicer_to_update_tv1 = isSystemName (varName tv1)
1210 1211 1212 1213 1214
	-- Try to update sys-y type variables in preference to ones
	-- gotten (say) by instantiating a polymorphic function with
	-- a user-written type sig
	
----------------
1215
checkUpdateMeta :: Bool -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1216
-- Update tv1, which is flexi; occurs check is alrady done
1217 1218 1219 1220 1221
-- 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
1222
  = do	{ checkKinds swapped tv1 ty2
1223 1224 1225 1226 1227 1228 1229 1230
	; 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)
1231
	; writeMutVar ref1 (Indirect ty2) }
1232

1233
----------------
1234 1235
checkKinds swapped tv1 ty2
-- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
1236 1237
-- ty2 has been zonked at this stage, which ensures that
-- its kind has as much boxity information visible as possible.
1238
  | tk2 `isSubKind` tk1 = returnM ()
1239 1240 1241 1242 1243 1244

  | 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
1245
  = addErrCtxtM (unifyKindCtxt swapped tv1 ty2)	$
1246
    unifyKindMisMatch k1 k2
1247 1248 1249 1250 1251 1252
  where
    (k1,k2) | swapped   = (tk2,tk1)
	    | otherwise = (tk1,tk2)
    tk1 = tyVarKind tv1
    tk2 = typeKind ty2

1253 1254 1255 1256 1257 1258 1259 1260
----------------
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
1261
-- 
1262 1263 1264 1265
-- Returns the (non-boxy) type to update the type variable with, or fails

checkTauTvUpdate orig_tv orig_ty
  = go orig_ty
1266
  where
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    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
1295
				BoxTv -> fillBoxWithTau tv ref