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