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