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