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