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