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