Two improvements to boxy matching
[ghc-hetmet.git] / compiler / typecheck / TcUnify.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Type subsumption and unification
7
8 \begin{code}
9 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module TcUnify (
17         -- Full-blown subsumption
18   tcSubExp, tcGen, 
19   checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt, 
20
21         -- Various unifications
22   unifyType, unifyTypeList, unifyTheta,
23   unifyKind, unifyKinds, unifyFunKind, 
24   checkExpectedKind, 
25   preSubType, boxyMatchTypes, 
26
27   --------------------------------
28   -- Holes
29   tcInfer, subFunTys, unBox, refineBox, refineBoxToTau, withBox, 
30   boxyUnify, boxyUnifyList, zapToMonotype,
31   boxySplitListTy, boxySplitPArrTy, boxySplitTyConApp, boxySplitAppTy,
32   wrapFunResCoercion
33   ) where
34
35 #include "HsVersions.h"
36
37 import HsSyn
38 import TypeRep
39
40 import TcMType
41 import TcSimplify
42 import TcEnv
43 import TcTyFuns
44 import TcIface
45 import TcRnMonad         -- TcType, amongst others
46 import TcType
47 import Type
48 import Coercion
49 import TysPrim
50 import Inst
51 import TyCon
52 import TysWiredIn
53 import Var
54 import VarSet
55 import VarEnv
56 import Name
57 import ErrUtils
58 import Maybes
59 import BasicTypes
60 import Util
61 import Outputable
62 import Unique
63 import FastString
64
65 import Control.Monad
66 \end{code}
67
68 %************************************************************************
69 %*                                                                      *
70 \subsection{'hole' type variables}
71 %*                                                                      *
72 %************************************************************************
73
74 \begin{code}
75 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
76 tcInfer tc_infer = withBox openTypeKind tc_infer
77 \end{code}
78
79
80 %************************************************************************
81 %*                                                                      *
82         subFunTys
83 %*                                                                      *
84 %************************************************************************
85
86 \begin{code}
87 subFunTys :: SDoc  -- Somthing like "The function f has 3 arguments"
88                    -- or "The abstraction (\x.e) takes 1 argument"
89           -> Arity              -- Expected # of args
90           -> BoxyRhoType        -- res_ty
91           -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
92           -> TcM (HsWrapper, a)
93 -- Attempt to decompse res_ty to have enough top-level arrows to
94 -- match the number of patterns in the match group
95 -- 
96 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
97 -- and the inner call to thing_inside passes args: [a1,...,an], b
98 -- then co_fn :: (a1 -> ... -> an -> b) ~ res_ty
99 --
100 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
101
102
103 {-      Error messages from subFunTys
104
105    The abstraction `\Just 1 -> ...' has two arguments
106    but its type `Maybe a -> a' has only one
107
108    The equation(s) for `f' have two arguments
109    but its type `Maybe a -> a' has only one
110
111    The section `(f 3)' requires 'f' to take two arguments
112    but its type `Int -> Int' has only one
113
114    The function 'f' is applied to two arguments
115    but its type `Int -> Int' has only one
116 -}
117
118
119 subFunTys error_herald n_pats res_ty thing_inside
120   = loop n_pats [] res_ty
121   where
122         -- In 'loop', the parameter 'arg_tys' accumulates 
123         -- the arg types so far, in *reverse order*
124         -- INVARIANT:   res_ty :: *
125     loop n args_so_far res_ty
126         | Just res_ty' <- tcView res_ty  = loop n args_so_far res_ty'
127
128     loop n args_so_far res_ty
129         | isSigmaTy res_ty      -- Do this before checking n==0, because we 
130                                 -- guarantee to return a BoxyRhoType, not a 
131                                 -- BoxySigmaType
132         = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ _ res_ty' ->
133                                          loop n args_so_far res_ty'
134              ; return (gen_fn <.> co_fn, res) }
135
136     loop 0 args_so_far res_ty 
137         = do { res <- thing_inside (reverse args_so_far) res_ty
138              ; return (idHsWrapper, res) }
139
140     loop n args_so_far (FunTy arg_ty res_ty) 
141         = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
142              ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
143              ; return (co_fn', res) }
144
145         -- Try to normalise synonym families and defer if that's not possible
146     loop n args_so_far ty@(TyConApp tc tys)
147         | isOpenSynTyCon tc
148         = do { (coi1, ty') <- tcNormaliseFamInst ty
149              ; case coi1 of
150                  IdCo   -> defer n args_so_far ty
151                                     -- no progress, but maybe solvable => defer
152                  ACo _  ->          -- progress: so lets try again
153                    do { (co_fn, res) <- loop n args_so_far ty'
154                       ; return $ (co_fn <.> coiToHsWrapper (mkSymCoI coi1), res)
155                       }
156              }
157
158         -- res_ty might have a type variable at the head, such as (a b c),
159         -- in which case we must fill in with (->).  Simplest thing to do
160         -- is to use boxyUnify, but we catch failure and generate our own
161         -- error message on failure
162     loop n args_so_far res_ty@(AppTy _ _)
163         = do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
164              ; (_, mb_coi) <- tryTcErrs $ 
165                                 boxyUnify res_ty (FunTy arg_ty' res_ty')
166              ; if isNothing mb_coi then bale_out args_so_far
167                else do { let coi = expectJust "subFunTys" mb_coi
168                        ; (co_fn, res) <- loop n args_so_far (FunTy arg_ty' 
169                                                                    res_ty')
170                        ; return (co_fn <.> coiToHsWrapper coi, res)
171                        }
172              }
173
174     loop n args_so_far ty@(TyVarTy tv)
175         | isTyConableTyVar tv
176         = do { cts <- readMetaTyVar tv 
177              ; case cts of
178                  Indirect ty -> loop n args_so_far ty
179                  Flexi -> 
180                    do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
181                       ; res <- thing_inside (reverse args_so_far ++ arg_tys) 
182                                             res_ty
183                       ; return (idHsWrapper, res) } }
184         | otherwise             -- defer as tyvar may be refined by equalities
185         = defer n args_so_far ty
186         where
187           mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
188           mk_res_ty [] = panic "TcUnify.mk_res_ty1"
189           kinds = openTypeKind : take n (repeat argTypeKind)
190                 -- Note argTypeKind: the args can have an unboxed type,
191                 -- but not an unboxed tuple.
192
193     loop n args_so_far res_ty = bale_out args_so_far
194
195          -- build a template type a1 -> ... -> an -> b and defer an equality
196          -- between that template and the expected result type res_ty; then,
197          -- use the template to type the thing_inside
198     defer n args_so_far ty
199       = do { arg_tys <- newFlexiTyVarTys n argTypeKind
200            ; res_ty' <- newFlexiTyVarTy openTypeKind
201            ; let fun_ty = mkFunTys arg_tys res_ty'
202                  err    = error_herald <> comma $$
203                           text "which does not match its type"
204            ; coi <- addErrCtxt err $
205                       defer_unification False False fun_ty ty
206            ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty'
207            ; return (coiToHsWrapper coi, res)
208            }
209
210     bale_out args_so_far 
211         = do { env0 <- tcInitTidyEnv
212              ; res_ty' <- zonkTcType res_ty
213              ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
214              ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
215
216     mk_msg res_ty n_actual 
217       = error_herald <> comma $$ 
218         sep [ptext SLIT("but its type") <+> quotes (pprType res_ty), 
219              if n_actual == 0 then ptext SLIT("has none") 
220              else ptext SLIT("has only") <+> speakN n_actual]
221 \end{code}
222
223 \begin{code}
224 ----------------------
225 boxySplitTyConApp :: TyCon                      -- T :: k1 -> ... -> kn -> *
226                   -> BoxyRhoType                -- Expected type (T a b c)
227                   -> TcM ([BoxySigmaType],      -- Element types, a b c
228                           CoercionI)            -- T a b c ~ orig_ty
229   -- It's used for wired-in tycons, so we call checkWiredInTyCon
230   -- Precondition: never called with FunTyCon
231   -- Precondition: input type :: *
232
233 boxySplitTyConApp tc orig_ty
234   = do  { checkWiredInTyCon tc 
235         ; loop (tyConArity tc) [] orig_ty }
236   where
237     loop n_req args_so_far ty 
238       | Just ty' <- tcView ty = loop n_req args_so_far ty'
239
240     loop n_req args_so_far ty@(TyConApp tycon args)
241       | tc == tycon
242       = ASSERT( n_req == length args)   -- ty::*
243         return (args ++ args_so_far, IdCo)
244
245       | isOpenSynTyCon tycon        -- try to normalise type family application
246       = do { (coi1, ty') <- tcNormaliseFamInst ty
247            ; traceTc $ text "boxySplitTyConApp:" <+> 
248                        ppr ty <+> text "==>" <+> ppr ty'
249            ; case coi1 of
250                IdCo   -> defer    -- no progress, but maybe solvable => defer
251                ACo _  ->          -- progress: so lets try again
252                  do { (args, coi2) <- loop n_req args_so_far ty'
253                     ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
254                     }
255            }
256
257     loop n_req args_so_far (AppTy fun arg)
258       | n_req > 0
259       = do { (args, coi) <- loop (n_req - 1) (arg:args_so_far) fun
260            ; return (args, mkAppTyCoI fun coi arg IdCo)
261            }
262
263     loop n_req args_so_far (TyVarTy tv)
264       | isTyConableTyVar tv
265       , res_kind `isSubKind` tyVarKind tv
266       = do { cts <- readMetaTyVar tv
267            ; case cts of
268                Indirect ty -> loop n_req args_so_far ty
269                Flexi       -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
270                                  ; return (arg_tys ++ args_so_far, IdCo) }
271            }
272       | otherwise             -- defer as tyvar may be refined by equalities
273       = defer
274       where
275         (arg_kinds, res_kind) = splitKindFunTysN n_req (tyConKind tc)
276
277     loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc)))
278                                   orig_ty
279
280     -- defer splitting by generating an equality constraint
281     defer = boxySplitDefer arg_kinds mk_res_ty orig_ty
282       where
283         (arg_kinds, _) = splitKindFunTys (tyConKind tc)
284
285     -- apply splitted tycon to arguments
286     mk_res_ty = mkTyConApp tc
287
288 ----------------------
289 boxySplitListTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
290 -- Special case for lists
291 boxySplitListTy exp_ty 
292  = do { ([elt_ty], coi) <- boxySplitTyConApp listTyCon exp_ty
293       ; return (elt_ty, coi) }
294
295 ----------------------
296 boxySplitPArrTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
297 -- Special case for parrs
298 boxySplitPArrTy exp_ty 
299   = do { ([elt_ty], coi) <- boxySplitTyConApp parrTyCon exp_ty
300        ; return (elt_ty, coi) }
301
302 ----------------------
303 boxySplitAppTy :: BoxyRhoType                           -- Type to split: m a
304                -> TcM ((BoxySigmaType, BoxySigmaType),  -- Returns m, a
305                        CoercionI)
306 -- If the incoming type is a mutable type variable of kind k, then 
307 -- boxySplitAppTy returns a new type variable (m: * -> k); note the *.
308 -- If the incoming type is boxy, then so are the result types; and vice versa
309
310 boxySplitAppTy orig_ty
311   = loop orig_ty
312   where
313     loop ty 
314       | Just ty' <- tcView ty = loop ty'
315
316     loop ty 
317       | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
318       = return ((fun_ty, arg_ty), IdCo)
319
320     loop ty@(TyConApp tycon _args)
321       | isOpenSynTyCon tycon        -- try to normalise type family application
322       = do { (coi1, ty') <- tcNormaliseFamInst ty
323            ; case coi1 of
324                IdCo   -> defer    -- no progress, but maybe solvable => defer
325                ACo co ->          -- progress: so lets try again
326                  do { (args, coi2) <- loop ty'
327                     ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
328                     }
329            }
330
331     loop (TyVarTy tv)
332       | isTyConableTyVar tv
333       = do { cts <- readMetaTyVar tv
334            ; case cts of
335                Indirect ty -> loop ty
336                Flexi -> do { [fun_ty, arg_ty] <- withMetaTvs tv kinds mk_res_ty
337                            ; return ((fun_ty, arg_ty), IdCo) } }
338       | otherwise             -- defer as tyvar may be refined by equalities
339       = defer
340       where
341         tv_kind = tyVarKind tv
342         kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
343                                                 -- m :: * -> k
344                  liftedTypeKind]                -- arg type :: *
345         -- The defaultKind is a bit smelly.  If you remove it,
346         -- try compiling        f x = do { x }
347         -- and you'll get a kind mis-match.  It smells, but
348         -- not enough to lose sleep over.
349         
350     loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
351
352     -- defer splitting by generating an equality constraint
353     defer = do { ([ty1, ty2], coi) <- boxySplitDefer arg_kinds mk_res_ty orig_ty
354                ; return ((ty1, ty2), coi)
355                }
356       where
357         orig_kind = typeKind orig_ty
358         arg_kinds = [mkArrowKind liftedTypeKind (defaultKind orig_kind),
359                                                 -- m :: * -> k
360                      liftedTypeKind]            -- arg type :: *
361  
362     -- build type application
363     mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
364     mk_res_ty _other             = panic "TcUnify.mk_res_ty2"
365
366 ------------------
367 boxySplitFailure actual_ty expected_ty
368   = unifyMisMatch False False actual_ty expected_ty
369         -- "outer" is False, so we don't pop the context
370         -- which is what we want since we have not pushed one!
371
372 ------------------
373 boxySplitDefer :: [Kind]                   -- kinds of required arguments
374                -> ([TcType] -> TcTauType)  -- construct lhs from argument tyvars
375                -> BoxyRhoType              -- type to split
376                -> TcM ([TcType], CoercionI)
377 boxySplitDefer kinds mkTy orig_ty
378   = do { tau_tys <- mapM newFlexiTyVarTy kinds
379        ; coi <- defer_unification False False (mkTy tau_tys) orig_ty
380        ; return (tau_tys, coi)
381        }
382 \end{code}
383
384
385 --------------------------------
386 -- withBoxes: the key utility function
387 --------------------------------
388
389 \begin{code}
390 withMetaTvs :: TcTyVar  -- An unfilled-in, non-skolem, meta type variable
391             -> [Kind]   -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
392             -> ([BoxySigmaType] -> BoxySigmaType)
393                                         -- Constructs the type to assign 
394                                         -- to the original var
395             -> TcM [BoxySigmaType]      -- Return the fresh boxes
396
397 -- It's entirely possible for the [kind] to be empty.  
398 -- For example, when pattern-matching on True, 
399 -- we call boxySplitTyConApp passing a boolTyCon
400
401 -- Invariant: tv is still Flexi
402
403 withMetaTvs tv kinds mk_res_ty
404   | isBoxyTyVar tv
405   = do  { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
406         ; let box_tys = mkTyVarTys box_tvs
407         ; writeMetaTyVar tv (mk_res_ty box_tys)
408         ; return box_tys }
409
410   | otherwise                   -- Non-boxy meta type variable
411   = do  { tau_tys <- mapM newFlexiTyVarTy kinds
412         ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
413                                                 -- Sure to be a tau-type
414         ; return tau_tys }
415
416 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
417 -- Allocate a *boxy* tyvar
418 withBox kind thing_inside
419   = do  { box_tv <- newBoxyTyVar kind
420         ; res <- thing_inside (mkTyVarTy box_tv)
421         ; ty  <- {- pprTrace "with_box" (ppr (mkTyVarTy box_tv)) $ -} readFilledBox box_tv
422         ; return (res, ty) }
423 \end{code}
424
425
426 %************************************************************************
427 %*                                                                      *
428                 Approximate boxy matching
429 %*                                                                      *
430 %************************************************************************
431
432 \begin{code}
433 preSubType :: [TcTyVar]         -- Quantified type variables
434            -> TcTyVarSet        -- Subset of quantified type variables
435                                 --   see Note [Pre-sub boxy]
436             -> TcType           -- The rho-type part; quantified tyvars scopes over this
437             -> BoxySigmaType    -- Matching type from the context
438             -> TcM [TcType]     -- Types to instantiate the tyvars
439 -- Perform pre-subsumption, and return suitable types
440 -- to instantiate the quantified type varibles:
441 --      info from the pre-subsumption, if there is any
442 --      a boxy type variable otherwise
443 --
444 -- Note [Pre-sub boxy]
445 --   The 'btvs' are a subset of 'qtvs'.  They are the ones we can
446 --   instantiate to a boxy type variable, because they'll definitely be
447 --   filled in later.  This isn't always the case; sometimes we have type 
448 --   variables mentioned in the context of the type, but not the body; 
449 --                f :: forall a b. C a b => a -> a
450 --   Then we may land up with an unconstrained 'b', so we want to 
451 --   instantiate it to a monotype (non-boxy) type variable
452 --
453 -- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
454 -- are instantiated to TauTv meta variables.
455         
456 preSubType qtvs btvs qty expected_ty
457   = do { tys <- mapM inst_tv qtvs
458         ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
459         ; return tys }
460   where
461     pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
462     inst_tv tv  
463         | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
464         | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
465                                     ; return (mkTyVarTy tv') }
466         | otherwise            = do { tv' <- tcInstTyVar tv
467                                     ; return (mkTyVarTy tv') }
468
469 boxySubMatchType 
470         :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
471         -> BoxyRhoType          -- Type to match (note a *Rho* type)
472         -> TvSubst              -- Substitution of the [TcTyVar] to BoxySigmaTypes
473
474 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
475 -- "Boxy types: inference for higher rank types and impredicativity"
476
477 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
478   = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
479   where
480     go t_tvs t_ty b_tvs b_ty
481         | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
482         | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
483
484     go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst      -- Rule S-ANY; no bindings
485         -- Rule S-ANY covers (a) type variables and (b) boxy types
486         -- in the template.  Both look like a TyVarTy.
487         -- See Note [Sub-match] below
488
489     go t_tvs t_ty b_tvs b_ty
490         | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty 
491         = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty       -- Rule S-SPEC
492                 -- Under a forall on the left, if there is shadowing, 
493                 -- do not bind! Hence the delVarSetList.
494         | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty 
495         = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau      -- Rule S-SKOL
496                 -- Add to the variables we must not bind to
497         -- NB: it's *important* to discard the theta part. Otherwise
498         -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
499         -- and end up with a completely bogus binding (b |-> Bool), by lining
500         -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).  
501         -- This pre-subsumption stuff can return too few bindings, but it 
502         -- must *never* return bogus info.
503                                                         
504     go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2)  -- Rule S-FUN
505         = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
506         -- Match the args, and sub-match the results
507
508     go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
509         -- Otherwise defer to boxy matching
510         -- This covers TyConApp, AppTy, PredTy
511 \end{code}
512
513 Note [Sub-match]
514 ~~~~~~~~~~~~~~~~
515 Consider this
516         head :: [a] -> a
517         |- head xs : <rhobox>
518 We will do a boxySubMatchType between   a ~ <rhobox>
519 But we *don't* want to match [a |-> <rhobox>] because 
520     (a) The box should be filled in with a rho-type, but
521            but the returned substitution maps TyVars to boxy
522            *sigma* types
523     (b) In any case, the right final answer might be *either*
524            instantiate 'a' with a rho-type or a sigma type
525            head xs : Int   vs   head xs : forall b. b->b
526 So the matcher MUST NOT make a choice here.   In general, we only
527 bind a template type variable in boxyMatchType, not in boxySubMatchType.
528
529
530 \begin{code}
531 boxyMatchTypes 
532         :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
533         -> [BoxySigmaType]        -- Type to match
534         -> TvSubst                -- Substitution of the [TcTyVar] to BoxySigmaTypes
535
536 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
537 -- "Boxy types: inference for higher rank types and impredicativity"
538
539 -- Find a *boxy* substitution that makes the template look as much 
540 --      like the BoxySigmaType as possible.  
541 -- It's always ok to return an empty substitution; 
542 --      anything more is jam on the pudding
543 -- 
544 -- NB1: This is a pure, non-monadic function.  
545 --      It does no unification, and cannot fail
546 --
547 -- Precondition: the arg lengths are equal
548 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
549 --
550         
551 ------------
552 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
553   = ASSERT( length tmpl_tys == length boxy_tys )
554     boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
555         -- ToDo: add error context?
556
557 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
558   = subst
559 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
560   = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
561     boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
562 boxy_match_s tmpl_tvs _ boxy_tvs _ subst
563   = panic "boxy_match_s"        -- Lengths do not match
564     
565
566 ------------
567 boxy_match :: TcTyVarSet -> TcType      -- Template
568            -> TcTyVarSet                -- boxy_tvs: do not bind template tyvars to any of these
569            -> BoxySigmaType             -- Match against this type
570            -> TvSubst
571            -> TvSubst
572
573 -- The boxy_tvs argument prevents this match:
574 --      [a]  forall b. a  ~  forall b. b
575 -- We don't want to bind the template variable 'a'
576 -- to the quantified type variable 'b'!
577
578 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
579   = go orig_tmpl_ty orig_boxy_ty
580   where
581     go t_ty b_ty 
582         | Just t_ty' <- tcView t_ty = go t_ty' b_ty
583         | Just b_ty' <- tcView b_ty = go t_ty b_ty'
584
585     go ty1 ty2          -- C.f. the isSigmaTy case for boxySubMatchType
586         | isSigmaTy ty1
587         , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
588         , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
589         , equalLength tvs1 tvs2
590         = boxy_match (tmpl_tvs `delVarSetList` tvs1)    tau1 
591                      (boxy_tvs `extendVarSetList` tvs2) tau2 subst
592
593     go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
594         | tc1 == tc2 
595         , not $ isOpenSynTyCon tc1
596         = go_s tys1 tys2
597
598     go (FunTy arg1 res1) (FunTy arg2 res2)
599         = go_s [arg1,res1] [arg2,res2]
600
601     go t_ty b_ty
602         | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
603           Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
604           typeKind t2 `isSubKind` typeKind t1   -- Maintain invariant
605         = go_s [s1,t1] [s2,t2]
606
607     go (TyVarTy tv) b_ty
608         | tv `elemVarSet` tmpl_tvs      -- Template type variable in the template
609         , boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
610         , typeKind b_ty `isSubKind` tyVarKind tv  -- See Note [Matching kinds]
611         = extendTvSubst subst tv boxy_ty'
612         | otherwise
613         = subst                         -- Ignore others
614         where
615           boxy_ty' = case lookupTyVar subst tv of
616                         Nothing -> orig_boxy_ty
617                         Just ty -> ty `boxyLub` orig_boxy_ty
618
619     go _ (TyVarTy tv) | isMetaTyVar tv
620         = subst         -- Don't fail if the template has more info than the target!
621                         -- Otherwise, with tmpl_tvs = [a], matching (a -> Int) ~ (Bool -> beta)
622                         -- would fail to instantiate 'a', because the meta-type-variable
623                         -- beta is as yet un-filled-in
624         
625     go _ _ = emptyTvSubst       -- It's important to *fail* by returning the empty substitution
626         -- Example:  Tree a ~ Maybe Int
627         -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
628         -- misleading error messages.  An even more confusing case is
629         --           a -> b ~ Maybe Int
630         -- Then we do not want to bind (b |-> Int)!  It's always safe to discard bindings
631         -- from this pre-matching phase.
632
633     --------
634     go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
635
636
637 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
638 -- Combine boxy information from the two types
639 -- If there is a conflict, return the first
640 boxyLub orig_ty1 orig_ty2
641   = go orig_ty1 orig_ty2
642   where
643     go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
644     go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
645     go (TyConApp tc1 ts1) (TyConApp tc2 ts2) 
646       | tc1 == tc2, length ts1 == length ts2
647       = TyConApp tc1 (zipWith boxyLub ts1 ts2)
648
649     go (TyVarTy tv1) ty2                -- This is the whole point; 
650       | isTcTyVar tv1, isBoxyTyVar tv1  -- choose ty2 if ty2 is a box
651       = orig_ty2        
652
653     go ty1 (TyVarTy tv2)                -- Symmetrical case
654       | isTcTyVar tv2, isBoxyTyVar tv2
655       = orig_ty1        
656
657         -- Look inside type synonyms, but only if the naive version fails
658     go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
659                | Just ty2' <- tcView ty1 = go ty1 ty2'
660
661     -- For now, we don't look inside ForAlls, PredTys
662     go ty1 ty2 = orig_ty1       -- Default
663 \end{code}
664
665 Note [Matching kinds]
666 ~~~~~~~~~~~~~~~~~~~~~
667 The target type might legitimately not be a sub-kind of template.  
668 For example, suppose the target is simply a box with an OpenTypeKind, 
669 and the template is a type variable with LiftedTypeKind.  
670 Then it's ok (because the target type will later be refined).
671 We simply don't bind the template type variable.
672
673 It might also be that the kind mis-match is an error. For example,
674 suppose we match the template (a -> Int) against (Int# -> Int),
675 where the template type variable 'a' has LiftedTypeKind.  This
676 matching function does not fail; it simply doesn't bind the template.
677 Later stuff will fail.
678
679 %************************************************************************
680 %*                                                                      *
681                 Subsumption checking
682 %*                                                                      *
683 %************************************************************************
684
685 All the tcSub calls have the form
686         
687                 tcSub actual_ty expected_ty
688 which checks
689                 actual_ty <= expected_ty
690
691 That is, that a value of type actual_ty is acceptable in
692 a place expecting a value of type expected_ty.
693
694 It returns a coercion function 
695         co_fn :: actual_ty ~ expected_ty
696 which takes an HsExpr of type actual_ty into one of type
697 expected_ty.
698
699 \begin{code}
700 -----------------
701 tcSubExp :: InstOrigin -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper
702         -- (tcSub act exp) checks that 
703         --      act <= exp
704 tcSubExp orig actual_ty expected_ty
705   = -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
706     -- Adding the error context here leads to some very confusing error
707     -- messages, such as "can't match forall a. a->a with forall a. a->a"
708     -- Example is tcfail165: 
709     --      do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
710     --         putMVar var (show :: forall a. Show a => a -> String)
711     -- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
712     -- but after zonking it looks as if it does!
713     --
714     -- So instead I'm adding the error context when moving from tc_sub to u_tys
715
716     traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
717     tc_sub orig actual_ty actual_ty False expected_ty expected_ty
718
719 -----------------
720 tc_sub :: InstOrigin
721        -> BoxySigmaType         -- actual_ty, before expanding synonyms
722        -> BoxySigmaType         --              ..and after
723        -> InBox                 -- True <=> expected_ty is inside a box
724        -> BoxySigmaType         -- expected_ty, before
725        -> BoxySigmaType         --              ..and after
726        -> TcM HsWrapper
727                                 -- The acual_ty is never inside a box
728 -- IMPORTANT pre-condition: if the args contain foralls, the bound type 
729 --                          variables are visible non-monadically
730 --                          (i.e. tha args are sufficiently zonked)
731 -- This invariant is needed so that we can "see" the foralls, ad
732 -- e.g. in the SPEC rule where we just use splitSigmaTy 
733         
734 tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty
735   = traceTc (text "tc_sub" <+> ppr act_ty $$ ppr exp_ty) >>
736     tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
737         -- This indirection is just here to make 
738         -- it easy to insert a debug trace!
739
740 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
741   | Just exp_ty' <- tcView exp_ty = tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty'
742 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
743   | Just act_ty' <- tcView act_ty = tc_sub orig act_sty act_ty' exp_ib exp_sty exp_ty
744
745 -----------------------------------
746 -- Rule SBOXY, plus other cases when act_ty is a type variable
747 -- Just defer to boxy matching
748 -- This rule takes precedence over SKOL!
749 tc_sub1 orig act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
750   = do  { traceTc (text "tc_sub1 - case 1")
751         ; coi <- addSubCtxt orig act_sty exp_sty $
752                  uVar True False tv exp_ib exp_sty exp_ty
753         ; traceTc (case coi of 
754                         IdCo   -> text "tc_sub1 (Rule SBOXY) IdCo"
755                         ACo co -> text "tc_sub1 (Rule SBOXY) ACo" <+> ppr co)
756         ; return $ coiToHsWrapper coi
757         }
758
759 -----------------------------------
760 -- Skolemisation case (rule SKOL)
761 --      actual_ty:   d:Eq b => b->b
762 --      expected_ty: forall a. Ord a => a->a
763 --      co_fn e      /\a. \d2:Ord a. let d = eqFromOrd d2 in e
764
765 -- It is essential to do this *before* the specialisation case
766 -- Example:  f :: (Eq a => a->a) -> ...
767 --           g :: Ord b => b->b
768 -- Consider  f g !
769
770 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
771   | isSigmaTy exp_ty = do
772     { traceTc (text "tc_sub1 - case 2") ;
773     if exp_ib then      -- SKOL does not apply if exp_ty is inside a box
774         defer_to_boxy_matching orig act_sty act_ty exp_ib exp_sty exp_ty
775     else do 
776         { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
777                              tc_sub orig act_sty act_ty False body_exp_ty body_exp_ty
778         ; return (gen_fn <.> co_fn) }
779     }
780   where
781     act_tvs = tyVarsOfType act_ty
782                 -- It's really important to check for escape wrt 
783                 -- the free vars of both expected_ty *and* actual_ty
784
785 -----------------------------------
786 -- Specialisation case (rule ASPEC):
787 --      actual_ty:   forall a. Ord a => a->a
788 --      expected_ty: Int -> Int
789 --      co_fn e =    e Int dOrdInt
790
791 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
792 -- Implements the new SPEC rule in the Appendix of the paper
793 -- "Boxy types: inference for higher rank types and impredicativity"
794 -- (This appendix isn't in the published version.)
795 -- The idea is to *first* do pre-subsumption, and then full subsumption
796 -- Example:     forall a. a->a  <=  Int -> (forall b. Int)
797 --   Pre-subsumpion finds a|->Int, and that works fine, whereas
798 --   just running full subsumption would fail.
799   | isSigmaTy actual_ty
800   = do  { traceTc (text "tc_sub1 - case 3")
801         ;       -- Perform pre-subsumption, and instantiate
802                 -- the type with info from the pre-subsumption; 
803                 -- boxy tyvars if pre-subsumption gives no info
804           let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
805               tau_tvs = exactTyVarsOfType tau
806         ; inst_tys <- if exp_ib then    -- Inside a box, do not do clever stuff
807                         do { tyvars' <- mapM tcInstBoxyTyVar tyvars
808                            ; return (mkTyVarTys tyvars') }
809                       else              -- Outside, do clever stuff
810                         preSubType tyvars tau_tvs tau expected_ty
811         ; let subst' = zipOpenTvSubst tyvars inst_tys
812               tau'   = substTy subst' tau
813
814                 -- Perform a full subsumption check
815         ; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty, 
816                                                 ppr tyvars <+> ppr theta <+> ppr tau,
817                                                 ppr tau'])
818         ; co_fn2 <- tc_sub orig tau' tau' exp_ib exp_sty expected_ty
819
820                 -- Deal with the dictionaries
821         ; co_fn1 <- instCall orig inst_tys (substTheta subst' theta)
822         ; return (co_fn2 <.> co_fn1) }
823
824 -----------------------------------
825 -- Function case (rule F1)
826 tc_sub1 orig act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
827   = do { traceTc (text "tc_sub1 - case 4")
828        ; tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
829        }
830
831 -- Function case (rule F2)
832 tc_sub1 orig act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
833   | isBoxyTyVar exp_tv
834   = do  { traceTc (text "tc_sub1 - case 5")
835         ; cts <- readMetaTyVar exp_tv
836         ; case cts of
837             Indirect ty -> tc_sub orig act_sty act_ty True exp_sty ty
838             Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
839                         ; tc_sub_funs orig act_arg act_res True arg_ty res_ty } }
840  where
841     mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
842     mk_res_ty other = panic "TcUnify.mk_res_ty3"
843     fun_kinds = [argTypeKind, openTypeKind]
844
845 -- Everything else: defer to boxy matching
846 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty@(TyVarTy exp_tv)
847   = do { traceTc (text "tc_sub1 - case 6a" <+> ppr [isBoxyTyVar exp_tv, isMetaTyVar exp_tv, isSkolemTyVar exp_tv, isExistentialTyVar exp_tv,isSigTyVar exp_tv] )
848        ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
849        }
850
851 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
852   = do { traceTc (text "tc_sub1 - case 6")
853        ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
854        }
855
856 -----------------------------------
857 defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
858   = do  { coi <- addSubCtxt orig act_sty exp_sty $
859                  u_tys True False act_sty actual_ty exp_ib exp_sty expected_ty
860         ; return $ coiToHsWrapper coi }
861
862 -----------------------------------
863 tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
864   = do  { arg_coi   <- addSubCtxt orig act_arg exp_arg $
865                        uTysOuter False act_arg exp_ib exp_arg
866         ; co_fn_res <- tc_sub orig act_res act_res exp_ib exp_res exp_res
867         ; wrapper1  <- wrapFunResCoercion [exp_arg] co_fn_res 
868         ; let wrapper2 = case arg_coi of 
869                                 IdCo   -> idHsWrapper
870                                 ACo co -> WpCo $ FunTy co act_res
871         ; return (wrapper1 <.> wrapper2) }
872
873 -----------------------------------
874 wrapFunResCoercion 
875         :: [TcType]     -- Type of args
876         -> HsWrapper    -- HsExpr a -> HsExpr b
877         -> TcM HsWrapper        -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
878 wrapFunResCoercion arg_tys co_fn_res
879   | isIdHsWrapper co_fn_res 
880   = return idHsWrapper
881   | null arg_tys           
882   = return co_fn_res
883   | otherwise
884   = do  { arg_ids <- newSysLocalIds FSLIT("sub") arg_tys
885         ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
886 \end{code}
887
888
889
890 %************************************************************************
891 %*                                                                      *
892 \subsection{Generalisation}
893 %*                                                                      *
894 %************************************************************************
895
896 \begin{code}
897 tcGen :: BoxySigmaType                          -- expected_ty
898       -> TcTyVarSet                             -- Extra tyvars that the universally
899                                                 --      quantified tyvars of expected_ty
900                                                 --      must not be unified
901       -> ([TcTyVar] -> BoxyRhoType -> TcM result)
902       -> TcM (HsWrapper, result)
903         -- The expression has type: spec_ty -> expected_ty
904
905 tcGen expected_ty extra_tvs thing_inside        -- We expect expected_ty to be a forall-type
906                                                 -- If not, the call is a no-op
907   = do  { traceTc (text "tcGen")        
908                 -- We want the GenSkol info in the skolemised type variables to 
909                 -- mention the *instantiated* tyvar names, so that we get a
910                 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
911                 -- Hence the tiresome but innocuous fixM
912         ; ((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
913                 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
914                         -- Get loation from monad, not from expected_ty
915                    ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty)
916                    ; return ((forall_tvs, theta, rho_ty), skol_info) })
917
918         ; when debugIsOn $
919               traceTc (text "tcGen" <+> vcat [
920                            text "extra_tvs" <+> ppr extra_tvs,
921                            text "expected_ty" <+> ppr expected_ty,
922                            text "inst ty" <+> ppr tvs' <+> ppr theta'
923                                <+> ppr rho',
924                            text "free_tvs" <+> ppr free_tvs])
925
926         -- Type-check the arg and unify with poly type
927         ; (result, lie) <- getLIE (thing_inside tvs' rho')
928
929         -- Check that the "forall_tvs" havn't been constrained
930         -- The interesting bit here is that we must include the free variables
931         -- of the expected_ty.  Here's an example:
932         --       runST (newVar True)
933         -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
934         -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
935         -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
936         -- So now s' isn't unconstrained because it's linked to a.
937         -- Conclusion: include the free vars of the expected_ty in the
938         -- list of "free vars" for the signature check.
939
940         ; loc <- getInstLoc (SigOrigin skol_info)
941         ; dicts <- newDictBndrs loc theta'      -- Includes equalities
942         ; inst_binds <- tcSimplifyCheck loc tvs' dicts lie
943
944         ; checkSigTyVarsWrt free_tvs tvs'
945         ; traceTc (text "tcGen:done")
946
947         ; let
948             -- The WpLet binds any Insts which came out of the simplification.
949             dict_vars = map instToVar dicts
950             co_fn = mkWpTyLams tvs' <.> mkWpLams dict_vars <.> WpLet inst_binds
951         ; return (co_fn, result) }
952   where
953     free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
954 \end{code}
955
956     
957
958 %************************************************************************
959 %*                                                                      *
960                 Boxy unification
961 %*                                                                      *
962 %************************************************************************
963
964 The exported functions are all defined as versions of some
965 non-exported generic functions.
966
967 \begin{code}
968 boxyUnify :: BoxyType -> BoxyType -> TcM CoercionI
969 -- Acutal and expected, respectively
970 boxyUnify ty1 ty2 
971   = addErrCtxtM (unifyCtxt ty1 ty2) $
972     uTysOuter False ty1 False ty2
973
974 ---------------
975 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM [CoercionI] 
976 -- Arguments should have equal length
977 -- Acutal and expected types
978 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
979
980 ---------------
981 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
982 -- No boxes expected inside these types
983 -- Acutal and expected types
984 unifyType ty1 ty2       -- ty1 expected, ty2 inferred
985   = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
986     ASSERT2( not (isBoxyTy ty2), ppr ty2 )
987     addErrCtxtM (unifyCtxt ty1 ty2) $
988     uTysOuter True ty1 True ty2
989
990 ---------------
991 unifyPred :: PredType -> PredType -> TcM CoercionI
992 -- Acutal and expected types
993 unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
994                         uPred True True p1 True p2
995
996 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
997 -- Acutal and expected types
998 unifyTheta theta1 theta2
999   = do  { checkTc (equalLength theta1 theta2)
1000                   (vcat [ptext SLIT("Contexts differ in length"),
1001                          nest 2 $ parens $ ptext SLIT("Use -fglasgow-exts to allow this")])
1002         ; uList unifyPred theta1 theta2 
1003         }
1004
1005 ---------------
1006 uList :: (a -> a -> TcM b)
1007        -> [a] -> [a] -> TcM [b]
1008 -- Unify corresponding elements of two lists of types, which
1009 -- should be of equal length.  We charge down the list explicitly so that
1010 -- we can complain if their lengths differ.
1011 uList unify []         []         = return []
1012 uList unify (ty1:tys1) (ty2:tys2) = do { x  <- unify ty1 ty2; 
1013                                        ; xs <- uList unify tys1 tys2 
1014                                        ; return (x:xs)
1015                                        }
1016 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
1017 \end{code}
1018
1019 @unifyTypeList@ takes a single list of @TauType@s and unifies them
1020 all together.  It is used, for example, when typechecking explicit
1021 lists, when all the elts should be of the same type.
1022
1023 \begin{code}
1024 unifyTypeList :: [TcTauType] -> TcM ()
1025 unifyTypeList []                 = return ()
1026 unifyTypeList [ty]               = return ()
1027 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
1028                                       ; unifyTypeList tys }
1029 \end{code}
1030
1031 %************************************************************************
1032 %*                                                                      *
1033 \subsection[Unify-uTys]{@uTys@: getting down to business}
1034 %*                                                                      *
1035 %************************************************************************
1036
1037 @uTys@ is the heart of the unifier.  Each arg occurs twice, because
1038 we want to report errors in terms of synomyms if possible.  The first of
1039 the pair is used in error messages only; it is always the same as the
1040 second, except that if the first is a synonym then the second may be a
1041 de-synonym'd version.  This way we get better error messages.
1042
1043 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
1044
1045 \begin{code}
1046 type SwapFlag = Bool
1047         -- False <=> the two args are (actual, expected) respectively
1048         -- True  <=> the two args are (expected, actual) respectively
1049
1050 type InBox = Bool       -- True  <=> we are inside a box
1051                         -- False <=> we are outside a box
1052         -- The importance of this is that if we get "filled-box meets 
1053         -- filled-box", we'll look into the boxes and unify... but
1054         -- we must not allow polytypes.  But if we are in a box on
1055         -- just one side, then we can allow polytypes
1056
1057 type Outer = Bool       -- True <=> this is the outer level of a unification
1058                         --          so that the types being unified are the
1059                         --          very ones we began with, not some sub
1060                         --          component or synonym expansion
1061 -- The idea is that if Outer is true then unifyMisMatch should
1062 -- pop the context to remove the "Expected/Acutal" context
1063
1064 uTysOuter, uTys
1065      :: InBox -> TcType -- ty1 is the *actual*   type
1066      -> InBox -> TcType -- ty2 is the *expected* type
1067      -> TcM CoercionI
1068 uTysOuter nb1 ty1 nb2 ty2 
1069         = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
1070              ; u_tys True nb1 ty1 ty1 nb2 ty2 ty2 }
1071 uTys nb1 ty1 nb2 ty2 
1072         = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
1073              ; u_tys False nb1 ty1 ty1 nb2 ty2 ty2 }
1074
1075
1076 --------------
1077 uTys_s :: InBox -> [TcType]     -- tys1 are the *actual*   types
1078        -> InBox -> [TcType]     -- tys2 are the *expected* types
1079        -> TcM [CoercionI] 
1080 uTys_s nb1 []         nb2 []         = return []
1081 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { coi <- uTys nb1 ty1 nb2 ty2
1082                                           ; cois <- uTys_s nb1 tys1 nb2 tys2 
1083                                           ; return (coi:cois)
1084                                           }
1085 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
1086
1087 --------------
1088 u_tys :: Outer
1089       -> InBox -> TcType -> TcType      -- ty1 is the *actual* type
1090       -> InBox -> TcType -> TcType      -- ty2 is the *expected* type
1091       -> TcM CoercionI
1092
1093 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
1094   = do { traceTc (text "u_tys " <+> ppr ty1 <+> text " " <+> ppr ty2)
1095        ; coi <- go outer ty1 ty2
1096        ; traceTc (case coi of
1097                         ACo co -> text "u_tys yields coercion: " <+> ppr co     
1098                         IdCo   -> text "u_tys yields no coercion")
1099        ; return coi
1100        }
1101   where 
1102
1103     go :: Outer -> TcType -> TcType -> TcM CoercionI
1104     go outer ty1 ty2 =
1105         do { traceTc (text "go " <+> ppr orig_ty1 <+> text "/" <+> ppr ty1
1106                          <+> ppr orig_ty2 <+> text "/" <+>  ppr ty2)
1107            ; go1 outer ty1 ty2
1108            }
1109            
1110     go1 :: Outer -> TcType -> TcType -> TcM CoercionI
1111         -- Always expand synonyms: see Note [Unification and synonyms]
1112         -- (this also throws away FTVs)
1113     go1 outer ty1 ty2 
1114       | Just ty1' <- tcView ty1 = go False ty1' ty2
1115       | Just ty2' <- tcView ty2 = go False ty1 ty2'
1116
1117         -- Variables; go for uVar
1118     go1 outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
1119     go1 outer ty1 (TyVarTy tyvar2) = uVar outer True  tyvar2 nb1 orig_ty1 ty1
1120                                 -- "True" means args swapped
1121
1122         -- The case for sigma-types must *follow* the variable cases
1123         -- because a boxy variable can be filed with a polytype;
1124         -- but must precede FunTy, because ((?x::Int) => ty) look
1125         -- like a FunTy; there isn't necy a forall at the top
1126     go1 _ ty1 ty2
1127       | isSigmaTy ty1 || isSigmaTy ty2
1128       = do   { traceTc (text "We have sigma types: equalLength" <+> ppr tvs1 <+> ppr tvs2)
1129              ; unless (equalLength tvs1 tvs2)
1130                       (unifyMisMatch outer False orig_ty1 orig_ty2)
1131              ; traceTc (text "We're past the first length test")
1132              ; tvs <- tcInstSkolTyVars UnkSkol tvs1     -- Not a helpful SkolemInfo
1133                         -- Get location from monad, not from tvs1
1134              ; let tys      = mkTyVarTys tvs
1135                    in_scope = mkInScopeSet (mkVarSet tvs)
1136                    phi1   = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
1137                    phi2   = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
1138                    (theta1,tau1) = tcSplitPhiTy phi1
1139                    (theta2,tau2) = tcSplitPhiTy phi2
1140
1141              ; addErrCtxtM (unifyForAllCtxt tvs phi1 phi2) $ do
1142              { unless (equalLength theta1 theta2)
1143                       (unifyMisMatch outer False orig_ty1 orig_ty2)
1144              
1145              ; cois <- uPreds False nb1 theta1 nb2 theta2 -- TOMDO: do something with these pred_cois
1146              ; traceTc (text "TOMDO!")
1147              ; coi <- uTys nb1 tau1 nb2 tau2
1148
1149                 -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
1150              ; free_tvs <- zonkTcTyVarsAndFV (varSetElems (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2))
1151              ; when (any (`elemVarSet` free_tvs) tvs)
1152                    (bleatEscapedTvs free_tvs tvs tvs)
1153
1154                 -- If both sides are inside a box, we are in a "box-meets-box"
1155                 -- situation, and we should not have a polytype at all.  
1156                 -- If we get here we have two boxes, already filled with
1157                 -- the same polytype... but it should be a monotype.
1158                 -- This check comes last, because the error message is 
1159                 -- extremely unhelpful.  
1160              ; when (nb1 && nb2) (notMonoType ty1)
1161              ; return coi
1162              }}
1163       where
1164         (tvs1, body1) = tcSplitForAllTys ty1
1165         (tvs2, body2) = tcSplitForAllTys ty2
1166
1167         -- Predicates
1168     go1 outer (PredTy p1) (PredTy p2) 
1169         = uPred False nb1 p1 nb2 p2
1170
1171         -- Type constructors must match
1172     go1 _ (TyConApp con1 tys1) (TyConApp con2 tys2)
1173       | con1 == con2 && not (isOpenSynTyCon con1)
1174       = do { cois <- uTys_s nb1 tys1 nb2 tys2
1175            ; return $ mkTyConAppCoI con1 tys1 cois
1176            }
1177         -- See Note [TyCon app]
1178       | con1 == con2 && identicalOpenSynTyConApp
1179       = do { cois <- uTys_s nb1 tys1' nb2 tys2'
1180            ; return $ mkTyConAppCoI con1 tys1 (replicate n IdCo ++ cois)
1181            }
1182       where
1183         n                        = tyConArity con1
1184         (idxTys1, tys1')         = splitAt n tys1
1185         (idxTys2, tys2')         = splitAt n tys2
1186         identicalOpenSynTyConApp = idxTys1 `tcEqTypes` idxTys2
1187         -- See Note [OpenSynTyCon app]
1188
1189         -- Functions; just check the two parts
1190     go1 _ (FunTy fun1 arg1) (FunTy fun2 arg2)
1191       = do { coi_l <- uTys nb1 fun1 nb2 fun2
1192            ; coi_r <- uTys nb1 arg1 nb2 arg2 
1193            ; return $ mkFunTyCoI fun1 coi_l arg1 coi_r
1194            }
1195
1196         -- Applications need a bit of care!
1197         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
1198         -- NB: we've already dealt with type variables and Notes,
1199         -- so if one type is an App the other one jolly well better be too
1200     go1 outer (AppTy s1 t1) ty2
1201       | Just (s2,t2) <- tcSplitAppTy_maybe ty2
1202       = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1203            ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1204
1205         -- Now the same, but the other way round
1206         -- Don't swap the types, because the error messages get worse
1207     go1 outer ty1 (AppTy s2 t2)
1208       | Just (s1,t1) <- tcSplitAppTy_maybe ty1
1209       = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2 
1210            ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1211
1212         -- One or both outermost constructors are type family applications.
1213         -- If we can normalise them away, proceed as usual; otherwise, we
1214         -- need to defer unification by generating a wanted equality constraint.
1215     go1 outer ty1 ty2
1216       | ty1_is_fun || ty2_is_fun
1217       = do { (coi1, ty1') <- if ty1_is_fun then tcNormaliseFamInst ty1 
1218                                            else return (IdCo, ty1)
1219            ; (coi2, ty2') <- if ty2_is_fun then tcNormaliseFamInst ty2 
1220                                            else return (IdCo, ty2)
1221            ; coi <- if isOpenSynTyConApp ty1' || isOpenSynTyConApp ty2'
1222                     then do { -- One type family app can't be reduced yet
1223                               -- => defer
1224                             ; ty1'' <- zonkTcType ty1'
1225                             ; ty2'' <- zonkTcType ty2'
1226                             ; if tcEqType ty1'' ty2'' 
1227                               then return IdCo
1228                               else -- see [Deferred Unification]
1229                                 defer_unification outer False orig_ty1 orig_ty2
1230                             }
1231                      else -- unification can proceed
1232                           go outer ty1' ty2'
1233            ; return $ coi1 `mkTransCoI` coi `mkTransCoI` (mkSymCoI coi2)
1234            }
1235         where
1236           ty1_is_fun = isOpenSynTyConApp ty1
1237           ty2_is_fun = isOpenSynTyConApp ty2
1238
1239         -- Anything else fails  
1240     go1 outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
1241
1242
1243 ----------
1244 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
1245   | n1 == n2 = 
1246         do { coi <- uTys nb1 t1 nb2 t2
1247            ; return $ mkIParamPredCoI n1 coi
1248            }
1249 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
1250   | c1 == c2 = 
1251         do { cois <- uTys_s nb1 tys1 nb2 tys2           -- Guaranteed equal lengths because the kinds check
1252            ; return $ mkClassPPredCoI c1 tys1 cois
1253            }
1254 uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
1255
1256 uPreds outer nb1 []       nb2 []       = return []
1257 uPreds outer nb1 (p1:ps1) nb2 (p2:ps2) = 
1258         do { coi  <- uPred outer nb1 p1 nb2 p2
1259            ; cois <- uPreds outer nb1 ps1 nb2 ps2
1260            ; return (coi:cois)
1261            }
1262 uPreds outer nb1 ps1      nb2 ps2      = panic "uPreds"
1263 \end{code}
1264
1265 Note [TyCon app]
1266 ~~~~~~~~~~~~~~~~
1267 When we find two TyConApps, the argument lists are guaranteed equal
1268 length.  Reason: intially the kinds of the two types to be unified is
1269 the same. The only way it can become not the same is when unifying two
1270 AppTys (f1 a1):=:(f2 a2).  In that case there can't be a TyConApp in
1271 the f1,f2 (because it'd absorb the app).  If we unify f1:=:f2 first,
1272 which we do, that ensures that f1,f2 have the same kind; and that
1273 means a1,a2 have the same kind.  And now the argument repeats.
1274
1275 Note [OpenSynTyCon app]
1276 ~~~~~~~~~~~~~~~~~~~~~~~
1277 Given
1278
1279   type family T a :: * -> *
1280
1281 the two types (T () a) and (T () Int) must unify, even if there are
1282 no type instances for T at all.  Should we just turn them into an
1283 equality (T () a ~ T () Int)?  I don't think so.  We currently try to 
1284 eagerly unify everything we can before generating equalities; otherwise,
1285 we could turn the unification of [Int] with [a] into an equality, too.
1286
1287 Note [Unification and synonyms]
1288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1289 If you are tempted to make a short cut on synonyms, as in this
1290 pseudocode...
1291
1292 \begin{verbatim}
1293 -- NO   uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1294 -- NO     = if (con1 == con2) then
1295 -- NO   -- Good news!  Same synonym constructors, so we can shortcut
1296 -- NO   -- by unifying their arguments and ignoring their expansions.
1297 -- NO   unifyTypepeLists args1 args2
1298 -- NO    else
1299 -- NO   -- Never mind.  Just expand them and try again
1300 -- NO   uTys ty1 ty2
1301 \end{verbatim}
1302
1303 then THINK AGAIN.  Here is the whole story, as detected and reported
1304 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1305 \begin{quotation}
1306 Here's a test program that should detect the problem:
1307
1308 \begin{verbatim}
1309         type Bogus a = Int
1310         x = (1 :: Bogus Char) :: Bogus Bool
1311 \end{verbatim}
1312
1313 The problem with [the attempted shortcut code] is that
1314 \begin{verbatim}
1315         con1 == con2
1316 \end{verbatim}
1317 is not a sufficient condition to be able to use the shortcut!
1318 You also need to know that the type synonym actually USES all
1319 its arguments.  For example, consider the following type synonym
1320 which does not use all its arguments.
1321 \begin{verbatim}
1322         type Bogus a = Int
1323 \end{verbatim}
1324
1325 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1326 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1327 would fail, even though the expanded forms (both \tr{Int}) should
1328 match.
1329
1330 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1331 unnecessarily bind \tr{t} to \tr{Char}.
1332
1333 ... You could explicitly test for the problem synonyms and mark them
1334 somehow as needing expansion, perhaps also issuing a warning to the
1335 user.
1336 \end{quotation}
1337
1338
1339 %************************************************************************
1340 %*                                                                      *
1341 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1342 %*                                                                      *
1343 %************************************************************************
1344
1345 @uVar@ is called when at least one of the types being unified is a
1346 variable.  It does {\em not} assume that the variable is a fixed point
1347 of the substitution; rather, notice that @uVar@ (defined below) nips
1348 back into @uTys@ if it turns out that the variable is already bound.
1349
1350 \begin{code}
1351 uVar :: Outer
1352      -> SwapFlag        -- False => tyvar is the "actual" (ty is "expected")
1353                         -- True  => ty is the "actual" (tyvar is "expected")
1354      -> TcTyVar
1355      -> InBox           -- True <=> definitely no boxes in t2
1356      -> TcTauType -> TcTauType  -- printing and real versions
1357      -> TcM CoercionI
1358
1359 uVar outer swapped tv1 nb2 ps_ty2 ty2
1360   = do  { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1361                         | otherwise = brackets (equals <+> ppr ty2)
1362         ; traceTc (text "uVar" <+> ppr swapped <+> 
1363                         sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1364                                 nest 2 (ptext SLIT(" <-> ")),
1365                              ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1366         ; details <- lookupTcTyVar tv1
1367         ; case details of
1368             IndirectTv ty1 
1369                 | swapped   -> u_tys outer nb2  ps_ty2 ty2 True ty1    ty1      -- Swap back
1370                 | otherwise -> u_tys outer True ty1    ty1 nb2  ps_ty2 ty2      -- Same order
1371                         -- The 'True' here says that ty1 is now inside a box
1372             DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1373         }
1374
1375 ----------------
1376 uUnfilledVar :: Outer
1377              -> SwapFlag
1378              -> TcTyVar -> TcTyVarDetails       -- Tyvar 1
1379              -> TcTauType -> TcTauType          -- Type 2
1380              -> TcM CoercionI
1381 -- Invariant: tyvar 1 is not unified with anything
1382
1383 uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1384   | Just ty2' <- tcView ty2
1385   =     -- Expand synonyms; ignore FTVs
1386     uUnfilledVar False swapped tv1 details1 ps_ty2 ty2'
1387
1388 uUnfilledVar outer swapped tv1 details1 ps_ty2 (TyVarTy tv2)
1389   | tv1 == tv2  -- Same type variable => no-op (but watch out for the boxy case)
1390   = case details1 of
1391         MetaTv BoxTv ref1  -- A boxy type variable meets itself;
1392                            -- this is box-meets-box, so fill in with a tau-type
1393               -> do { tau_tv <- tcInstTyVar tv1
1394                     ; updateMeta tv1 ref1 (mkTyVarTy tau_tv) 
1395                     ; return IdCo
1396                     }
1397         other -> return IdCo    -- No-op
1398
1399   | otherwise  -- Distinct type variables
1400   = do  { lookup2 <- lookupTcTyVar tv2
1401         ; case lookup2 of
1402             IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 ty2' ty2'
1403             DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1404         }
1405
1406 uUnfilledVar outer swapped tv1 details1 ps_ty2 non_var_ty2
1407   =     -- ty2 is not a type variable
1408     case details1 of    
1409       MetaTv (SigTv _) _ -> rigid_variable
1410       MetaTv info ref1   -> 
1411         uMetaVar outer swapped tv1 info ref1 ps_ty2 non_var_ty2 
1412       SkolemTv _         -> rigid_variable
1413   where
1414     rigid_variable 
1415       | isOpenSynTyConApp non_var_ty2
1416       =           -- 'non_var_ty2's outermost constructor is a type family,
1417                   -- which we may may be able to normalise
1418         do { (coi2, ty2') <- tcNormaliseFamInst non_var_ty2
1419            ; case coi2 of
1420                IdCo   ->   -- no progress, but maybe after other instantiations
1421                          defer_unification outer swapped (TyVarTy tv1) ps_ty2
1422                ACo co ->   -- progress: so lets try again
1423                  do { traceTc $
1424                         ppr co <+> text "::"<+> ppr non_var_ty2 <+> text "~" <+>
1425                         ppr ty2'
1426                     ; coi <- uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2'
1427                     ; let coi2' = (if swapped then id else mkSymCoI) coi2
1428                     ; return $ coi2' `mkTransCoI` coi
1429                     }
1430            }
1431       | SkolemTv RuntimeUnkSkol <- details1
1432                    -- runtime unknown will never match
1433       = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1434       | otherwise  -- defer as a given equality may still resolve this
1435       = defer_unification outer swapped (TyVarTy tv1) ps_ty2
1436 \end{code}
1437
1438 Note [Deferred Unification]
1439 ~~~~~~~~~~~~~~~~~~~~
1440 We may encounter a unification ty1 = ty2 that cannot be performed syntactically,
1441 and yet its consistency is undetermined. Previously, there was no way to still
1442 make it consistent. So a mismatch error was issued. 
1443
1444 Now these unfications are deferred until constraint simplification, where type
1445 family instances and given equations may (or may not) establish the consistency.
1446 Deferred unifications are of the form 
1447                 F ... ~ ... 
1448 or              x ~ ... 
1449 where F is a type function and x is a type variable.   
1450 E.g. 
1451         id :: x ~ y => x -> y
1452         id e = e
1453
1454 involves the unfication x = y. It is deferred until we bring into account the
1455 context x ~ y to establish that it holds.
1456
1457 If available, we defer original types (rather than those where closed type
1458 synonyms have already been expanded via tcCoreView).  This is, as usual, to
1459 improve error messages.
1460
1461 We need to both 'unBox' and zonk deferred types.  We need to unBox as
1462 functions, such as TcExpr.tcMonoExpr promise to fill boxes in the expected
1463 type.  We need to zonk as the types go into the kind of the coercion variable
1464 `cotv' and those are not zonked in Inst.zonkInst.  (Maybe it would be better
1465 to zonk in zonInst instead.  Would that be sufficient?)
1466
1467 \begin{code}
1468 defer_unification :: Bool               -- pop innermost context?
1469                   -> SwapFlag
1470                   -> TcType
1471                   -> TcType
1472                   -> TcM CoercionI
1473 defer_unification outer True ty1 ty2
1474   = defer_unification outer False ty2 ty1
1475 defer_unification outer False ty1 ty2
1476   = do  { ty1' <- unBox ty1 >>= zonkTcType      -- unbox *and* zonk..
1477         ; ty2' <- unBox ty2 >>= zonkTcType      -- ..see preceding note
1478         ; traceTc $ text "deferring:" <+> ppr ty1 <+> text "~" <+> ppr ty2
1479         ; cotv <- newMetaCoVar ty1' ty2'
1480                 -- put ty1 ~ ty2 in LIE
1481                 -- Left means "wanted"
1482         ; inst <- (if outer then popErrCtxt else id) $
1483                   mkEqInst (EqPred ty1' ty2') (Left cotv)
1484         ; extendLIE inst 
1485         ; return $ ACo $ TyVarTy cotv  }
1486
1487 ----------------
1488 uMetaVar :: Bool               -- pop innermost context?
1489          -> SwapFlag
1490          -> TcTyVar -> BoxInfo -> IORef MetaDetails
1491          -> TcType -> TcType
1492          -> TcM CoercionI
1493 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1494 -- ty2 is not a type variable
1495
1496 uMetaVar outer swapped tv1 BoxTv ref1 ps_ty2 non_var_ty2
1497   =     -- tv1 is a BoxTv.  So we must unbox ty2, to ensure
1498         -- that any boxes in ty2 are filled with monotypes
1499         -- 
1500         -- It should not be the case that tv1 occurs in ty2
1501         -- (i.e. no occurs check should be needed), but if perchance
1502         -- it does, the unbox operation will fill it, and the debug code
1503         -- checks for that.
1504     do { final_ty <- unBox ps_ty2
1505        ; when debugIsOn $ do
1506            { meta_details <- readMutVar ref1
1507            ; case meta_details of
1508                  Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1509                                 return () -- This really should *not* happen
1510                  Flexi -> return ()
1511            }
1512         ; checkUpdateMeta swapped tv1 ref1 final_ty
1513         ; return IdCo
1514         }
1515
1516 uMetaVar outer swapped tv1 info1 ref1 ps_ty2 non_var_ty2
1517   = do  { -- Occurs check + monotype check
1518         ; mb_final_ty <- checkTauTvUpdate tv1 ps_ty2
1519         ; case mb_final_ty of
1520             Nothing       ->    -- tv1 occured in type family parameter
1521               defer_unification outer swapped (mkTyVarTy tv1) ps_ty2
1522             Just final_ty -> 
1523               do { checkUpdateMeta swapped tv1 ref1 final_ty 
1524                  ; return IdCo
1525                  }
1526         }
1527
1528 ----------------
1529 uUnfilledVars :: Outer
1530               -> SwapFlag
1531               -> TcTyVar -> TcTyVarDetails      -- Tyvar 1
1532               -> TcTyVar -> TcTyVarDetails      -- Tyvar 2
1533               -> TcM CoercionI
1534 -- Invarant: The type variables are distinct, 
1535 --           Neither is filled in yet
1536 --           They might be boxy or not
1537
1538 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1539   = -- see [Deferred Unification]
1540     defer_unification outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1541
1542 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1543   = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2) >> return IdCo
1544 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1545   = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1) >> return IdCo
1546
1547 -- ToDo: this function seems too long for what it acutally does!
1548 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1549   = case (info1, info2) of
1550         (BoxTv,   BoxTv)   -> box_meets_box >> return IdCo
1551
1552         -- If a box meets a TauTv, but the fomer has the smaller kind
1553         -- then we must create a fresh TauTv with the smaller kind
1554         (_,       BoxTv)   | k1_sub_k2 -> update_tv2 >> return IdCo
1555                            | otherwise -> box_meets_box >> return IdCo
1556         (BoxTv,   _    )   | k2_sub_k1 -> update_tv1 >> return IdCo
1557                            | otherwise -> box_meets_box >> return IdCo
1558
1559         -- Avoid SigTvs if poss
1560         (SigTv _, _      ) | k1_sub_k2 -> update_tv2 >> return IdCo
1561         (_,       SigTv _) | k2_sub_k1 -> update_tv1 >> return IdCo
1562
1563         (_,   _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1564                                 then update_tv1 >> return IdCo  -- Same kinds
1565                                 else update_tv2 >> return IdCo
1566                  | k2_sub_k1 -> update_tv1 >> return IdCo
1567                  | otherwise -> kind_err >> return IdCo
1568
1569         -- Update the variable with least kind info
1570         -- See notes on type inference in Kind.lhs
1571         -- The "nicer to" part only applies if the two kinds are the same,
1572         -- so we can choose which to do.
1573   where
1574         -- Kinds should be guaranteed ok at this point
1575     update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1576     update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1577
1578     box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1579                                 then fill_from tv2
1580                                 else fill_from tv1
1581                   | k2_sub_k1 = fill_from tv2
1582                   | otherwise = kind_err
1583
1584         -- Update *both* tyvars with a TauTv whose name and kind
1585         -- are gotten from tv (avoid losing nice names is poss)
1586     fill_from tv = do { tv' <- tcInstTyVar tv
1587                       ; let tau_ty = mkTyVarTy tv'
1588                       ; updateMeta tv1 ref1 tau_ty
1589                       ; updateMeta tv2 ref2 tau_ty }
1590
1591     kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2))  $
1592                unifyKindMisMatch k1 k2
1593
1594     k1 = tyVarKind tv1
1595     k2 = tyVarKind tv2
1596     k1_sub_k2 = k1 `isSubKind` k2
1597     k2_sub_k1 = k2 `isSubKind` k1
1598
1599     nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1600         -- Try to update sys-y type variables in preference to ones
1601         -- gotten (say) by instantiating a polymorphic function with
1602         -- a user-written type sig
1603 \end{code}
1604
1605 \begin{code}
1606 refineBox :: TcType -> TcM TcType
1607 -- Unbox the outer box of a boxy type (if any)
1608 refineBox ty@(TyVarTy box_tv) 
1609   | isMetaTyVar box_tv
1610   = do  { cts <- readMetaTyVar box_tv
1611         ; case cts of
1612                 Flexi -> return ty
1613                 Indirect ty -> return ty } 
1614 refineBox other_ty = return other_ty
1615
1616 refineBoxToTau :: TcType -> TcM TcType
1617 -- Unbox the outer box of a boxy type, filling with a monotype if it is empty
1618 -- Like refineBox except for the "fill with monotype" part.
1619 refineBoxToTau ty@(TyVarTy box_tv) 
1620   | isMetaTyVar box_tv
1621   , MetaTv BoxTv ref <- tcTyVarDetails box_tv
1622   = do  { cts <- readMutVar ref
1623         ; case cts of
1624                 Flexi -> fillBoxWithTau box_tv ref
1625                 Indirect ty -> return ty } 
1626 refineBoxToTau other_ty = return other_ty
1627
1628 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1629 -- Subtle... we must zap the boxy res_ty
1630 -- to kind * before using it to instantiate a LitInst
1631 -- Calling unBox instead doesn't do the job, because the box
1632 -- often has an openTypeKind, and we don't want to instantiate
1633 -- with that type.
1634 zapToMonotype res_ty
1635   = do  { res_tau <- newFlexiTyVarTy liftedTypeKind
1636         ; boxyUnify res_tau res_ty
1637         ; return res_tau }
1638
1639 unBox :: BoxyType -> TcM TcType
1640 -- unBox implements the judgement 
1641 --      |- s' ~ box(s)
1642 -- with input s', and result s
1643 -- 
1644 -- It removes all boxes from the input type, returning a non-boxy type.
1645 -- A filled box in the type can only contain a monotype; unBox fails if not
1646 -- The type can have empty boxes, which unBox fills with a monotype
1647 --
1648 -- Compare this wth checkTauTvUpdate
1649 --
1650 -- For once, it's safe to treat synonyms as opaque!
1651
1652 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1653 unBox (AppTy f a)       = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1654 unBox (FunTy f a)       = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1655 unBox (PredTy p)        = do { p' <- unBoxPred p; return (PredTy p') }
1656 unBox (ForAllTy tv ty)  = ASSERT( isImmutableTyVar tv )
1657                           do { ty' <- unBox ty; return (ForAllTy tv ty') }
1658 unBox (TyVarTy tv)
1659   | isTcTyVar tv                                -- It's a boxy type variable
1660   , MetaTv BoxTv ref <- tcTyVarDetails tv       -- NB: non-TcTyVars are possible
1661   = do  { cts <- readMutVar ref                 --     under nested quantifiers
1662         ; case cts of
1663             Flexi -> fillBoxWithTau tv ref
1664             Indirect ty -> do { non_boxy_ty <- unBox ty
1665                               ; if isTauTy non_boxy_ty 
1666                                 then return non_boxy_ty
1667                                 else notMonoType non_boxy_ty }
1668         }
1669   | otherwise   -- Skolems, and meta-tau-variables
1670   = return (TyVarTy tv)
1671
1672 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1673 unBoxPred (IParam ip ty)   = do { ty' <- unBox ty; return (IParam ip ty') }
1674 unBoxPred (EqPred ty1 ty2) = do { ty1' <- unBox ty1; ty2' <- unBox ty2; return (EqPred ty1' ty2') }
1675 \end{code}
1676
1677
1678
1679 %************************************************************************
1680 %*                                                                      *
1681 \subsection[Unify-context]{Errors and contexts}
1682 %*                                                                      *
1683 %************************************************************************
1684
1685 Errors
1686 ~~~~~~
1687
1688 \begin{code}
1689 unifyCtxt act_ty exp_ty tidy_env
1690   = do  { act_ty' <- zonkTcType act_ty
1691         ; exp_ty' <- zonkTcType exp_ty
1692         ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1693               (env2, act_ty'') = tidyOpenType env1     act_ty'
1694         ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1695
1696 ----------------
1697 mkExpectedActualMsg act_ty exp_ty
1698   = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1699                    text "Inferred type" <> colon <+> ppr act_ty ])
1700
1701 ----------------
1702 -- If an error happens we try to figure out whether the function
1703 -- function has been given too many or too few arguments, and say so.
1704 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1705   = addErrCtxtM mk_err thing_inside
1706   where
1707     mk_err tidy_env
1708       = do { exp_ty' <- zonkTcType expected_res_ty
1709            ; act_ty' <- zonkTcType actual_res_ty
1710            ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1711                  (env2, act_ty'') = tidyOpenType env1     act_ty'
1712                  (exp_args, _)    = tcSplitFunTys exp_ty''
1713                  (act_args, _)    = tcSplitFunTys act_ty''
1714         
1715                  len_act_args     = length act_args
1716                  len_exp_args     = length exp_args
1717
1718                  message = case orig of
1719                              OccurrenceOf fun 
1720                                   | len_exp_args < len_act_args -> wrongArgsCtxt "too few"  fun
1721                                   | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1722                              other -> mkExpectedActualMsg act_ty'' exp_ty''
1723            ; return (env2, message) }
1724
1725     wrongArgsCtxt too_many_or_few fun
1726       = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1727         <+> ptext SLIT("is applied to") <+> text too_many_or_few 
1728         <+> ptext SLIT("arguments")
1729
1730 ------------------
1731 unifyForAllCtxt tvs phi1 phi2 env
1732   = return (env2, msg)
1733   where
1734     (env', tvs') = tidyOpenTyVars env tvs       -- NB: not tidyTyVarBndrs
1735     (env1, phi1') = tidyOpenType env' phi1
1736     (env2, phi2') = tidyOpenType env1 phi2
1737     msg = vcat [ptext SLIT("When matching") <+> quotes (ppr (mkForAllTys tvs' phi1')),
1738                 ptext SLIT("          and") <+> quotes (ppr (mkForAllTys tvs' phi2'))]
1739
1740 -----------------------
1741 unifyMisMatch outer swapped ty1 ty2
1742   | swapped   = unifyMisMatch outer False ty2 ty1
1743   | outer     = popErrCtxt $ unifyMisMatch False swapped ty1 ty2  -- This is the whole point of the 'outer' stuff
1744   | otherwise = failWithMisMatch ty1 ty2
1745 \end{code}
1746
1747
1748 %************************************************************************
1749 %*                                                                      *
1750                 Kind unification
1751 %*                                                                      *
1752 %************************************************************************
1753
1754 Unifying kinds is much, much simpler than unifying types.
1755
1756 \begin{code}
1757 unifyKind :: TcKind                 -- Expected
1758           -> TcKind                 -- Actual
1759           -> TcM ()
1760 unifyKind (TyConApp kc1 []) (TyConApp kc2 []) 
1761   | isSubKindCon kc2 kc1 = return ()
1762
1763 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1764   = do { unifyKind a2 a1; unifyKind r1 r2 }
1765                 -- Notice the flip in the argument,
1766                 -- so that the sub-kinding works right
1767 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1768 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1769 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1770
1771 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1772 unifyKinds []       []       = return ()
1773 unifyKinds (k1:ks1) (k2:ks2) = do unifyKind k1 k2
1774                                   unifyKinds ks1 ks2
1775 unifyKinds _ _               = panic "unifyKinds: length mis-match"
1776
1777 ----------------
1778 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1779 uKVar swapped kv1 k2
1780   = do  { mb_k1 <- readKindVar kv1
1781         ; case mb_k1 of
1782             Flexi -> uUnboundKVar swapped kv1 k2
1783             Indirect k1 | swapped   -> unifyKind k2 k1
1784                         | otherwise -> unifyKind k1 k2 }
1785
1786 ----------------
1787 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1788 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1789   | kv1 == kv2 = return ()
1790   | otherwise   -- Distinct kind variables
1791   = do  { mb_k2 <- readKindVar kv2
1792         ; case mb_k2 of
1793             Indirect k2 -> uUnboundKVar swapped kv1 k2
1794             Flexi -> writeKindVar kv1 k2 }
1795
1796 uUnboundKVar swapped kv1 non_var_k2
1797   = do  { k2' <- zonkTcKind non_var_k2
1798         ; kindOccurCheck kv1 k2'
1799         ; k2'' <- kindSimpleKind swapped k2'
1800                 -- KindVars must be bound only to simple kinds
1801                 -- Polarities: (kindSimpleKind True ?) succeeds 
1802                 -- returning *, corresponding to unifying
1803                 --      expected: ?
1804                 --      actual:   kind-ver
1805         ; writeKindVar kv1 k2'' }
1806
1807 ----------------
1808 kindOccurCheck kv1 k2   -- k2 is zonked
1809   = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1810   where
1811     not_in (TyVarTy kv2)   = kv1 /= kv2
1812     not_in (FunTy a2 r2) = not_in a2 && not_in r2
1813     not_in other         = True
1814
1815 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1816 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1817 -- If the flag is False, it requires k <: sk
1818 -- E.g.         kindSimpleKind False ?? = *
1819 -- What about (kv -> *) :=: ?? -> *
1820 kindSimpleKind orig_swapped orig_kind
1821   = go orig_swapped orig_kind
1822   where
1823     go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1824                              ; k2' <- go sw k2
1825                              ; return (mkArrowKind k1' k2') }
1826     go True k
1827      | isOpenTypeKind k = return liftedTypeKind
1828      | isArgTypeKind k  = return liftedTypeKind
1829     go sw k
1830      | isLiftedTypeKind k   = return liftedTypeKind
1831      | isUnliftedTypeKind k = return unliftedTypeKind
1832     go sw k@(TyVarTy _)   = return k    -- KindVars are always simple
1833     go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1834                                   <+> ppr orig_swapped <+> ppr orig_kind)
1835         -- I think this can't actually happen
1836
1837 -- T v = MkT v           v must be a type 
1838 -- T v w = MkT (v -> w)  v must not be an umboxed tuple
1839
1840 ----------------
1841 kindOccurCheckErr tyvar ty
1842   = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1843        2 (sep [ppr tyvar, char '=', ppr ty])
1844 \end{code}
1845
1846 \begin{code}
1847 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1848 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1849
1850 unifyFunKind (TyVarTy kvar) = do
1851     maybe_kind <- readKindVar kvar
1852     case maybe_kind of
1853       Indirect fun_kind -> unifyFunKind fun_kind
1854       Flexi -> 
1855           do { arg_kind <- newKindVar
1856              ; res_kind <- newKindVar
1857              ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1858              ; return (Just (arg_kind,res_kind)) }
1859     
1860 unifyFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1861 unifyFunKind other                     = return Nothing
1862 \end{code}
1863
1864 %************************************************************************
1865 %*                                                                      *
1866         Checking kinds
1867 %*                                                                      *
1868 %************************************************************************
1869
1870 ---------------------------
1871 -- We would like to get a decent error message from
1872 --   (a) Under-applied type constructors
1873 --              f :: (Maybe, Maybe)
1874 --   (b) Over-applied type constructors
1875 --              f :: Int x -> Int x
1876 --
1877
1878 \begin{code}
1879 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1880 -- A fancy wrapper for 'unifyKind', which tries 
1881 -- to give decent error messages.
1882 --      (checkExpectedKind ty act_kind exp_kind)
1883 -- checks that the actual kind act_kind is compatible 
1884 --      with the expected kind exp_kind
1885 -- The first argument, ty, is used only in the error message generation
1886 checkExpectedKind ty act_kind exp_kind
1887   | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1888   = return ()
1889   | otherwise = do
1890     (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
1891     case mb_r of
1892         Just r  -> return () ;  -- Unification succeeded
1893         Nothing -> do
1894
1895         -- So there's definitely an error
1896         -- Now to find out what sort
1897            exp_kind <- zonkTcKind exp_kind
1898            act_kind <- zonkTcKind act_kind
1899
1900            env0 <- tcInitTidyEnv
1901            let (exp_as, _) = splitKindFunTys exp_kind
1902                (act_as, _) = splitKindFunTys act_kind
1903                n_exp_as = length exp_as
1904                n_act_as = length act_as
1905
1906                (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1907                (env2, tidy_act_kind) = tidyKind env1 act_kind
1908
1909                err | n_exp_as < n_act_as     -- E.g. [Maybe]
1910                    = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1911
1912                      -- Now n_exp_as >= n_act_as. In the next two cases,
1913                      -- n_exp_as == 0, and hence so is n_act_as
1914                    | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1915                    = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1916                        <+> ptext SLIT("is unlifted")
1917
1918                    | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1919                    = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1920                        <+> ptext SLIT("is lifted")
1921
1922                    | otherwise               -- E.g. Monad [Int]
1923                    = ptext SLIT("Kind mis-match")
1924
1925                more_info = sep [ ptext SLIT("Expected kind") <+>
1926                                      quotes (pprKind tidy_exp_kind) <> comma,
1927                                  ptext SLIT("but") <+> quotes (ppr ty) <+>
1928                                      ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1929
1930            failWithTcM (env2, err $$ more_info)
1931 \end{code}
1932
1933 %************************************************************************
1934 %*                                                                      *
1935 \subsection{Checking signature type variables}
1936 %*                                                                      *
1937 %************************************************************************
1938
1939 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1940 are not mentioned in the environment.  In particular:
1941
1942         (a) Not mentioned in the type of a variable in the envt
1943                 eg the signature for f in this:
1944
1945                         g x = ... where
1946                                         f :: a->[a]
1947                                         f y = [x,y]
1948
1949                 Here, f is forced to be monorphic by the free occurence of x.
1950
1951         (d) Not (unified with another type variable that is) in scope.
1952                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1953             when checking the expression type signature, we find that
1954             even though there is nothing in scope whose type mentions r,
1955             nevertheless the type signature for the expression isn't right.
1956
1957             Another example is in a class or instance declaration:
1958                 class C a where
1959                    op :: forall b. a -> b
1960                    op x = x
1961             Here, b gets unified with a
1962
1963 Before doing this, the substitution is applied to the signature type variable.
1964
1965 \begin{code}
1966 checkSigTyVars :: [TcTyVar] -> TcM ()
1967 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1968
1969 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1970 -- The extra_tvs can include boxy type variables; 
1971 --      e.g. TcMatches.tcCheckExistentialPat
1972 checkSigTyVarsWrt extra_tvs sig_tvs
1973   = do  { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1974         ; check_sig_tyvars extra_tvs' sig_tvs }
1975
1976 check_sig_tyvars
1977         :: TcTyVarSet   -- Global type variables. The universally quantified
1978                         --      tyvars should not mention any of these
1979                         --      Guaranteed already zonked.
1980         -> [TcTyVar]    -- Universally-quantified type variables in the signature
1981                         --      Guaranteed to be skolems
1982         -> TcM ()
1983 check_sig_tyvars extra_tvs []
1984   = return ()
1985 check_sig_tyvars extra_tvs sig_tvs 
1986   = ASSERT( all isSkolemTyVar sig_tvs )
1987     do  { gbl_tvs <- tcGetGlobalTyVars
1988         ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1989                                       text "gbl_tvs" <+> ppr gbl_tvs,
1990                                       text "extra_tvs" <+> ppr extra_tvs]))
1991
1992         ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1993         ; when (any (`elemVarSet` env_tvs) sig_tvs)
1994                (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1995         }
1996
1997 bleatEscapedTvs :: TcTyVarSet   -- The global tvs
1998                 -> [TcTyVar]    -- The possibly-escaping type variables
1999                 -> [TcTyVar]    -- The zonked versions thereof
2000                 -> TcM ()
2001 -- Complain about escaping type variables
2002 -- We pass a list of type variables, at least one of which
2003 -- escapes.  The first list contains the original signature type variable,
2004 -- while the second  contains the type variable it is unified to (usually itself)
2005 bleatEscapedTvs globals sig_tvs zonked_tvs
2006   = do  { env0 <- tcInitTidyEnv
2007         ; let (env1, tidy_tvs)        = tidyOpenTyVars env0 sig_tvs
2008               (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
2009
2010         ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
2011         ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
2012   where
2013     main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
2014
2015     check (tidy_env, msgs) (sig_tv, zonked_tv)
2016       | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
2017       | otherwise
2018       = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
2019            ; return (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
2020
2021 -----------------------
2022 escape_msg sig_tv zonked_tv globs
2023   | notNull globs 
2024   = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")], 
2025           nest 2 (vcat globs)]
2026   | otherwise
2027   = msg <+> ptext SLIT("escapes")
2028         -- Sigh.  It's really hard to give a good error message
2029         -- all the time.   One bad case is an existential pattern match.
2030         -- We rely on the "When..." context to help.
2031   where
2032     msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
2033     is_bound_to 
2034         | sig_tv == zonked_tv = empty
2035         | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
2036 \end{code}
2037
2038 These two context are used with checkSigTyVars
2039     
2040 \begin{code}
2041 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
2042         -> TidyEnv -> TcM (TidyEnv, Message)
2043 sigCtxt id sig_tvs sig_theta sig_tau tidy_env = do
2044     actual_tau <- zonkTcType sig_tau
2045     let
2046         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
2047         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
2048         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
2049         sub_msg = vcat [ptext SLIT("Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
2050                         ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
2051                    ]
2052         msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),
2053                     nest 2 sub_msg]
2054     
2055     return (env3, msg)
2056 \end{code}