Major refactoring of the type inference engine
[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   tcWrapResult, tcSubType, tcGen, 
12   checkConstraints, newImplication, sigCtxt,
13
14         -- Various unifications
15   unifyType, unifyTypeList, unifyTheta, unifyKind, 
16
17   --------------------------------
18   -- Holes
19   tcInfer, 
20   matchExpectedListTy, matchExpectedPArrTy, 
21   matchExpectedTyConApp, matchExpectedAppTy, 
22   matchExpectedFunTys, matchExpectedFunKind,
23   wrapFunResCoercion
24   ) where
25
26 #include "HsVersions.h"
27
28 import HsSyn
29 import TypeRep
30 import CoreUtils( mkPiTypes )
31 import TcErrors ( unifyCtxt )
32 import TcMType
33 import TcIface
34 import TcRnMonad
35 import TcType
36 import Type
37 import Coercion
38 import Inst
39 import TyCon
40 import TysWiredIn
41 import Var
42 import VarSet
43 import VarEnv
44 import Name
45 import ErrUtils
46 import BasicTypes
47
48 import Maybes ( allMaybes )  
49 import Util
50 import Outputable
51 import FastString
52
53 import Control.Monad
54 \end{code}
55
56
57 %************************************************************************
58 %*                                                                      *
59              matchExpected functions
60 %*                                                                      *
61 %************************************************************************
62
63 Note [Herald for matchExpectedFunTys]
64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65 The 'herald' always looks like:
66    "The equation(s) for 'f' have"
67    "The abstraction (\x.e) takes"
68    "The section (+ x) expects"
69    "The function 'f' is applied to"
70
71 This is used to construct a message of form
72
73    The abstraction `\Just 1 -> ...' takes two arguments
74    but its type `Maybe a -> a' has only one
75
76    The equation(s) for `f' have two arguments
77    but its type `Maybe a -> a' has only one
78
79    The section `(f 3)' requires 'f' to take two arguments
80    but its type `Int -> Int' has only one
81
82    The function 'f' is applied to two arguments
83    but its type `Int -> Int' has only one
84
85 Note [matchExpectedFunTys]
86 ~~~~~~~~~~~~~~~~~~~~~~~~~~
87 matchExpectedFunTys checks that an (Expected rho) has the form
88 of an n-ary function.  It passes the decomposed type to the
89 thing_inside, and returns a wrapper to coerce between the two types
90
91 It's used wherever a language construct must have a functional type,
92 namely:
93         A lambda expression
94         A function definition
95      An operator section
96
97 This is not (currently) where deep skolemisation occurs;
98 matchExpectedFunTys does not skolmise nested foralls in the 
99 expected type, becuase it expects that to have been done already
100
101
102 \begin{code}
103 matchExpectedFunTys :: SDoc     -- See Note [Herald for matchExpectedFunTys]
104                     -> Arity
105                     -> TcRhoType 
106                     -> TcM (CoercionI, [TcSigmaType], TcRhoType)                        
107
108 -- If    matchExpectFunTys n ty = (co, [t1,..,tn], ty_r)
109 -- then  co : ty ~ (t1 -> ... -> tn -> ty_r)
110 --
111 -- Does not allocate unnecessary meta variables: if the input already is 
112 -- a function, we just take it apart.  Not only is this efficient, 
113 -- it's important for higher rank: the argument might be of form
114 --              (forall a. ty) -> other
115 -- If allocated (fresh-meta-var1 -> fresh-meta-var2) and unified, we'd
116 -- hide the forall inside a meta-variable
117
118 matchExpectedFunTys herald arity orig_ty 
119   = go arity orig_ty
120   where
121     -- If     go n ty = (co, [t1,..,tn], ty_r)
122     -- then   co : ty ~ t1 -> .. -> tn -> ty_r
123
124     go n_req ty
125       | n_req == 0 = return (IdCo ty, [], ty)
126
127     go n_req ty
128       | Just ty' <- tcView ty = go n_req ty'
129
130     go n_req (FunTy arg_ty res_ty)
131       | not (isPredTy arg_ty) 
132       = do { (coi, tys, ty_r) <- go (n_req-1) res_ty
133            ; return (mkFunTyCoI (IdCo arg_ty) coi, arg_ty:tys, ty_r) }
134
135     go _ (TyConApp tc _)              -- A common case
136       | not (isSynFamilyTyCon tc)
137       = do { (env,msg) <- mk_ctxt emptyTidyEnv
138            ; failWithTcM (env,msg) }
139
140     go n_req ty@(TyVarTy tv)
141       | ASSERT( isTcTyVar tv) isMetaTyVar tv
142       = do { cts <- readMetaTyVar tv
143            ; case cts of
144                Indirect ty' -> go n_req ty'
145                Flexi        -> defer n_req ty }
146
147        -- In all other cases we bale out into ordinary unification
148     go n_req ty = defer n_req ty
149
150     ------------
151     defer n_req fun_ty 
152       = addErrCtxtM mk_ctxt $
153         do { arg_tys <- newFlexiTyVarTys n_req argTypeKind
154            ; res_ty  <- newFlexiTyVarTy openTypeKind
155            ; coi     <- unifyType fun_ty (mkFunTys arg_tys res_ty)
156            ; return (coi, arg_tys, res_ty) }
157
158     ------------
159     mk_ctxt :: TidyEnv -> TcM (TidyEnv, Message)
160     mk_ctxt env = do { orig_ty1 <- zonkTcType orig_ty
161                      ; let (env', orig_ty2) = tidyOpenType env orig_ty1
162                            (args, _) = tcSplitFunTys orig_ty2
163                            n_actual = length args
164                      ; return (env', mk_msg orig_ty2 n_actual) }
165
166     mk_msg ty n_args
167       = herald <+> speakNOf arity (ptext (sLit "argument")) <> comma $$ 
168         sep [ptext (sLit "but its type") <+> quotes (pprType ty), 
169              if n_args == 0 then ptext (sLit "has none") 
170              else ptext (sLit "has only") <+> speakN n_args]
171 \end{code}
172
173
174 \begin{code}
175 ----------------------
176 matchExpectedListTy :: TcRhoType -> TcM (CoercionI, TcRhoType)
177 -- Special case for lists
178 matchExpectedListTy exp_ty
179  = do { (coi, [elt_ty]) <- matchExpectedTyConApp listTyCon exp_ty
180       ; return (coi, elt_ty) }
181
182 ----------------------
183 matchExpectedPArrTy :: TcRhoType -> TcM (CoercionI, TcRhoType)
184 -- Special case for parrs
185 matchExpectedPArrTy exp_ty
186   = do { (coi, [elt_ty]) <- matchExpectedTyConApp parrTyCon exp_ty
187        ; return (coi, elt_ty) }
188
189 ----------------------
190 matchExpectedTyConApp :: TyCon                -- T :: k1 -> ... -> kn -> *
191                       -> TcRhoType            -- orig_ty
192                       -> TcM (CoercionI,      -- T a b c ~ orig_ty
193                               [TcSigmaType])  -- Element types, a b c
194                               
195 -- It's used for wired-in tycons, so we call checkWiredInTyCon
196 -- Precondition: never called with FunTyCon
197 -- Precondition: input type :: *
198
199 matchExpectedTyConApp tc orig_ty
200   = do  { checkWiredInTyCon tc
201         ; go (tyConArity tc) orig_ty [] }
202   where
203     go :: Int -> TcRhoType -> [TcSigmaType] -> TcM (CoercionI, [TcSigmaType])
204     -- If     go n ty tys = (co, [t1..tn] ++ tys)
205     -- then   co : T t1..tn ~ ty
206
207     go n_req ty tys
208       | Just ty' <- tcView ty = go n_req ty' tys
209
210     go n_req ty@(TyVarTy tv) tys
211       | ASSERT( isTcTyVar tv) isMetaTyVar tv
212       = do { cts <- readMetaTyVar tv
213            ; case cts of
214                Indirect ty -> go n_req ty tys
215                Flexi       -> defer n_req ty tys }
216
217     go n_req ty@(TyConApp tycon args) tys
218       | tc == tycon
219       = ASSERT( n_req == length args)   -- ty::*
220         return (IdCo ty, args ++ tys)
221
222     go n_req (AppTy fun arg) tys
223       | n_req > 0
224       = do { (coi, args) <- go (n_req - 1) fun (arg : tys) 
225            ; return (mkAppTyCoI coi (IdCo arg), args) }
226
227     go n_req ty tys = defer n_req ty tys
228
229     ----------
230     defer n_req ty tys
231       = do { tau_tys <- mapM newFlexiTyVarTy arg_kinds
232            ; coi <- unifyType (mkTyConApp tc tau_tys) ty
233            ; return (coi, tau_tys ++ tys) }
234       where
235         (arg_kinds, _) = splitKindFunTysN n_req (tyConKind tc)
236
237 ----------------------
238 matchExpectedAppTy :: TcRhoType                         -- orig_ty
239                    -> TcM (CoercionI,                   -- m a ~ orig_ty
240                            (TcSigmaType, TcSigmaType))  -- Returns m, a
241 -- If the incoming type is a mutable type variable of kind k, then
242 -- matchExpectedAppTy returns a new type variable (m: * -> k); note the *.
243
244 matchExpectedAppTy orig_ty
245   = go orig_ty
246   where
247     go ty
248       | Just ty' <- tcView ty = go ty'
249
250       | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
251       = return (IdCo orig_ty, (fun_ty, arg_ty))
252
253     go (TyVarTy tv)
254       | ASSERT( isTcTyVar tv) isMetaTyVar tv
255       = do { cts <- readMetaTyVar tv
256            ; case cts of
257                Indirect ty -> go ty
258                Flexi       -> defer }
259
260     go _ = defer
261
262     -- Defer splitting by generating an equality constraint
263     defer = do { ty1 <- newFlexiTyVarTy kind1
264                ; ty2 <- newFlexiTyVarTy kind2
265                ; coi <- unifyType (mkAppTy ty1 ty2) orig_ty
266                ; return (coi, (ty1, ty2)) }
267
268     orig_kind = typeKind orig_ty
269     kind1 = mkArrowKind liftedTypeKind (defaultKind orig_kind)
270     kind2 = liftedTypeKind    -- m :: * -> k
271                               -- arg type :: *
272         -- The defaultKind is a bit smelly.  If you remove it,
273         -- try compiling        f x = do { x }
274         -- and you'll get a kind mis-match.  It smells, but
275         -- not enough to lose sleep over.
276 \end{code}
277
278
279 %************************************************************************
280 %*                                                                      *
281                 Subsumption checking
282 %*                                                                      *
283 %************************************************************************
284
285 All the tcSub calls have the form
286
287                 tcSub actual_ty expected_ty
288 which checks
289                 actual_ty <= expected_ty
290
291 That is, that a value of type actual_ty is acceptable in
292 a place expecting a value of type expected_ty.
293
294 It returns a coercion function
295         co_fn :: actual_ty ~ expected_ty
296 which takes an HsExpr of type actual_ty into one of type
297 expected_ty.
298
299 \begin{code}
300 tcSubType :: CtOrigin -> UserTypeCtxt -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
301 -- Check that ty_actual is more polymorphic than ty_expected
302 -- Both arguments might be polytypes, so we must instantiate and skolemise
303 -- Returns a wrapper of shape   ty_actual ~ ty_expected
304 tcSubType origin ctxt ty_actual ty_expected
305   | isSigmaTy ty_actual
306   = do { (sk_wrap, inst_wrap) 
307             <- tcGen ctxt ty_expected $ \ _ sk_rho -> do
308             { (in_wrap, in_rho) <- deeplyInstantiate origin ty_actual
309             ; coi <- unifyType in_rho sk_rho
310             ; return (coiToHsWrapper coi <.> in_wrap) }
311        ; return (sk_wrap <.> inst_wrap) }
312
313   | otherwise   -- Urgh!  It seems deeply weird to have equality
314                 -- when actual is not a polytype, and it makes a big 
315                 -- difference e.g. tcfail104
316   = do { coi <- unifyType ty_actual ty_expected
317        ; return (coiToHsWrapper coi) }
318   
319 tcInfer :: (TcType -> TcM a) -> TcM (a, TcType)
320 tcInfer tc_infer = do { ty  <- newFlexiTyVarTy openTypeKind
321                       ; res <- tc_infer ty
322                       ; return (res, ty) }
323
324 -----------------
325 tcWrapResult :: HsExpr TcId -> TcRhoType -> TcRhoType -> TcM (HsExpr TcId)
326 tcWrapResult expr actual_ty res_ty
327   = do { coi <- unifyType actual_ty res_ty
328                 -- Both types are deeply skolemised
329        ; return (mkHsWrapCoI coi expr) }
330
331 -----------------------------------
332 wrapFunResCoercion
333         :: [TcType]     -- Type of args
334         -> HsWrapper    -- HsExpr a -> HsExpr b
335         -> TcM HsWrapper        -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
336 wrapFunResCoercion arg_tys co_fn_res
337   | isIdHsWrapper co_fn_res
338   = return idHsWrapper
339   | null arg_tys
340   = return co_fn_res
341   | otherwise
342   = do  { arg_ids <- newSysLocalIds (fsLit "sub") arg_tys
343         ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpEvVarApps arg_ids) }
344 \end{code}
345
346
347
348 %************************************************************************
349 %*                                                                      *
350 \subsection{Generalisation}
351 %*                                                                      *
352 %************************************************************************
353
354 \begin{code}
355 tcGen :: UserTypeCtxt -> TcType
356       -> ([TcTyVar] -> TcRhoType -> TcM result)
357       -> TcM (HsWrapper, result)
358         -- The expression has type: spec_ty -> expected_ty
359
360 tcGen ctxt expected_ty thing_inside
361    -- We expect expected_ty to be a forall-type
362    -- If not, the call is a no-op
363   = do  { traceTc "tcGen" empty
364         ; (wrap, tvs', given, rho') <- deeplySkolemise expected_ty
365
366         ; when debugIsOn $
367               traceTc "tcGen" $ vcat [
368                            text "expected_ty" <+> ppr expected_ty,
369                            text "inst ty" <+> ppr tvs' <+> ppr rho' ]
370
371         -- Generally we must check that the "forall_tvs" havn't been constrained
372         -- The interesting bit here is that we must include the free variables
373         -- of the expected_ty.  Here's an example:
374         --       runST (newVar True)
375         -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
376         -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
377         -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
378         -- So now s' isn't unconstrained because it's linked to a.
379         -- 
380         -- However [Oct 10] now that the untouchables are a range of 
381         -- TcTyVars, all this is handled automatically with no need for
382         -- extra faffing around
383
384         -- Use the *instantiated* type in the SkolemInfo
385         -- so that the names of displayed type variables line up
386         ; let skol_info = SigSkol ctxt (mkPiTypes given rho')
387
388         ; (ev_binds, result) <- checkConstraints skol_info tvs' given $
389                                 thing_inside tvs' rho'
390
391         ; return (wrap <.> mkWpLet ev_binds, result) }
392           -- The ev_binds returned by checkConstraints is very
393           -- often empty, in which case mkWpLet is a no-op
394
395 checkConstraints :: SkolemInfo
396                  -> [TcTyVar]           -- Skolems
397                  -> [EvVar]             -- Given
398                  -> TcM result
399                  -> TcM (TcEvBinds, result)
400
401 checkConstraints skol_info skol_tvs given thing_inside
402   | null skol_tvs && null given
403   = do { res <- thing_inside; return (emptyTcEvBinds, res) }
404       -- Just for efficiency.  We check every function argument with
405       -- tcPolyExpr, which uses tcGen and hence checkConstraints.
406
407   | otherwise
408   = newImplication skol_info skol_tvs given thing_inside
409
410 newImplication :: SkolemInfo -> [TcTyVar]
411                -> [EvVar] -> TcM result
412                -> TcM (TcEvBinds, result)
413 newImplication skol_info skol_tvs given thing_inside
414   = ASSERT2( all isTcTyVar skol_tvs, ppr skol_tvs )
415     ASSERT2( all isSkolemTyVar skol_tvs, ppr skol_tvs )
416     do { ((result, untch), wanted) <- captureConstraints  $ 
417                                       captureUntouchables $
418                                       thing_inside
419
420        ; if isEmptyWC wanted && not (hasEqualities given)
421             -- Optimisation : if there are no wanteds, and the givens
422             -- are sufficiently simple, don't generate an implication
423             -- at all.  Reason for the hasEqualities test:
424             -- we don't want to lose the "inaccessible alternative"
425             -- error check
426          then 
427             return (emptyTcEvBinds, result)
428          else do
429        { ev_binds_var <- newTcEvBinds
430        ; lcl_env <- getLclTypeEnv
431        ; loc <- getCtLoc skol_info
432        ; emitImplication $ Implic { ic_untch = untch
433                                   , ic_env = lcl_env
434                                   , ic_skols = mkVarSet skol_tvs
435                                   , ic_given = given
436                                   , ic_wanted = wanted
437                                   , ic_insol  = insolubleWC wanted
438                                   , ic_binds = ev_binds_var
439                                   , ic_loc = loc }
440
441        ; return (TcEvBinds ev_binds_var, result) } }
442 \end{code}
443
444 %************************************************************************
445 %*                                                                      *
446                 Boxy unification
447 %*                                                                      *
448 %************************************************************************
449
450 The exported functions are all defined as versions of some
451 non-exported generic functions.
452
453 \begin{code}
454 ---------------
455 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
456 -- Actual and expected types
457 -- Returns a coercion : ty1 ~ ty2
458 unifyType ty1 ty2 = uType [] ty1 ty2
459
460 ---------------
461 unifyPred :: PredType -> PredType -> TcM CoercionI
462 -- Actual and expected types
463 unifyPred p1 p2 = uPred [UnifyOrigin (mkPredTy p1) (mkPredTy p2)] p1 p2
464
465 ---------------
466 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
467 -- Actual and expected types
468 unifyTheta theta1 theta2
469   = do  { checkTc (equalLength theta1 theta2)
470                   (vcat [ptext (sLit "Contexts differ in length"),
471                          nest 2 $ parens $ ptext (sLit "Use -XRelaxedPolyRec to allow this")])
472         ; zipWithM unifyPred theta1 theta2 }
473 \end{code}
474
475 @unifyTypeList@ takes a single list of @TauType@s and unifies them
476 all together.  It is used, for example, when typechecking explicit
477 lists, when all the elts should be of the same type.
478
479 \begin{code}
480 unifyTypeList :: [TcTauType] -> TcM ()
481 unifyTypeList []                 = return ()
482 unifyTypeList [_]                = return ()
483 unifyTypeList (ty1:tys@(ty2:_)) = do { _ <- unifyType ty1 ty2
484                                      ; unifyTypeList tys }
485 \end{code}
486
487 %************************************************************************
488 %*                                                                      *
489                  uType and friends                                                                      
490 %*                                                                      *
491 %************************************************************************
492
493 uType is the heart of the unifier.  Each arg occurs twice, because
494 we want to report errors in terms of synomyms if possible.  The first of
495 the pair is used in error messages only; it is always the same as the
496 second, except that if the first is a synonym then the second may be a
497 de-synonym'd version.  This way we get better error messages.
498
499 \begin{code}
500 data SwapFlag 
501   = NotSwapped  -- Args are: actual,   expected
502   | IsSwapped   -- Args are: expected, actual
503
504 instance Outputable SwapFlag where
505   ppr IsSwapped  = ptext (sLit "Is-swapped")
506   ppr NotSwapped = ptext (sLit "Not-swapped")
507
508 unSwap :: SwapFlag -> (a->a->b) -> a -> a -> b
509 unSwap NotSwapped f a b = f a b
510 unSwap IsSwapped  f a b = f b a
511
512 ------------
513 uType, uType_np, uType_defer
514   :: [EqOrigin]
515   -> TcType    -- ty1 is the *actual* type
516   -> TcType    -- ty2 is the *expected* type
517   -> TcM CoercionI
518
519 --------------
520 -- It is always safe to defer unification to the main constraint solver
521 -- See Note [Deferred unification]
522 uType_defer (item : origin) ty1 ty2
523   = wrapEqCtxt origin $
524     do { co_var <- newWantedCoVar ty1 ty2
525        ; loc <- getCtLoc (TypeEqOrigin item)
526        ; emitFlat (mkEvVarX co_var loc)
527
528        -- Error trace only
529        ; ctxt <- getErrCtxt
530        ; doc <- mkErrInfo emptyTidyEnv ctxt
531        ; traceTc "utype_defer" (vcat [ppr co_var, ppr ty1, ppr ty2, ppr origin, doc])
532
533        ; return $ ACo $ mkTyVarTy co_var }
534 uType_defer [] _ _
535   = panic "uType_defer"
536
537 --------------
538 -- Push a new item on the origin stack (the most common case)
539 uType origin ty1 ty2  -- Push a new item on the origin stack
540   = uType_np (pushOrigin ty1 ty2 origin) ty1 ty2
541
542 --------------
543 -- unify_np (short for "no push" on the origin stack) does the work
544 uType_np origin orig_ty1 orig_ty2
545   = do { traceTc "u_tys " $ vcat 
546               [ sep [ ppr orig_ty1, text "~", ppr orig_ty2]
547               , ppr origin]
548        ; coi <- go orig_ty1 orig_ty2
549        ; case coi of
550             ACo co -> traceTc "u_tys yields coercion:" (ppr co)
551             IdCo _ -> traceTc "u_tys yields no coercion" empty
552        ; return coi }
553   where
554     bale_out :: [EqOrigin] -> TcM a
555     bale_out origin = failWithMisMatch origin
556
557     go :: TcType -> TcType -> TcM CoercionI
558         -- The arguments to 'go' are always semantically identical 
559         -- to orig_ty{1,2} except for looking through type synonyms
560
561         -- Variables; go for uVar
562         -- Note that we pass in *original* (before synonym expansion), 
563         -- so that type variables tend to get filled in with 
564         -- the most informative version of the type
565     go (TyVarTy tyvar1) ty2 = uVar origin NotSwapped tyvar1 ty2
566     go ty1 (TyVarTy tyvar2) = uVar origin IsSwapped  tyvar2 ty1
567
568         -- Expand synonyms: 
569         --      see Note [Unification and synonyms]
570         -- Do this after the variable case so that we tend to unify
571         -- variables with un-expanded type synonym
572         --
573         -- Also NB that we recurse to 'go' so that we don't push a
574         -- new item on the origin stack. As a result if we have
575         --   type Foo = Int
576         -- and we try to unify  Foo ~ Bool
577         -- we'll end up saying "can't match Foo with Bool"
578         -- rather than "can't match "Int with Bool".  See Trac #4535.
579     go ty1 ty2
580       | Just ty1' <- tcView ty1 = go ty1' ty2
581       | Just ty2' <- tcView ty2 = go ty1  ty2'
582              
583
584         -- Predicates
585     go (PredTy p1) (PredTy p2) = uPred origin p1 p2
586
587         -- Coercion functions: (t1a ~ t1b) => t1c  ~  (t2a ~ t2b) => t2c
588     go ty1 ty2 
589       | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe ty1, 
590         Just (t2a,t2b,t2c) <- splitCoPredTy_maybe ty2
591       = do { co1 <- uType origin t1a t2a 
592            ; co2 <- uType origin t1b t2b
593            ; co3 <- uType origin t1c t2c 
594            ; return $ mkCoPredCoI co1 co2 co3 }
595
596         -- Functions (or predicate functions) just check the two parts
597     go (FunTy fun1 arg1) (FunTy fun2 arg2)
598       = do { coi_l <- uType origin fun1 fun2
599            ; coi_r <- uType origin arg1 arg2
600            ; return $ mkFunTyCoI coi_l coi_r }
601
602         -- Always defer if a type synonym family (type function)
603         -- is involved.  (Data families behave rigidly.)
604     go ty1@(TyConApp tc1 _) ty2
605       | isSynFamilyTyCon tc1 = uType_defer origin ty1 ty2   
606     go ty1 ty2@(TyConApp tc2 _)
607       | isSynFamilyTyCon tc2 = uType_defer origin ty1 ty2   
608
609     go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
610       | tc1 == tc2         -- See Note [TyCon app]
611       = do { cois <- uList origin uType tys1 tys2
612            ; return $ mkTyConAppCoI tc1 cois }
613      
614         -- See Note [Care with type applications]
615     go (AppTy s1 t1) ty2
616       | Just (s2,t2) <- tcSplitAppTy_maybe ty2
617       = do { coi_s <- uType_np origin s1 s2  -- See Note [Unifying AppTy]
618            ; coi_t <- uType origin t1 t2        
619            ; return $ mkAppTyCoI coi_s coi_t }
620
621     go ty1 (AppTy s2 t2)
622       | Just (s1,t1) <- tcSplitAppTy_maybe ty1
623       = do { coi_s <- uType_np origin s1 s2
624            ; coi_t <- uType origin t1 t2
625            ; return $ mkAppTyCoI coi_s coi_t }
626
627     go ty1 ty2
628       | tcIsForAllTy ty1 || tcIsForAllTy ty2 
629       = unifySigmaTy origin ty1 ty2
630
631         -- Anything else fails
632     go _ _ = bale_out origin
633
634 unifySigmaTy :: [EqOrigin] -> TcType -> TcType -> TcM CoercionI
635 unifySigmaTy origin ty1 ty2
636   = do { let (tvs1, body1) = tcSplitForAllTys ty1
637              (tvs2, body2) = tcSplitForAllTys ty2
638        ; unless (equalLength tvs1 tvs2) (failWithMisMatch origin)
639        ; skol_tvs <- tcInstSkolTyVars tvs1
640                   -- Get location from monad, not from tvs1
641        ; let tys      = mkTyVarTys skol_tvs
642              in_scope = mkInScopeSet (mkVarSet skol_tvs)
643              phi1     = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
644              phi2     = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
645 --             untch = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
646
647        ; ((coi, _untch), lie) <- captureConstraints $ 
648                                  captureUntouchables $ 
649                                  uType origin phi1 phi2
650           -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
651          ; when (any (`elemVarSet` tyVarsOfWC lie) skol_tvs)
652               (failWithMisMatch origin) -- ToDo: give details from bad_lie
653
654        ; emitConstraints lie
655        ; return (foldr mkForAllTyCoI coi skol_tvs) }
656
657 ----------
658 uPred :: [EqOrigin] -> PredType -> PredType -> TcM CoercionI
659 uPred origin (IParam n1 t1) (IParam n2 t2)
660   | n1 == n2
661   = do { coi <- uType origin t1 t2
662        ; return $ mkIParamPredCoI n1 coi }
663 uPred origin (ClassP c1 tys1) (ClassP c2 tys2)
664   | c1 == c2 
665   = do { cois <- uList origin uType tys1 tys2
666           -- Guaranteed equal lengths because the kinds check
667        ; return $ mkClassPPredCoI c1 cois }
668 uPred origin (EqPred ty1a ty1b) (EqPred ty2a ty2b)
669   = do { coia <- uType origin ty1a ty2a
670        ; coib <- uType origin ty1b ty2b
671        ; return $ mkEqPredCoI coia coib }
672
673 uPred origin _ _ = failWithMisMatch origin
674
675 ---------------
676 uList :: [EqOrigin] 
677       -> ([EqOrigin] -> a -> a -> TcM b)
678       -> [a] -> [a] -> TcM [b]
679 -- Unify corresponding elements of two lists of types, which
680 -- should be of equal length.  We charge down the list explicitly so that
681 -- we can complain if their lengths differ.
682 uList _       _     []         []        = return []
683 uList origin unify (ty1:tys1) (ty2:tys2) = do { x  <- unify origin ty1 ty2;
684                                               ; xs <- uList origin unify tys1 tys2
685                                               ; return (x:xs) }
686 uList origin _ _ _ = failWithMisMatch origin
687        -- See Note [Mismatched type lists and application decomposition]
688
689 \end{code}
690
691 Note [Care with type applications]
692 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
693 Note: type applications need a bit of care!
694 They can match FunTy and TyConApp, so use splitAppTy_maybe
695 NB: we've already dealt with type variables and Notes,
696 so if one type is an App the other one jolly well better be too
697
698 Note [Unifying AppTy]
699 ~~~~~~~~~~~~~~~~~~~~~
700 Considerm unifying  (m Int) ~ (IO Int) where m is a unification variable 
701 that is now bound to (say) (Bool ->).  Then we want to report 
702      "Can't unify (Bool -> Int) with (IO Int)
703 and not 
704      "Can't unify ((->) Bool) with IO"
705 That is why we use the "_np" variant of uType, which does not alter the error
706 message.
707
708 Note [TyCon app]
709 ~~~~~~~~~~~~~~~~
710 When we find two TyConApps, the argument lists are guaranteed equal
711 length.  Reason: intially the kinds of the two types to be unified is
712 the same. The only way it can become not the same is when unifying two
713 AppTys (f1 a1)~(f2 a2).  In that case there can't be a TyConApp in
714 the f1,f2 (because it'd absorb the app).  If we unify f1~f2 first,
715 which we do, that ensures that f1,f2 have the same kind; and that
716 means a1,a2 have the same kind.  And now the argument repeats.
717
718 Note [Mismatched type lists and application decomposition]
719 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
720 When we find two TyConApps, you might think that the argument lists 
721 are guaranteed equal length.  But they aren't. Consider matching
722         w (T x) ~ Foo (T x y)
723 We do match (w ~ Foo) first, but in some circumstances we simply create
724 a deferred constraint; and then go ahead and match (T x ~ T x y).
725 This came up in Trac #3950.
726
727 So either 
728    (a) either we must check for identical argument kinds 
729        when decomposing applications,
730   
731    (b) or we must be prepared for ill-kinded unification sub-problems
732
733 Currently we adopt (b) since it seems more robust -- no need to maintain
734 a global invariant.
735
736 Note [Unification and synonyms]
737 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
738 If you are tempted to make a short cut on synonyms, as in this
739 pseudocode...
740
741    uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
742      = if (con1 == con2) then
743    -- Good news!  Same synonym constructors, so we can shortcut
744    -- by unifying their arguments and ignoring their expansions.
745    unifyTypepeLists args1 args2
746     else
747    -- Never mind.  Just expand them and try again
748    uTys ty1 ty2
749
750 then THINK AGAIN.  Here is the whole story, as detected and reported
751 by Chris Okasaki:
752
753 Here's a test program that should detect the problem:
754
755         type Bogus a = Int
756         x = (1 :: Bogus Char) :: Bogus Bool
757
758 The problem with [the attempted shortcut code] is that
759
760         con1 == con2
761
762 is not a sufficient condition to be able to use the shortcut!
763 You also need to know that the type synonym actually USES all
764 its arguments.  For example, consider the following type synonym
765 which does not use all its arguments.
766
767         type Bogus a = Int
768
769 If you ever tried unifying, say, (Bogus Char) with )Bogus Bool), the
770 unifier would blithely try to unify Char with Bool and would fail,
771 even though the expanded forms (both Int) should match. Similarly,
772 unifying (Bogus Char) with (Bogus t) would unnecessarily bind t to
773 Char.
774
775 ... You could explicitly test for the problem synonyms and mark them
776 somehow as needing expansion, perhaps also issuing a warning to the
777 user.
778
779 Note [Deferred Unification]
780 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
781 We may encounter a unification ty1 ~ ty2 that cannot be performed syntactically,
782 and yet its consistency is undetermined. Previously, there was no way to still
783 make it consistent. So a mismatch error was issued.
784
785 Now these unfications are deferred until constraint simplification, where type
786 family instances and given equations may (or may not) establish the consistency.
787 Deferred unifications are of the form
788                 F ... ~ ...
789 or              x ~ ...
790 where F is a type function and x is a type variable.
791 E.g.
792         id :: x ~ y => x -> y
793         id e = e
794
795 involves the unfication x = y. It is deferred until we bring into account the
796 context x ~ y to establish that it holds.
797
798 If available, we defer original types (rather than those where closed type
799 synonyms have already been expanded via tcCoreView).  This is, as usual, to
800 improve error messages.
801
802
803 %************************************************************************
804 %*                                                                      *
805                  uVar and friends
806 %*                                                                      *
807 %************************************************************************
808
809 @uVar@ is called when at least one of the types being unified is a
810 variable.  It does {\em not} assume that the variable is a fixed point
811 of the substitution; rather, notice that @uVar@ (defined below) nips
812 back into @uTys@ if it turns out that the variable is already bound.
813
814 \begin{code}
815 uVar :: [EqOrigin] -> SwapFlag -> TcTyVar -> TcTauType -> TcM CoercionI
816 uVar origin swapped tv1 ty2
817   = do  { traceTc "uVar" (vcat [ ppr origin
818                                 , ppr swapped
819                                 , ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
820                                 , nest 2 (ptext (sLit " ~ "))
821                                 , ppr ty2 <+> dcolon <+> ppr (typeKind ty2)])
822         ; details <- lookupTcTyVar tv1
823         ; case details of
824             Filled ty1  -> unSwap swapped (uType_np origin) ty1 ty2
825             Unfilled details1 -> uUnfilledVar origin swapped tv1 details1 ty2
826         }
827
828 ----------------
829 uUnfilledVar :: [EqOrigin]
830              -> SwapFlag
831              -> TcTyVar -> TcTyVarDetails       -- Tyvar 1
832              -> TcTauType                       -- Type 2
833              -> TcM CoercionI
834 -- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
835 --            It might be a skolem, or untouchable, or meta
836
837 uUnfilledVar origin swapped tv1 details1 (TyVarTy tv2)
838   | tv1 == tv2  -- Same type variable => no-op
839   = return (IdCo (mkTyVarTy tv1))
840
841   | otherwise  -- Distinct type variables
842   = do  { lookup2 <- lookupTcTyVar tv2
843         ; case lookup2 of
844             Filled ty2'       -> uUnfilledVar origin swapped tv1 details1 ty2' 
845             Unfilled details2 -> uUnfilledVars origin swapped tv1 details1 tv2 details2
846         }
847
848 uUnfilledVar origin swapped tv1 details1 non_var_ty2  -- ty2 is not a type variable
849   = case details1 of
850       MetaTv TauTv ref1 
851         -> do { mb_ty2' <- checkTauTvUpdate tv1 non_var_ty2
852               ; case mb_ty2' of
853                   Nothing   -> do { traceTc "Occ/kind defer" (ppr tv1); defer }
854                   Just ty2' -> updateMeta tv1 ref1 ty2'
855               }
856
857       _other -> do { traceTc "Skolem defer" (ppr tv1); defer }          -- Skolems of all sorts
858   where
859     defer = unSwap swapped (uType_defer origin) (mkTyVarTy tv1) non_var_ty2
860           -- Occurs check or an untouchable: just defer
861           -- NB: occurs check isn't necessarily fatal: 
862           --     eg tv1 occured in type family parameter
863
864 ----------------
865 uUnfilledVars :: [EqOrigin]
866               -> SwapFlag
867               -> TcTyVar -> TcTyVarDetails      -- Tyvar 1
868               -> TcTyVar -> TcTyVarDetails      -- Tyvar 2
869               -> TcM CoercionI
870 -- Invarant: The type variables are distinct,
871 --           Neither is filled in yet
872
873 uUnfilledVars origin swapped tv1 details1 tv2 details2
874   = case (details1, details2) of
875       (MetaTv i1 ref1, MetaTv i2 ref2)
876           | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1 i1 i2
877                          then updateMeta tv1 ref1 ty2
878                          else updateMeta tv2 ref2 ty1
879           | k2_sub_k1 -> updateMeta tv1 ref1 ty2
880
881       (_, MetaTv _ ref2) | k1_sub_k2 -> updateMeta tv2 ref2 ty1
882       (MetaTv _ ref1, _) | k2_sub_k1 -> updateMeta tv1 ref1 ty2
883
884       (_, _) -> unSwap swapped (uType_defer origin) ty1 ty2
885                 -- Defer for skolems of all sorts
886   where
887     k1        = tyVarKind tv1
888     k2        = tyVarKind tv2
889     k1_sub_k2 = k1 `isSubKind` k2
890     k2_sub_k1 = k2 `isSubKind` k1
891     ty1       = mkTyVarTy tv1
892     ty2       = mkTyVarTy tv2
893
894     nicer_to_update_tv1 _         (SigTv _) = True
895     nicer_to_update_tv1 (SigTv _) _         = False
896     nicer_to_update_tv1 _         _         = isSystemName (Var.varName tv1)
897         -- Try not to update SigTvs; and try to update sys-y type
898         -- variables in preference to ones gotten (say) by
899         -- instantiating a polymorphic function with a user-written
900         -- type sig
901
902 ----------------
903 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
904 --    (checkTauTvUpdate tv ty)
905 -- We are about to update the TauTv tv with ty.
906 -- Check (a) that tv doesn't occur in ty (occurs check)
907 --       (b) that kind(ty) is a sub-kind of kind(tv)
908 --       (c) that ty does not contain any type families, see Note [Type family sharing]
909 -- 
910 -- We have two possible outcomes:
911 -- (1) Return the type to update the type variable with, 
912 --        [we know the update is ok]
913 -- (2) Return Nothing,
914 --        [the update might be dodgy]
915 --
916 -- Note that "Nothing" does not mean "definite error".  For example
917 --   type family F a
918 --   type instance F Int = Int
919 -- consider
920 --   a ~ F a
921 -- This is perfectly reasonable, if we later get a ~ Int.  For now, though,
922 -- we return Nothing, leaving it to the later constraint simplifier to
923 -- sort matters out.
924
925 checkTauTvUpdate tv ty
926   = do { ty' <- zonkTcType ty
927        ; if typeKind ty' `isSubKind` tyVarKind tv then
928            case ok ty' of 
929              Nothing -> return Nothing 
930              Just ty'' -> return (Just ty'')
931          else return Nothing }
932
933   where ok :: TcType -> Maybe TcType 
934         ok (TyVarTy tv') | not (tv == tv') = Just (TyVarTy tv') 
935         ok this_ty@(TyConApp tc tys) 
936           | not (isSynFamilyTyCon tc), Just tys' <- allMaybes (map ok tys) 
937           = Just (TyConApp tc tys') 
938           | isSynTyCon tc, Just ty_expanded <- tcView this_ty
939           = ok ty_expanded -- See Note [Type synonyms and the occur check] 
940         ok (PredTy sty) | Just sty' <- ok_pred sty = Just (PredTy sty') 
941         ok (FunTy arg res) | Just arg' <- ok arg, Just res' <- ok res
942                            = Just (FunTy arg' res') 
943         ok (AppTy fun arg) | Just fun' <- ok fun, Just arg' <- ok arg 
944                            = Just (AppTy fun' arg') 
945         ok (ForAllTy tv1 ty1) | Just ty1' <- ok ty1 = Just (ForAllTy tv1 ty1') 
946         -- Fall-through 
947         ok _ty = Nothing 
948        
949         ok_pred (IParam nm ty) | Just ty' <- ok ty = Just (IParam nm ty') 
950         ok_pred (ClassP cl tys) 
951           | Just tys' <- allMaybes (map ok tys) 
952           = Just (ClassP cl tys') 
953         ok_pred (EqPred ty1 ty2) 
954           | Just ty1' <- ok ty1, Just ty2' <- ok ty2 
955           = Just (EqPred ty1' ty2') 
956         -- Fall-through 
957         ok_pred _pty = Nothing 
958
959 \end{code}
960
961 Note [Type synonyms and the occur check]
962 ~~~~~~~~~~~~~~~~~~~~
963 Generally speaking we need to update a variable with type synonyms not expanded, which
964 improves later error messages, except for when looking inside a type synonym may help resolve
965 a spurious occurs check error. Consider: 
966           type A a = ()
967
968           f :: (A a -> a -> ()) -> ()
969           f = \ _ -> ()
970
971           x :: ()
972           x = f (\ x p -> p x)
973
974 We will eventually get a constraint of the form t ~ A t. The ok function above will 
975 properly expand the type (A t) to just (), which is ok to be unified with t. If we had
976 unified with the original type A t, we would lead the type checker into an infinite loop. 
977
978 Hence, if the occurs check fails for a type synonym application, then (and *only* then), 
979 the ok function expands the synonym to detect opportunities for occurs check success using
980 the underlying definition of the type synonym. 
981
982 The same applies later on in the constraint interaction code; see TcInteract, 
983 function @occ_check_ok@. 
984
985
986 Note [Type family sharing]
987 ~~~~~~~~~~~~~~ 
988 We must avoid eagerly unifying type variables to types that contain function symbols, 
989 because this may lead to loss of sharing, and in turn, in very poor performance of the
990 constraint simplifier. Assume that we have a wanted constraint: 
991
992   m1 ~ [F m2], 
993   m2 ~ [F m3], 
994   m3 ~ [F m4], 
995   D m1, 
996   D m2, 
997   D m3 
998
999 where D is some type class. If we eagerly unify m1 := [F m2], m2 := [F m3], m3 := [F m2], 
1000 then, after zonking, our constraint simplifier will be faced with the following wanted 
1001 constraint: 
1002
1003   D [F [F [F m4]]], 
1004   D [F [F m4]], 
1005   D [F m4] 
1006
1007 which has to be flattened by the constraint solver. However, because the sharing is lost, 
1008 an polynomially larger number of flatten skolems will be created and the constraint sets 
1009 we are working with will be polynomially larger. 
1010
1011 Instead, if we defer the unifications m1 := [F m2], etc. we will only be generating three 
1012 flatten skolems, which is the maximum possible sharing arising from the original constraint. 
1013
1014 \begin{code}
1015 data LookupTyVarResult  -- The result of a lookupTcTyVar call
1016   = Unfilled TcTyVarDetails     -- SkolemTv or virgin MetaTv
1017   | Filled   TcType
1018
1019 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
1020 lookupTcTyVar tyvar 
1021   | MetaTv _ ref <- details
1022   = do { meta_details <- readMutVar ref
1023        ; case meta_details of
1024            Indirect ty -> return (Filled ty)
1025            Flexi -> do { is_untch <- isUntouchable tyvar
1026                        ; let    -- Note [Unifying untouchables]
1027                              ret_details | is_untch  = vanillaSkolemTv
1028                                          | otherwise = details
1029                        ; return (Unfilled ret_details) } }
1030   | otherwise
1031   = return (Unfilled details)
1032   where
1033     details = ASSERT2( isTcTyVar tyvar, ppr tyvar )
1034               tcTyVarDetails tyvar
1035
1036 updateMeta :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM CoercionI
1037 updateMeta tv1 ref1 ty2
1038   = do { writeMetaTyVarRef tv1 ref1 ty2
1039        ; return (IdCo ty2) }
1040 \end{code}
1041
1042 Note [Unifying untouchables]
1043 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1044 We treat an untouchable type variable as if it was a skolem.  That
1045 ensures it won't unify with anything.  It's a slight had, because
1046 we return a made-up TcTyVarDetails, but I think it works smoothly.
1047
1048
1049 %************************************************************************
1050 %*                                                                      *
1051         Errors and contexts
1052 %*                                                                      *
1053 %************************************************************************
1054
1055 \begin{code}
1056 pushOrigin :: TcType -> TcType -> [EqOrigin] -> [EqOrigin]
1057 pushOrigin ty_act ty_exp origin
1058   = UnifyOrigin { uo_actual = ty_act, uo_expected = ty_exp } : origin
1059
1060 ---------------
1061 wrapEqCtxt :: [EqOrigin] -> TcM a -> TcM a
1062 -- Build a suitable error context from the origin and do the thing inside
1063 -- The "couldn't match" error comes from the innermost item on the stack,
1064 -- and, if there is more than one item, the "Expected/inferred" part
1065 -- comes from the outermost item
1066 wrapEqCtxt []    thing_inside = thing_inside
1067 wrapEqCtxt items thing_inside = addErrCtxtM (unifyCtxt (last items)) thing_inside
1068
1069 ---------------
1070 failWithMisMatch :: [EqOrigin] -> TcM a
1071 -- Generate the message when two types fail to match,
1072 -- going to some trouble to make it helpful.
1073 -- We take the failing types from the top of the origin stack
1074 -- rather than reporting the particular ones we are looking 
1075 -- at right now
1076 failWithMisMatch (item:origin)
1077   = wrapEqCtxt origin $
1078     do  { ty_act <- zonkTcType (uo_actual item)
1079         ; ty_exp <- zonkTcType (uo_expected item)
1080         ; env0 <- tcInitTidyEnv
1081         ; let (env1, pp_exp) = tidyOpenType env0 ty_exp
1082               (env2, pp_act) = tidyOpenType env1 ty_act
1083         ; failWithTcM (env2, misMatchMsg pp_act pp_exp) }
1084 failWithMisMatch [] 
1085   = panic "failWithMisMatch"
1086
1087 misMatchMsg :: TcType -> TcType -> SDoc
1088 misMatchMsg ty_act ty_exp
1089   = sep [ ptext (sLit "Couldn't match expected type") <+> quotes (ppr ty_exp)
1090         , nest 12 $   ptext (sLit "with actual type") <+> quotes (ppr ty_act)]
1091 \end{code}
1092
1093
1094 -----------------------------------------
1095         UNUSED FOR NOW
1096 -----------------------------------------
1097
1098 ----------------
1099 ----------------
1100 -- If an error happens we try to figure out whether the function
1101 -- function has been given too many or too few arguments, and say so.
1102 addSubCtxt :: InstOrigin -> TcType -> TcType -> TcM a -> TcM a
1103 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1104   = addErrCtxtM mk_err thing_inside
1105   where
1106     mk_err tidy_env
1107       = do { exp_ty' <- zonkTcType expected_res_ty
1108            ; act_ty' <- zonkTcType actual_res_ty
1109            ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1110                  (env2, act_ty'') = tidyOpenType env1     act_ty'
1111                  (exp_args, _)    = tcSplitFunTys exp_ty''
1112                  (act_args, _)    = tcSplitFunTys act_ty''
1113
1114                  len_act_args     = length act_args
1115                  len_exp_args     = length exp_args
1116
1117                  message = case orig of
1118                              OccurrenceOf fun
1119                                   | len_exp_args < len_act_args -> wrongArgsCtxt "too few"  fun
1120                                   | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1121                              _ -> mkExpectedActualMsg act_ty'' exp_ty''
1122            ; return (env2, message) }
1123
1124
1125 %************************************************************************
1126 %*                                                                      *
1127                 Kind unification
1128 %*                                                                      *
1129 %************************************************************************
1130
1131 Unifying kinds is much, much simpler than unifying types.
1132
1133 \begin{code}
1134 matchExpectedFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1135 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1136
1137 matchExpectedFunKind (TyVarTy kvar) = do
1138     maybe_kind <- readKindVar kvar
1139     case maybe_kind of
1140       Indirect fun_kind -> matchExpectedFunKind fun_kind
1141       Flexi ->
1142           do { arg_kind <- newKindVar
1143              ; res_kind <- newKindVar
1144              ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1145              ; return (Just (arg_kind,res_kind)) }
1146
1147 matchExpectedFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1148 matchExpectedFunKind _                         = return Nothing
1149
1150 -----------------
1151 unifyKind :: TcKind                 -- Expected
1152           -> TcKind                 -- Actual
1153           -> TcM ()
1154
1155 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1156   | isSubKindCon kc2 kc1 = return ()
1157
1158 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1159   = do { unifyKind a2 a1; unifyKind r1 r2 }
1160                 -- Notice the flip in the argument,
1161                 -- so that the sub-kinding works right
1162 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1163 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1164 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1165
1166 ----------------
1167 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1168 uKVar swapped kv1 k2
1169   = do  { mb_k1 <- readKindVar kv1
1170         ; case mb_k1 of
1171             Flexi -> uUnboundKVar swapped kv1 k2
1172             Indirect k1 | swapped   -> unifyKind k2 k1
1173                         | otherwise -> unifyKind k1 k2 }
1174
1175 ----------------
1176 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1177 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1178   | kv1 == kv2 = return ()
1179   | otherwise   -- Distinct kind variables
1180   = do  { mb_k2 <- readKindVar kv2
1181         ; case mb_k2 of
1182             Indirect k2 -> uUnboundKVar swapped kv1 k2
1183             Flexi -> writeKindVar kv1 k2 }
1184
1185 uUnboundKVar swapped kv1 non_var_k2
1186   = do  { k2' <- zonkTcKind non_var_k2
1187         ; kindOccurCheck kv1 k2'
1188         ; k2'' <- kindSimpleKind swapped k2'
1189                 -- KindVars must be bound only to simple kinds
1190                 -- Polarities: (kindSimpleKind True ?) succeeds
1191                 -- returning *, corresponding to unifying
1192                 --      expected: ?
1193                 --      actual:   kind-ver
1194         ; writeKindVar kv1 k2'' }
1195
1196 ----------------
1197 kindOccurCheck :: TyVar -> Type -> TcM ()
1198 kindOccurCheck kv1 k2   -- k2 is zonked
1199   = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1200   where
1201     not_in (TyVarTy kv2) = kv1 /= kv2
1202     not_in (FunTy a2 r2) = not_in a2 && not_in r2
1203     not_in _             = True
1204
1205 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1206 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1207 -- If the flag is False, it requires k <: sk
1208 -- E.g.         kindSimpleKind False ?? = *
1209 -- What about (kv -> *) ~ ?? -> *
1210 kindSimpleKind orig_swapped orig_kind
1211   = go orig_swapped orig_kind
1212   where
1213     go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1214                              ; k2' <- go sw k2
1215                              ; return (mkArrowKind k1' k2') }
1216     go True k
1217      | isOpenTypeKind k = return liftedTypeKind
1218      | isArgTypeKind k  = return liftedTypeKind
1219     go _ k
1220      | isLiftedTypeKind k   = return liftedTypeKind
1221      | isUnliftedTypeKind k = return unliftedTypeKind
1222     go _ k@(TyVarTy _) = return k -- KindVars are always simple
1223     go _ _ = failWithTc (ptext (sLit "Unexpected kind unification failure:")
1224                                   <+> ppr orig_swapped <+> ppr orig_kind)
1225         -- I think this can't actually happen
1226
1227 -- T v = MkT v           v must be a type
1228 -- T v w = MkT (v -> w)  v must not be an umboxed tuple
1229
1230 unifyKindMisMatch :: TcKind -> TcKind -> TcM ()
1231 unifyKindMisMatch ty1 ty2 = do
1232     ty1' <- zonkTcKind ty1
1233     ty2' <- zonkTcKind ty2
1234     let
1235         msg = hang (ptext (sLit "Couldn't match kind"))
1236                    2 (sep [quotes (ppr ty1'), 
1237                            ptext (sLit "against"), 
1238                            quotes (ppr ty2')])
1239     failWithTc msg
1240
1241 ----------------
1242 kindOccurCheckErr :: Var -> Type -> SDoc
1243 kindOccurCheckErr tyvar ty
1244   = hang (ptext (sLit "Occurs check: cannot construct the infinite kind:"))
1245        2 (sep [ppr tyvar, char '=', ppr ty])
1246 \end{code}
1247
1248 %************************************************************************
1249 %*                                                                      *
1250 \subsection{Checking signature type variables}
1251 %*                                                                      *
1252 %************************************************************************
1253
1254 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1255 are not mentioned in the environment.  In particular:
1256
1257         (a) Not mentioned in the type of a variable in the envt
1258                 eg the signature for f in this:
1259
1260                         g x = ... where
1261                                         f :: a->[a]
1262                                         f y = [x,y]
1263
1264                 Here, f is forced to be monorphic by the free occurence of x.
1265
1266         (d) Not (unified with another type variable that is) in scope.
1267                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1268             when checking the expression type signature, we find that
1269             even though there is nothing in scope whose type mentions r,
1270             nevertheless the type signature for the expression isn't right.
1271
1272             Another example is in a class or instance declaration:
1273                 class C a where
1274                    op :: forall b. a -> b
1275                    op x = x
1276             Here, b gets unified with a
1277
1278 Before doing this, the substitution is applied to the signature type variable.
1279
1280 -- \begin{code}
1281 checkSigTyVars :: [TcTyVar] -> TcM ()
1282 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1283
1284 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1285 -- The extra_tvs can include boxy type variables;
1286 --      e.g. TcMatches.tcCheckExistentialPat
1287 checkSigTyVarsWrt extra_tvs sig_tvs
1288   = do  { extra_tvs' <- zonkTcTyVarsAndFV extra_tvs
1289         ; check_sig_tyvars extra_tvs' sig_tvs }
1290
1291 check_sig_tyvars
1292         :: TcTyVarSet   -- Global type variables. The universally quantified
1293                         --      tyvars should not mention any of these
1294                         --      Guaranteed already zonked.
1295         -> [TcTyVar]    -- Universally-quantified type variables in the signature
1296                         --      Guaranteed to be skolems
1297         -> TcM ()
1298 check_sig_tyvars _ []
1299   = return ()
1300 check_sig_tyvars extra_tvs sig_tvs
1301   = ASSERT( all isTcTyVar sig_tvs && all isSkolemTyVar sig_tvs )
1302     do  { gbl_tvs <- tcGetGlobalTyVars
1303         ; traceTc "check_sig_tyvars" $ vcat 
1304                [ text "sig_tys" <+> ppr sig_tvs
1305                , text "gbl_tvs" <+> ppr gbl_tvs
1306                , text "extra_tvs" <+> ppr extra_tvs]
1307
1308         ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1309         ; when (any (`elemVarSet` env_tvs) sig_tvs)
1310                (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1311         }
1312
1313 bleatEscapedTvs :: TcTyVarSet   -- The global tvs
1314                 -> [TcTyVar]    -- The possibly-escaping type variables
1315                 -> [TcTyVar]    -- The zonked versions thereof
1316                 -> TcM ()
1317 -- Complain about escaping type variables
1318 -- We pass a list of type variables, at least one of which
1319 -- escapes.  The first list contains the original signature type variable,
1320 -- while the second  contains the type variable it is unified to (usually itself)
1321 bleatEscapedTvs globals sig_tvs zonked_tvs
1322   = do  { env0 <- tcInitTidyEnv
1323         ; let (env1, tidy_tvs)        = tidyOpenTyVars env0 sig_tvs
1324               (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1325
1326         ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1327         ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1328   where
1329     main_msg = ptext (sLit "Inferred type is less polymorphic than expected")
1330
1331     check (tidy_env, msgs) (sig_tv, zonked_tv)
1332       | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1333       | otherwise
1334       = do { lcl_env <- getLclTypeEnv
1335            ; (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) lcl_env tidy_env
1336            ; return (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1337
1338 -----------------------
1339 escape_msg :: Var -> Var -> [SDoc] -> SDoc
1340 escape_msg sig_tv zonked_tv globs
1341   | notNull globs
1342   = vcat [sep [msg, ptext (sLit "is mentioned in the environment:")],
1343           nest 2 (vcat globs)]
1344   | otherwise
1345   = msg <+> ptext (sLit "escapes")
1346         -- Sigh.  It's really hard to give a good error message
1347         -- all the time.   One bad case is an existential pattern match.
1348         -- We rely on the "When..." context to help.
1349   where
1350     msg = ptext (sLit "Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1351     is_bound_to
1352         | sig_tv == zonked_tv = empty
1353         | otherwise = ptext (sLit "is unified with") <+> quotes (ppr zonked_tv) <+> ptext (sLit "which")
1354 -- \end{code}
1355
1356 These two context are used with checkSigTyVars
1357
1358 \begin{code}
1359 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1360         -> TidyEnv -> TcM (TidyEnv, Message)
1361 sigCtxt id sig_tvs sig_theta sig_tau tidy_env = do
1362     actual_tau <- zonkTcType sig_tau
1363     let
1364         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
1365         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1366         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1367         sub_msg = vcat [ptext (sLit "Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1368                         ptext (sLit "Type to generalise:") <+> pprType tidy_actual_tau
1369                    ]
1370         msg = vcat [ptext (sLit "When trying to generalise the type inferred for") <+> quotes (ppr id),
1371                     nest 2 sub_msg]
1372
1373     return (env3, msg)
1374 \end{code}