Make unification robust to a boxy type variable meeting itself
[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, isBoxyTyVar tv1  -- choose ty2 if ty2 is a box
482       = orig_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 (TyVarTy tv2)
1000   | tv1 == tv2  -- Same type variable => no-op (but watch out for the boxy case)
1001   = case details1 of
1002         MetaTv BoxTv ref1  -- A boxy type variable meets itself;
1003                            -- this is box-meets-box, so fill in with a tau-type
1004               -> do { tau_tv <- tcInstTyVar tv1
1005                     ; updateMeta tv1 ref1 (mkTyVarTy tau_tv) }
1006         other -> returnM ()     -- No-op
1007
1008         -- Distinct type variables
1009   | otherwise
1010   = do  { lookup2 <- lookupTcTyVar tv2
1011         ; case lookup2 of
1012             IndirectTv ty2' -> uUnfilledVar  outer swapped tv1 details1 True ty2' ty2'
1013             DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1014         }
1015
1016 uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 non_var_ty2  -- ty2 is not a type variable
1017   = case details1 of
1018         MetaTv (SigTv _) ref1 -> mis_match      -- Can't update a skolem with a non-type-variable
1019         MetaTv info ref1      -> uMetaVar swapped tv1 info ref1 nb2 ps_ty2 non_var_ty2
1020         skolem_details        -> mis_match
1021   where
1022     mis_match = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1023
1024 ----------------
1025 uMetaVar :: Bool
1026          -> TcTyVar -> BoxInfo -> IORef MetaDetails
1027          -> NoBoxes -> TcType -> TcType
1028          -> TcM ()
1029 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1030 -- ty2 is not a type variable
1031
1032 uMetaVar swapped tv1 BoxTv ref1 nb2 ps_ty2 non_var_ty2
1033   =     -- tv1 is a BoxTv.  So we must unbox ty2, to ensure
1034         -- that any boxes in ty2 are filled with monotypes
1035         -- 
1036         -- It should not be the case that tv1 occurs in ty2
1037         -- (i.e. no occurs check should be needed), but if perchance
1038         -- it does, the unbox operation will fill it, and the DEBUG
1039         -- checks for that.
1040     do  { final_ty <- unBox ps_ty2
1041 #ifdef DEBUG
1042         ; meta_details <- readMutVar ref1
1043         ; case meta_details of
1044             Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1045                            return ()    -- This really should *not* happen
1046             Flexi       -> return ()
1047 #endif
1048         ; checkUpdateMeta swapped tv1 ref1 final_ty }
1049
1050 uMetaVar swapped tv1 info1 ref1 nb2 ps_ty2 non_var_ty2
1051   = do  { final_ty <- checkTauTvUpdate tv1 ps_ty2       -- Occurs check + monotype check
1052         ; checkUpdateMeta swapped tv1 ref1 final_ty }
1053
1054 ----------------
1055 uUnfilledVars :: Outer
1056               -> Bool                   -- Args are swapped
1057               -> TcTyVar -> TcTyVarDetails      -- Tyvar 1
1058               -> TcTyVar -> TcTyVarDetails      -- Tyvar 2
1059               -> TcM ()
1060 -- Invarant: The type variables are distinct, 
1061 --           Neither is filled in yet
1062 --           They might be boxy or not
1063
1064 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1065   = unifyMisMatch outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1066
1067 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1068   = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2)
1069 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1070   = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1)
1071
1072 -- ToDo: this function seems too long for what it acutally does!
1073 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1074   = case (info1, info2) of
1075         (BoxTv,   BoxTv)   -> box_meets_box
1076
1077         -- If a box meets a TauTv, but the fomer has the smaller kind
1078         -- then we must create a fresh TauTv with the smaller kind
1079         (_,       BoxTv)   | k1_sub_k2 -> update_tv2
1080                            | otherwise -> box_meets_box
1081         (BoxTv,   _    )   | k2_sub_k1 -> update_tv1
1082                            | otherwise -> box_meets_box
1083
1084         -- Avoid SigTvs if poss
1085         (SigTv _, _      ) | k1_sub_k2 -> update_tv2
1086         (_,       SigTv _) | k2_sub_k1 -> update_tv1
1087
1088         (_,   _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1089                                 then update_tv1         -- Same kinds
1090                                 else update_tv2
1091                  | k2_sub_k1 -> update_tv1
1092                  | otherwise -> kind_err 
1093
1094         -- Update the variable with least kind info
1095         -- See notes on type inference in Kind.lhs
1096         -- The "nicer to" part only applies if the two kinds are the same,
1097         -- so we can choose which to do.
1098   where
1099         -- Kinds should be guaranteed ok at this point
1100     update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1101     update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1102
1103     box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1104                                 then fill_from tv2
1105                                 else fill_from tv1
1106                   | k2_sub_k1 = fill_from tv2
1107                   | otherwise = kind_err
1108
1109         -- Update *both* tyvars with a TauTv whose name and kind
1110         -- are gotten from tv (avoid losing nice names is poss)
1111     fill_from tv = do { tv' <- tcInstTyVar tv
1112                       ; let tau_ty = mkTyVarTy tv'
1113                       ; updateMeta tv1 ref1 tau_ty
1114                       ; updateMeta tv2 ref2 tau_ty }
1115
1116     kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2))  $
1117                unifyKindMisMatch k1 k2
1118
1119     k1 = tyVarKind tv1
1120     k2 = tyVarKind tv2
1121     k1_sub_k2 = k1 `isSubKind` k2
1122     k2_sub_k1 = k2 `isSubKind` k1
1123
1124     nicer_to_update_tv1 = isSystemName (varName tv1)
1125         -- Try to update sys-y type variables in preference to ones
1126         -- gotten (say) by instantiating a polymorphic function with
1127         -- a user-written type sig
1128         
1129 ----------------
1130 checkUpdateMeta :: Bool -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1131 -- Update tv1, which is flexi; occurs check is alrady done
1132 -- The 'check' version does a kind check too
1133 -- We do a sub-kind check here: we might unify (a b) with (c d) 
1134 --      where b::*->* and d::*; this should fail
1135
1136 checkUpdateMeta swapped tv1 ref1 ty2
1137   = do  { checkKinds swapped tv1 ty2
1138         ; updateMeta tv1 ref1 ty2 }
1139
1140 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1141 updateMeta tv1 ref1 ty2
1142   = ASSERT( isMetaTyVar tv1 )
1143     ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
1144     do  { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
1145         ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
1146         ; writeMutVar ref1 (Indirect ty2) }
1147
1148 ----------------
1149 checkKinds swapped tv1 ty2
1150 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
1151 -- ty2 has been zonked at this stage, which ensures that
1152 -- its kind has as much boxity information visible as possible.
1153   | tk2 `isSubKind` tk1 = returnM ()
1154
1155   | otherwise
1156         -- Either the kinds aren't compatible
1157         --      (can happen if we unify (a b) with (c d))
1158         -- or we are unifying a lifted type variable with an
1159         --      unlifted type: e.g.  (id 3#) is illegal
1160   = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
1161     unifyKindMisMatch k1 k2
1162   where
1163     (k1,k2) | swapped   = (tk2,tk1)
1164             | otherwise = (tk1,tk2)
1165     tk1 = tyVarKind tv1
1166     tk2 = typeKind ty2
1167
1168 ----------------
1169 checkTauTvUpdate :: TcTyVar -> TcType -> TcM TcType
1170 --    (checkTauTvUpdate tv ty)
1171 -- We are about to update the TauTv tv with ty.
1172 -- Check (a) that tv doesn't occur in ty (occurs check)
1173 --       (b) that ty is a monotype
1174 -- Furthermore, in the interest of (b), if you find an
1175 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
1176 -- 
1177 -- Returns the (non-boxy) type to update the type variable with, or fails
1178
1179 checkTauTvUpdate orig_tv orig_ty
1180   = go orig_ty
1181   where
1182     go (TyConApp tc tys)
1183         | isSynTyCon tc  = go_syn tc tys
1184         | otherwise      = do { tys' <- mappM go tys; return (TyConApp tc tys') }
1185     go (NoteTy _ ty2)    = go ty2       -- Discard free-tyvar annotations
1186     go (PredTy p)        = do { p' <- go_pred p; return (PredTy p') }
1187     go (FunTy arg res)   = do { arg' <- go arg; res' <- go res; return (FunTy arg' res') }
1188     go (AppTy fun arg)   = do { fun' <- go fun; arg' <- go arg; return (mkAppTy fun' arg') }
1189                 -- NB the mkAppTy; we might have instantiated a
1190                 -- type variable to a type constructor, so we need
1191                 -- to pull the TyConApp to the top.
1192     go (ForAllTy tv ty) = notMonoType orig_ty           -- (b)
1193
1194     go (TyVarTy tv)
1195         | orig_tv == tv = occurCheck tv orig_ty         -- (a)
1196         | isTcTyVar tv  = go_tyvar tv (tcTyVarDetails tv)
1197         | otherwise     = return (TyVarTy tv)
1198                  -- Ordinary (non Tc) tyvars
1199                  -- occur inside quantified types
1200
1201     go_pred (ClassP c tys) = do { tys' <- mapM go tys; return (ClassP c tys') }
1202     go_pred (IParam n ty)  = do { ty' <- go ty;        return (IParam n ty') }
1203
1204     go_tyvar tv (SkolemTv _) = return (TyVarTy tv)
1205     go_tyvar tv (MetaTv box ref)
1206         = do { cts <- readMutVar ref
1207              ; case cts of
1208                   Indirect ty -> go ty 
1209                   Flexi -> case box of
1210                                 BoxTv -> fillBoxWithTau tv ref
1211                                 other -> return (TyVarTy tv)
1212              }
1213
1214         -- go_syn is called for synonyms only
1215         -- See Note [Type synonyms and the occur check]
1216     go_syn tc tys
1217         | not (isTauTyCon tc)
1218         = notMonoType orig_ty   -- (b) again
1219         | otherwise
1220         = do { (msgs, mb_tys') <- tryTc (mapM go tys)
1221              ; case mb_tys' of
1222                 Just tys' -> return (TyConApp tc tys')
1223                                 -- Retain the synonym (the common case)
1224                 Nothing   -> go (expectJust "checkTauTvUpdate" 
1225                                         (tcView (TyConApp tc tys)))
1226                                 -- Try again, expanding the synonym
1227              }
1228
1229 fillBoxWithTau :: BoxyTyVar -> IORef MetaDetails -> TcM TcType
1230 -- (fillBoxWithTau tv ref) fills ref with a freshly allocated 
1231 --  tau-type meta-variable, whose print-name is the same as tv
1232 -- Choosing the same name is good: when we instantiate a function
1233 -- we allocate boxy tyvars with the same print-name as the quantified
1234 -- tyvar; and then we often fill the box with a tau-tyvar, and again
1235 -- we want to choose the same name.
1236 fillBoxWithTau tv ref 
1237   = do  { tv' <- tcInstTyVar tv         -- Do not gratuitously forget
1238         ; let tau = mkTyVarTy tv'       -- name of the type variable
1239         ; writeMutVar ref (Indirect tau)
1240         ; return tau }
1241 \end{code}
1242
1243 Note [Type synonyms and the occur check]
1244 ~~~~~~~~~~~~~~~~~~~~
1245 Basically we want to update     tv1 := ps_ty2
1246 because ps_ty2 has type-synonym info, which improves later error messages
1247
1248 But consider 
1249         type A a = ()
1250
1251         f :: (A a -> a -> ()) -> ()
1252         f = \ _ -> ()
1253
1254         x :: ()
1255         x = f (\ x p -> p x)
1256
1257 In the application (p x), we try to match "t" with "A t".  If we go
1258 ahead and bind t to A t (= ps_ty2), we'll lead the type checker into 
1259 an infinite loop later.
1260 But we should not reject the program, because A t = ().
1261 Rather, we should bind t to () (= non_var_ty2).
1262
1263 \begin{code}
1264 stripBoxyType :: BoxyType -> TcM TcType
1265 -- Strip all boxes from the input type, returning a non-boxy type.
1266 -- It's fine for there to be a polytype inside a box (c.f. unBox)
1267 -- All of the boxes should have been filled in by now; 
1268 -- hence we return a TcType
1269 stripBoxyType ty = zonkType strip_tv ty
1270   where
1271     strip_tv tv = ASSERT( not (isBoxyTyVar tv) ) return (TyVarTy tv)
1272         -- strip_tv will be called for *Flexi* meta-tyvars
1273         -- There should not be any Boxy ones; hence the ASSERT
1274
1275 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1276 -- Subtle... we must zap the boxy res_ty
1277 -- to kind * before using it to instantiate a LitInst
1278 -- Calling unBox instead doesn't do the job, because the box
1279 -- often has an openTypeKind, and we don't want to instantiate
1280 -- with that type.
1281 zapToMonotype res_ty
1282   = do  { res_tau <- newFlexiTyVarTy liftedTypeKind
1283         ; boxyUnify res_tau res_ty
1284         ; return res_tau }
1285
1286 unBox :: BoxyType -> TcM TcType
1287 -- unBox implements the judgement 
1288 --      |- s' ~ box(s)
1289 -- with input s', and result s
1290 -- 
1291 -- It remove all boxes from the input type, returning a non-boxy type.
1292 -- A filled box in the type can only contain a monotype; unBox fails if not
1293 -- The type can have empty boxes, which unBox fills with a monotype
1294 --
1295 -- Compare this wth checkTauTvUpdate
1296 --
1297 -- For once, it's safe to treat synonyms as opaque!
1298
1299 unBox (NoteTy n ty)     = do { ty' <- unBox ty; return (NoteTy n ty') }
1300 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1301 unBox (AppTy f a)       = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1302 unBox (FunTy f a)       = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1303 unBox (PredTy p)        = do { p' <- unBoxPred p; return (PredTy p') }
1304 unBox (ForAllTy tv ty)  = ASSERT( isImmutableTyVar tv )
1305                           do { ty' <- unBox ty; return (ForAllTy tv ty') }
1306 unBox (TyVarTy tv)
1307   | isTcTyVar tv                                -- It's a boxy type variable
1308   , MetaTv BoxTv ref <- tcTyVarDetails tv       -- NB: non-TcTyVars are possible
1309   = do  { cts <- readMutVar ref                 --     under nested quantifiers
1310         ; case cts of
1311             Flexi       -> fillBoxWithTau tv ref
1312             Indirect ty -> do { non_boxy_ty <- unBox ty
1313                               ; if isTauTy non_boxy_ty 
1314                                 then return non_boxy_ty
1315                                 else notMonoType non_boxy_ty }
1316         }
1317   | otherwise   -- Skolems, and meta-tau-variables
1318   = return (TyVarTy tv)
1319
1320 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1321 unBoxPred (IParam ip ty)   = do { ty' <- unBox ty; return (IParam ip ty') }
1322 \end{code}
1323
1324
1325
1326 %************************************************************************
1327 %*                                                                      *
1328 \subsection[Unify-context]{Errors and contexts}
1329 %*                                                                      *
1330 %************************************************************************
1331
1332 Errors
1333 ~~~~~~
1334
1335 \begin{code}
1336 unifyCtxt act_ty exp_ty tidy_env
1337   = do  { act_ty' <- zonkTcType act_ty
1338         ; exp_ty' <- zonkTcType exp_ty
1339         ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1340               (env2, act_ty'') = tidyOpenType env1     act_ty'
1341         ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1342
1343 ----------------
1344 mkExpectedActualMsg act_ty exp_ty
1345   = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1346                    text "Inferred type" <> colon <+> ppr act_ty ])
1347
1348 ----------------
1349 -- If an error happens we try to figure out whether the function
1350 -- function has been given too many or too few arguments, and say so.
1351 checkFunResCtxt fun actual_res_ty expected_res_ty tidy_env
1352   = do  { exp_ty' <- zonkTcType expected_res_ty
1353         ; act_ty' <- zonkTcType actual_res_ty
1354         ; let
1355               (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1356               (env2, act_ty'') = tidyOpenType env1     act_ty'
1357               (exp_args, _)    = tcSplitFunTys exp_ty''
1358               (act_args, _)    = tcSplitFunTys act_ty''
1359         
1360               len_act_args     = length act_args
1361               len_exp_args     = length exp_args
1362
1363               message | len_exp_args < len_act_args = wrongArgsCtxt "too few"  fun
1364                       | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun
1365                       | otherwise                   = mkExpectedActualMsg act_ty'' exp_ty''
1366         ; return (env2, message) }
1367
1368   where
1369     wrongArgsCtxt too_many_or_few fun
1370       = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1371         <+> ptext SLIT("is applied to") <+> text too_many_or_few 
1372         <+> ptext SLIT("arguments")
1373
1374 ------------------
1375 unifyKindCtxt swapped tv1 ty2 tidy_env  -- not swapped => tv1 expected, ty2 inferred
1376         -- tv1 and ty2 are zonked already
1377   = returnM msg
1378   where
1379     msg = (env2, ptext SLIT("When matching the kinds of") <+> 
1380                  sep [quotes pp_expected <+> ptext SLIT("and"), quotes pp_actual])
1381
1382     (pp_expected, pp_actual) | swapped   = (pp2, pp1)
1383                              | otherwise = (pp1, pp2)
1384     (env1, tv1') = tidyOpenTyVar tidy_env tv1
1385     (env2, ty2') = tidyOpenType  env1 ty2
1386     pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
1387     pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
1388
1389 unifyMisMatch outer swapped ty1 ty2
1390   = do  { (env, msg) <- if swapped then misMatchMsg ty1 ty2
1391                                    else misMatchMsg ty2 ty1
1392
1393         -- This is the whole point of the 'outer' stuff
1394         ; if outer then popErrCtxt (failWithTcM (env, msg))
1395                    else failWithTcM (env, msg)
1396         } 
1397
1398 misMatchMsg ty1 ty2
1399   = do  { env0 <- tcInitTidyEnv
1400         ; (env1, pp1, extra1) <- ppr_ty env0 ty1
1401         ; (env2, pp2, extra2) <- ppr_ty env1 ty2
1402         ; return (env2, sep [sep [ptext SLIT("Couldn't match expected type") <+> pp1, 
1403                                   nest 7 (ptext SLIT("against inferred type") <+> pp2)],
1404                              nest 2 extra1, nest 2 extra2]) }
1405
1406 ppr_ty :: TidyEnv -> TcType -> TcM (TidyEnv, SDoc, SDoc)
1407 ppr_ty env ty
1408   = do { ty' <- zonkTcType ty
1409        ; let (env1,tidy_ty) = tidyOpenType env ty'
1410              simple_result  = (env1, quotes (ppr tidy_ty), empty)
1411        ; case tidy_ty of
1412            TyVarTy tv 
1413                 | isSkolemTyVar tv -> return (env2, pp_rigid tv',
1414                                               pprSkolTvBinding tv')
1415                 | otherwise -> return simple_result
1416                 where
1417                   (env2, tv') = tidySkolemTyVar env1 tv
1418            other -> return simple_result }
1419   where
1420     pp_rigid tv = quotes (ppr tv) <+> parens (ptext SLIT("a rigid variable"))
1421
1422
1423 notMonoType ty
1424   = do  { ty' <- zonkTcType ty
1425         ; env0 <- tcInitTidyEnv
1426         ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1427               msg = ptext SLIT("Cannot match a monotype with") <+> ppr tidy_ty
1428         ; failWithTcM (env1, msg) }
1429
1430 occurCheck tyvar ty
1431   = do  { env0 <- tcInitTidyEnv
1432         ; ty'  <- zonkTcType ty
1433         ; let (env1, tidy_tyvar) = tidyOpenTyVar env0 tyvar
1434               (env2, tidy_ty)    = tidyOpenType  env1 ty'
1435               extra = sep [ppr tidy_tyvar, char '=', ppr tidy_ty]
1436         ; failWithTcM (env2, hang msg 2 extra) }
1437   where
1438     msg = ptext SLIT("Occurs check: cannot construct the infinite type:")
1439 \end{code}
1440
1441
1442 %************************************************************************
1443 %*                                                                      *
1444                 Kind unification
1445 %*                                                                      *
1446 %************************************************************************
1447
1448 Unifying kinds is much, much simpler than unifying types.
1449
1450 \begin{code}
1451 unifyKind :: TcKind                 -- Expected
1452           -> TcKind                 -- Actual
1453           -> TcM ()
1454 unifyKind LiftedTypeKind   LiftedTypeKind   = returnM ()
1455 unifyKind UnliftedTypeKind UnliftedTypeKind = returnM ()
1456
1457 unifyKind OpenTypeKind k2 | isOpenTypeKind k2 = returnM ()
1458 unifyKind ArgTypeKind  k2 | isArgTypeKind k2    = returnM ()
1459   -- Respect sub-kinding
1460
1461 unifyKind (FunKind a1 r1) (FunKind a2 r2)
1462  = do { unifyKind a2 a1; unifyKind r1 r2 }
1463                 -- Notice the flip in the argument,
1464                 -- so that the sub-kinding works right
1465
1466 unifyKind (KindVar kv1) k2 = uKVar False kv1 k2
1467 unifyKind k1 (KindVar kv2) = uKVar True kv2 k1
1468 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1469
1470 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1471 unifyKinds []       []       = returnM ()
1472 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2  `thenM_`
1473                                unifyKinds ks1 ks2
1474 unifyKinds _ _               = panic "unifyKinds: length mis-match"
1475
1476 ----------------
1477 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1478 uKVar swapped kv1 k2
1479   = do  { mb_k1 <- readKindVar kv1
1480         ; case mb_k1 of
1481             Nothing -> uUnboundKVar swapped kv1 k2
1482             Just k1 | swapped   -> unifyKind k2 k1
1483                     | otherwise -> unifyKind k1 k2 }
1484
1485 ----------------
1486 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1487 uUnboundKVar swapped kv1 k2@(KindVar kv2)
1488   | kv1 == kv2 = returnM ()
1489   | otherwise   -- Distinct kind variables
1490   = do  { mb_k2 <- readKindVar kv2
1491         ; case mb_k2 of
1492             Just k2 -> uUnboundKVar swapped kv1 k2
1493             Nothing -> writeKindVar kv1 k2 }
1494
1495 uUnboundKVar swapped kv1 non_var_k2
1496   = do  { k2' <- zonkTcKind non_var_k2
1497         ; kindOccurCheck kv1 k2'
1498         ; k2'' <- kindSimpleKind swapped k2'
1499                 -- KindVars must be bound only to simple kinds
1500                 -- Polarities: (kindSimpleKind True ?) succeeds 
1501                 -- returning *, corresponding to unifying
1502                 --      expected: ?
1503                 --      actual:   kind-ver
1504         ; writeKindVar kv1 k2'' }
1505
1506 ----------------
1507 kindOccurCheck kv1 k2   -- k2 is zonked
1508   = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1509   where
1510     not_in (KindVar kv2)   = kv1 /= kv2
1511     not_in (FunKind a2 r2) = not_in a2 && not_in r2
1512     not_in other           = True
1513
1514 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1515 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1516 -- If the flag is False, it requires k <: sk
1517 -- E.g.         kindSimpleKind False ?? = *
1518 -- What about (kv -> *) :=: ?? -> *
1519 kindSimpleKind orig_swapped orig_kind
1520   = go orig_swapped orig_kind
1521   where
1522     go sw (FunKind k1 k2) = do { k1' <- go (not sw) k1
1523                                ; k2' <- go sw k2
1524                                ; return (FunKind k1' k2') }
1525     go True OpenTypeKind = return liftedTypeKind
1526     go True ArgTypeKind  = return liftedTypeKind
1527     go sw LiftedTypeKind  = return liftedTypeKind
1528     go sw UnliftedTypeKind = return unliftedTypeKind
1529     go sw k@(KindVar _)   = return k    -- KindVars are always simple
1530     go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1531                                   <+> ppr orig_swapped <+> ppr orig_kind)
1532         -- I think this can't actually happen
1533
1534 -- T v = MkT v           v must be a type 
1535 -- T v w = MkT (v -> w)  v must not be an umboxed tuple
1536
1537 ----------------
1538 kindOccurCheckErr tyvar ty
1539   = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1540        2 (sep [ppr tyvar, char '=', ppr ty])
1541
1542 unifyKindMisMatch ty1 ty2
1543   = zonkTcKind ty1      `thenM` \ ty1' ->
1544     zonkTcKind ty2      `thenM` \ ty2' ->
1545     let
1546         msg = hang (ptext SLIT("Couldn't match kind"))
1547                    2 (sep [quotes (ppr ty1'), 
1548                            ptext SLIT("against"), 
1549                            quotes (ppr ty2')])
1550     in
1551     failWithTc msg
1552 \end{code}
1553
1554 \begin{code}
1555 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1556 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1557
1558 unifyFunKind (KindVar kvar)
1559   = readKindVar kvar    `thenM` \ maybe_kind ->
1560     case maybe_kind of
1561         Just fun_kind -> unifyFunKind fun_kind
1562         Nothing       -> do { arg_kind <- newKindVar
1563                             ; res_kind <- newKindVar
1564                             ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1565                             ; returnM (Just (arg_kind,res_kind)) }
1566     
1567 unifyFunKind (FunKind arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1568 unifyFunKind other                       = returnM Nothing
1569 \end{code}
1570
1571 %************************************************************************
1572 %*                                                                      *
1573         Checking kinds
1574 %*                                                                      *
1575 %************************************************************************
1576
1577 ---------------------------
1578 -- We would like to get a decent error message from
1579 --   (a) Under-applied type constructors
1580 --              f :: (Maybe, Maybe)
1581 --   (b) Over-applied type constructors
1582 --              f :: Int x -> Int x
1583 --
1584
1585 \begin{code}
1586 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1587 -- A fancy wrapper for 'unifyKind', which tries 
1588 -- to give decent error messages.
1589 checkExpectedKind ty act_kind exp_kind
1590   | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1591   = returnM ()
1592   | otherwise
1593   = tryTc (unifyKind exp_kind act_kind) `thenM` \ (_errs, mb_r) ->
1594     case mb_r of {
1595         Just r  -> returnM () ; -- Unification succeeded
1596         Nothing ->
1597
1598         -- So there's definitely an error
1599         -- Now to find out what sort
1600     zonkTcKind exp_kind         `thenM` \ exp_kind ->
1601     zonkTcKind act_kind         `thenM` \ act_kind ->
1602
1603     tcInitTidyEnv               `thenM` \ env0 -> 
1604     let (exp_as, _) = splitKindFunTys exp_kind
1605         (act_as, _) = splitKindFunTys act_kind
1606         n_exp_as = length exp_as
1607         n_act_as = length act_as
1608         
1609         (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1610         (env2, tidy_act_kind) = tidyKind env1 act_kind
1611
1612         err | n_exp_as < n_act_as       -- E.g. [Maybe]
1613             = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1614
1615                 -- Now n_exp_as >= n_act_as. In the next two cases, 
1616                 -- n_exp_as == 0, and hence so is n_act_as
1617             | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1618             = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1619                 <+> ptext SLIT("is unlifted")
1620
1621             | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1622             = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1623                 <+> ptext SLIT("is lifted")
1624
1625             | otherwise                 -- E.g. Monad [Int]
1626             = ptext SLIT("Kind mis-match")
1627
1628         more_info = sep [ ptext SLIT("Expected kind") <+> 
1629                                 quotes (pprKind tidy_exp_kind) <> comma,
1630                           ptext SLIT("but") <+> quotes (ppr ty) <+> 
1631                                 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1632    in
1633    failWithTcM (env2, err $$ more_info)
1634    }
1635 \end{code}
1636
1637 %************************************************************************
1638 %*                                                                      *
1639 \subsection{Checking signature type variables}
1640 %*                                                                      *
1641 %************************************************************************
1642
1643 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1644 are not mentioned in the environment.  In particular:
1645
1646         (a) Not mentioned in the type of a variable in the envt
1647                 eg the signature for f in this:
1648
1649                         g x = ... where
1650                                         f :: a->[a]
1651                                         f y = [x,y]
1652
1653                 Here, f is forced to be monorphic by the free occurence of x.
1654
1655         (d) Not (unified with another type variable that is) in scope.
1656                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1657             when checking the expression type signature, we find that
1658             even though there is nothing in scope whose type mentions r,
1659             nevertheless the type signature for the expression isn't right.
1660
1661             Another example is in a class or instance declaration:
1662                 class C a where
1663                    op :: forall b. a -> b
1664                    op x = x
1665             Here, b gets unified with a
1666
1667 Before doing this, the substitution is applied to the signature type variable.
1668
1669 \begin{code}
1670 checkSigTyVars :: [TcTyVar] -> TcM ()
1671 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1672
1673 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1674 -- The extra_tvs can include boxy type variables; 
1675 --      e.g. TcMatches.tcCheckExistentialPat
1676 checkSigTyVarsWrt extra_tvs sig_tvs
1677   = do  { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1678         ; check_sig_tyvars extra_tvs' sig_tvs }
1679
1680 check_sig_tyvars
1681         :: TcTyVarSet   -- Global type variables. The universally quantified
1682                         --      tyvars should not mention any of these
1683                         --      Guaranteed already zonked.
1684         -> [TcTyVar]    -- Universally-quantified type variables in the signature
1685                         --      Guaranteed to be skolems
1686         -> TcM ()
1687 check_sig_tyvars extra_tvs []
1688   = returnM ()
1689 check_sig_tyvars extra_tvs sig_tvs 
1690   = ASSERT( all isSkolemTyVar sig_tvs )
1691     do  { gbl_tvs <- tcGetGlobalTyVars
1692         ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1693                                       text "gbl_tvs" <+> ppr gbl_tvs,
1694                                       text "extra_tvs" <+> ppr extra_tvs]))
1695
1696         ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1697         ; ifM (any (`elemVarSet` env_tvs) sig_tvs)
1698               (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1699         }
1700
1701 bleatEscapedTvs :: TcTyVarSet   -- The global tvs
1702                 -> [TcTyVar]    -- The possibly-escaping type variables
1703                 -> [TcTyVar]    -- The zonked versions thereof
1704                 -> TcM ()
1705 -- Complain about escaping type variables
1706 -- We pass a list of type variables, at least one of which
1707 -- escapes.  The first list contains the original signature type variable,
1708 -- while the second  contains the type variable it is unified to (usually itself)
1709 bleatEscapedTvs globals sig_tvs zonked_tvs
1710   = do  { env0 <- tcInitTidyEnv
1711         ; let (env1, tidy_tvs)        = tidyOpenTyVars env0 sig_tvs
1712               (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1713
1714         ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1715         ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1716   where
1717     main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
1718
1719     check (tidy_env, msgs) (sig_tv, zonked_tv)
1720       | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1721       | otherwise
1722       = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
1723            ; returnM (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1724
1725 -----------------------
1726 escape_msg sig_tv zonked_tv globs
1727   | notNull globs 
1728   = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")], 
1729           nest 2 (vcat globs)]
1730   | otherwise
1731   = msg <+> ptext SLIT("escapes")
1732         -- Sigh.  It's really hard to give a good error message
1733         -- all the time.   One bad case is an existential pattern match.
1734         -- We rely on the "When..." context to help.
1735   where
1736     msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1737     is_bound_to 
1738         | sig_tv == zonked_tv = empty
1739         | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
1740 \end{code}
1741
1742 These two context are used with checkSigTyVars
1743     
1744 \begin{code}
1745 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1746         -> TidyEnv -> TcM (TidyEnv, Message)
1747 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
1748   = zonkTcType sig_tau          `thenM` \ actual_tau ->
1749     let
1750         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
1751         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1752         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1753         sub_msg = vcat [ptext SLIT("Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1754                         ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
1755                    ]
1756         msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),
1757                     nest 2 sub_msg]
1758     in
1759     returnM (env3, msg)
1760 \end{code}