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