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