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