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