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