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