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