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