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