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