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