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