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