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