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