Typechecker performance fixes and flatten skolem bugfixing
[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 TcEnv
34 import TcIface
35 import TcRnMonad
36 import TcType
37 import Type
38 import Coercion
39 import Inst
40 import TyCon
41 import TysWiredIn
42 import Var
43 import VarSet
44 import VarEnv
45 import Name
46 import ErrUtils
47 import BasicTypes
48 import Bag
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 -> SkolemInfo -> 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 skol_info ty_actual ty_expected 
305   | isSigmaTy ty_actual
306   = do { let extra_tvs = tyVarsOfType ty_actual
307        ; (sk_wrap, inst_wrap) 
308             <- tcGen skol_info extra_tvs 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 -> TcTyVarSet -> TcType  
357       -> ([TcTyVar] -> TcRhoType -> TcM result)
358       -> TcM (HsWrapper, result)
359         -- The expression has type: spec_ty -> expected_ty
360
361 tcGen skol_info extra_tvs 
362        expected_ty thing_inside    -- 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         -- In 'free_tvs' 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         -- Conclusion: pass the free vars of the expected_ty to checkConsraints
381         ; let free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
382
383         ; (ev_binds, result) <- checkConstraints skol_info free_tvs tvs' given $
384                                 thing_inside tvs' rho'
385
386         ; return (wrap <.> mkWpLet ev_binds, result) }
387           -- The ev_binds returned by checkConstraints is very
388           -- often empty, in which case mkWpLet is a no-op
389
390 checkConstraints :: SkolemInfo
391                  -> TcTyVarSet          -- Free variables (other than the type envt)
392                                         -- for the skolem escape check
393                  -> [TcTyVar]           -- Skolems
394                  -> [EvVar]             -- Given
395                  -> TcM result
396                  -> TcM (TcEvBinds, result)
397
398 checkConstraints skol_info free_tvs 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 free_tvs 
406                                              skol_tvs given thing_inside
407        ; emitConstraints wanted
408        ; return (ev_binds, result) }
409
410 newImplication :: SkolemInfo -> TcTyVarSet -> [TcTyVar]
411                -> [EvVar] -> TcM result
412                -> TcM (TcEvBinds, WantedConstraints, result)
413 newImplication skol_info free_tvs 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 { gbl_tvs  <- tcGetGlobalTyVars
417        ; free_tvs <- zonkTcTyVarsAndFV free_tvs
418        ; let untch = gbl_tvs `unionVarSet` free_tvs
419
420        ; (result, wanted) <- getConstraints               $ 
421                              setUntouchables untch $
422                              thing_inside
423
424        ; if isEmptyBag wanted && not (hasEqualities given) 
425             -- Optimisation : if there are no wanteds, and the givens
426             -- are sufficiently simple, don't generate an implication
427             -- at all.  Reason for the hasEqualities test:
428             -- we don't want to lose the "inaccessible alternative"
429             -- error check
430          then 
431             return (emptyTcEvBinds, emptyWanteds, result)
432          else do
433        { ev_binds_var <- newTcEvBinds
434        ; lcl_env <- getLclTypeEnv
435        ; loc <- getCtLoc skol_info
436        ; let implic = Implic { ic_untch = untch
437                              , ic_env = lcl_env
438                              , ic_skols = mkVarSet skol_tvs
439                              , ic_scoped = panic "emitImplication"
440                              , ic_given = given
441                              , ic_wanted = wanted
442                              , ic_binds = ev_binds_var
443                              , ic_loc = loc }
444
445        ; return (TcEvBinds ev_binds_var, unitBag (WcImplic implic), result) } }
446 \end{code}
447
448 %************************************************************************
449 %*                                                                      *
450                 Boxy unification
451 %*                                                                      *
452 %************************************************************************
453
454 The exported functions are all defined as versions of some
455 non-exported generic functions.
456
457 \begin{code}
458 ---------------
459 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
460 -- Actual and expected types
461 -- Returns a coercion : ty1 ~ ty2
462 unifyType ty1 ty2 = uType [] ty1 ty2
463
464 ---------------
465 unifyPred :: PredType -> PredType -> TcM CoercionI
466 -- Actual and expected types
467 unifyPred p1 p2 = uPred [UnifyOrigin (mkPredTy p1) (mkPredTy p2)] p1 p2
468
469 ---------------
470 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
471 -- Actual and expected types
472 unifyTheta theta1 theta2
473   = do  { checkTc (equalLength theta1 theta2)
474                   (vcat [ptext (sLit "Contexts differ in length"),
475                          nest 2 $ parens $ ptext (sLit "Use -XRelaxedPolyRec to allow this")])
476         ; zipWithM unifyPred theta1 theta2 }
477 \end{code}
478
479 @unifyTypeList@ takes a single list of @TauType@s and unifies them
480 all together.  It is used, for example, when typechecking explicit
481 lists, when all the elts should be of the same type.
482
483 \begin{code}
484 unifyTypeList :: [TcTauType] -> TcM ()
485 unifyTypeList []                 = return ()
486 unifyTypeList [_]                = return ()
487 unifyTypeList (ty1:tys@(ty2:_)) = do { _ <- unifyType ty1 ty2
488                                      ; unifyTypeList tys }
489 \end{code}
490
491 %************************************************************************
492 %*                                                                      *
493                  uType and friends                                                                      
494 %*                                                                      *
495 %************************************************************************
496
497 uType is the heart of the unifier.  Each arg occurs twice, because
498 we want to report errors in terms of synomyms if possible.  The first of
499 the pair is used in error messages only; it is always the same as the
500 second, except that if the first is a synonym then the second may be a
501 de-synonym'd version.  This way we get better error messages.
502
503 \begin{code}
504 data SwapFlag 
505   = NotSwapped  -- Args are: actual,   expected
506   | IsSwapped   -- Args are: expected, actual
507
508 instance Outputable SwapFlag where
509   ppr IsSwapped  = ptext (sLit "Is-swapped")
510   ppr NotSwapped = ptext (sLit "Not-swapped")
511
512 unSwap :: SwapFlag -> (a->a->b) -> a -> a -> b
513 unSwap NotSwapped f a b = f a b
514 unSwap IsSwapped  f a b = f b a
515
516 ------------
517 uType, uType_np, uType_defer
518   :: [EqOrigin]
519   -> TcType    -- ty1 is the *actual* type
520   -> TcType    -- ty2 is the *expected* type
521   -> TcM CoercionI
522
523 --------------
524 -- It is always safe to defer unification to the main constraint solver
525 -- See Note [Deferred unification]
526 uType_defer (item : origin) ty1 ty2
527   = do { co_var <- newWantedCoVar ty1 ty2
528        ; traceTc "utype_defer" (vcat [ppr co_var, ppr ty1, ppr ty2, ppr origin])
529        ; loc <- getCtLoc (TypeEqOrigin item)
530        ; wrapEqCtxt origin $
531          emitConstraint (WcEvVar (WantedEvVar co_var loc)) 
532        ; return $ ACo $ mkTyVarTy co_var }
533 uType_defer [] _ _
534   = panic "uType_defer"
535
536 --------------
537 -- Push a new item on the origin stack (the most common case)
538 uType origin ty1 ty2  -- Push a new item on the origin stack
539   = uType_np (pushOrigin ty1 ty2 origin) ty1 ty2
540
541 --------------
542 -- unify_np (short for "no push" on the origin stack) does the work
543 uType_np origin orig_ty1 orig_ty2
544   = do { traceTc "u_tys " $ vcat 
545               [ sep [ ppr orig_ty1, text "~", ppr orig_ty2]
546               , ppr origin]
547        ; coi <- go origin orig_ty1 orig_ty2
548        ; case coi of
549             ACo co -> traceTc "u_tys yields coercion:" (ppr co)
550             IdCo _ -> traceTc "u_tys yields no coercion" empty
551        ; return coi }
552   where
553     bale_out :: [EqOrigin] -> TcM a
554     bale_out origin = failWithMisMatch origin
555
556     go :: [EqOrigin] -> TcType -> TcType -> TcM CoercionI
557         -- The arguments to 'go' are always semantically identical 
558         -- to orig_ty{1,2} except for looking through type synonyms
559
560         -- Variables; go for uVar
561         -- Note that we pass in *original* (before synonym expansion), 
562         -- so that type variables tend to get filled in with 
563         -- the most informative version of the type
564     go origin (TyVarTy tyvar1) ty2 = uVar origin NotSwapped tyvar1 ty2
565     go origin ty1 (TyVarTy tyvar2) = uVar origin IsSwapped  tyvar2 ty1
566
567         -- Expand synonyms: 
568         --      see Note [Unification and synonyms]
569         -- Do this after the variable case so that we tend to unify
570         -- variables with un-expended type synonym
571     go origin ty1 ty2
572       | Just ty1' <- tcView ty1 = uType origin ty1' ty2
573       | Just ty2' <- tcView ty2 = uType origin ty1  ty2'
574
575         -- Predicates
576     go origin (PredTy p1) (PredTy p2) = uPred origin p1 p2
577
578         -- Functions; just check the two parts
579     go origin (FunTy fun1 arg1) (FunTy fun2 arg2)
580       = do { coi_l <- uType origin fun1 fun2
581            ; coi_r <- uType origin arg1 arg2
582            ; return $ mkFunTyCoI coi_l coi_r }
583
584         -- Always defer if a type synonym family (type function)
585         -- is involved.  (Data families behave rigidly.)
586     go origin ty1@(TyConApp tc1 _) ty2
587       | isSynFamilyTyCon tc1 = uType_defer origin ty1 ty2   
588     go origin ty1 ty2@(TyConApp tc2 _)
589       | isSynFamilyTyCon tc2 = uType_defer origin ty1 ty2   
590
591     go origin (TyConApp tc1 tys1) (TyConApp tc2 tys2)
592       | tc1 == tc2         -- See Note [TyCon app]
593       = do { cois <- uList origin uType tys1 tys2
594            ; return $ mkTyConAppCoI tc1 cois }
595      
596         -- See Note [Care with type applications]
597     go origin (AppTy s1 t1) ty2
598       | Just (s2,t2) <- tcSplitAppTy_maybe ty2
599       = do { coi_s <- uType_np origin s1 s2  -- See Note [Unifying AppTy]
600            ; coi_t <- uType origin t1 t2        
601            ; return $ mkAppTyCoI coi_s coi_t }
602
603     go origin ty1 (AppTy s2 t2)
604       | Just (s1,t1) <- tcSplitAppTy_maybe ty1
605       = do { coi_s <- uType_np origin s1 s2
606            ; coi_t <- uType origin t1 t2
607            ; return $ mkAppTyCoI coi_s coi_t }
608
609     go _ ty1 ty2
610       | isSigmaTy ty1 || isSigmaTy ty2
611       = unifySigmaTy origin ty1 ty2
612
613         -- Anything else fails
614     go origin _ _ = bale_out origin
615
616 unifySigmaTy :: [EqOrigin] -> TcType -> TcType -> TcM CoercionI
617 unifySigmaTy origin ty1 ty2
618   = do { let (tvs1, body1) = tcSplitForAllTys ty1
619              (tvs2, body2) = tcSplitForAllTys ty2
620        ; unless (equalLength tvs1 tvs2) (failWithMisMatch origin)
621        ; skol_tvs <- tcInstSkolTyVars UnkSkol tvs1     -- Not a helpful SkolemInfo
622                   -- Get location from monad, not from tvs1
623        ; let tys      = mkTyVarTys skol_tvs
624              in_scope = mkInScopeSet (mkVarSet skol_tvs)
625              phi1     = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
626              phi2     = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
627              untch = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
628
629        ; (coi, lie) <- getConstraints $ 
630                        setUntouchables untch $ 
631                        uType origin phi1 phi2
632
633           -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
634        ; let bad_lie  = filterBag is_bad lie
635              is_bad w = any (`elemVarSet` tyVarsOfWanted w) skol_tvs
636        ; when (not (isEmptyBag bad_lie))
637               (failWithMisMatch origin) -- ToDo: give details from bad_lie
638
639        ; emitConstraints lie
640        ; return (foldr mkForAllTyCoI coi skol_tvs) }
641
642 ----------
643 uPred :: [EqOrigin] -> PredType -> PredType -> TcM CoercionI
644 uPred origin (IParam n1 t1) (IParam n2 t2)
645   | n1 == n2
646   = do { coi <- uType origin t1 t2
647        ; return $ mkIParamPredCoI n1 coi }
648 uPred origin (ClassP c1 tys1) (ClassP c2 tys2)
649   | c1 == c2 
650   = do { cois <- uList origin uType tys1 tys2
651           -- Guaranteed equal lengths because the kinds check
652        ; return $ mkClassPPredCoI c1 cois }
653 uPred origin (EqPred ty1a ty1b) (EqPred ty2a ty2b)
654   = do { coia <- uType origin ty1a ty2a
655        ; coib <- uType origin ty1b ty2b
656        ; return $ mkEqPredCoI coia coib }
657
658 uPred origin _ _ = failWithMisMatch origin
659
660 ---------------
661 uList :: [EqOrigin] 
662       -> ([EqOrigin] -> a -> a -> TcM b)
663       -> [a] -> [a] -> TcM [b]
664 -- Unify corresponding elements of two lists of types, which
665 -- should be of equal length.  We charge down the list explicitly so that
666 -- we can complain if their lengths differ.
667 uList _       _     []         []        = return []
668 uList origin unify (ty1:tys1) (ty2:tys2) = do { x  <- unify origin ty1 ty2;
669                                               ; xs <- uList origin unify tys1 tys2
670                                               ; return (x:xs) }
671 uList origin _ _ _ = failWithMisMatch origin
672        -- See Note [Mismatched type lists and application decomposition]
673
674 \end{code}
675
676 Note [Care with type applications]
677 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
678 Note: type applications need a bit of care!
679 They can match FunTy and TyConApp, so use splitAppTy_maybe
680 NB: we've already dealt with type variables and Notes,
681 so if one type is an App the other one jolly well better be too
682
683 Note [Unifying AppTy]
684 ~~~~~~~~~~~~~~~~~~~~~
685 Considerm unifying  (m Int) ~ (IO Int) where m is a unification variable 
686 that is now bound to (say) (Bool ->).  Then we want to report 
687      "Can't unify (Bool -> Int) with (IO Int)
688 and not 
689      "Can't unify ((->) Bool) with IO"
690 That is why we use the "_np" variant of uType, which does not alter the error
691 message.
692
693 Note [TyCon app]
694 ~~~~~~~~~~~~~~~~
695 When we find two TyConApps, the argument lists are guaranteed equal
696 length.  Reason: intially the kinds of the two types to be unified is
697 the same. The only way it can become not the same is when unifying two
698 AppTys (f1 a1)~(f2 a2).  In that case there can't be a TyConApp in
699 the f1,f2 (because it'd absorb the app).  If we unify f1~f2 first,
700 which we do, that ensures that f1,f2 have the same kind; and that
701 means a1,a2 have the same kind.  And now the argument repeats.
702
703 Note [Mismatched type lists and application decomposition]
704 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
705 When we find two TyConApps, you might think that the argument lists 
706 are guaranteed equal length.  But they aren't. Consider matching
707         w (T x) ~ Foo (T x y)
708 We do match (w ~ Foo) first, but in some circumstances we simply create
709 a deferred constraint; and then go ahead and match (T x ~ T x y).
710 This came up in Trac #3950.
711
712 So either 
713    (a) either we must check for identical argument kinds 
714        when decomposing applications,
715   
716    (b) or we must be prepared for ill-kinded unification sub-problems
717
718 Currently we adopt (b) since it seems more robust -- no need to maintain
719 a global invariant.
720
721 Note [Unification and synonyms]
722 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
723 If you are tempted to make a short cut on synonyms, as in this
724 pseudocode...
725
726    uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
727      = if (con1 == con2) then
728    -- Good news!  Same synonym constructors, so we can shortcut
729    -- by unifying their arguments and ignoring their expansions.
730    unifyTypepeLists args1 args2
731     else
732    -- Never mind.  Just expand them and try again
733    uTys ty1 ty2
734
735 then THINK AGAIN.  Here is the whole story, as detected and reported
736 by Chris Okasaki:
737
738 Here's a test program that should detect the problem:
739
740         type Bogus a = Int
741         x = (1 :: Bogus Char) :: Bogus Bool
742
743 The problem with [the attempted shortcut code] is that
744
745         con1 == con2
746
747 is not a sufficient condition to be able to use the shortcut!
748 You also need to know that the type synonym actually USES all
749 its arguments.  For example, consider the following type synonym
750 which does not use all its arguments.
751
752         type Bogus a = Int
753
754 If you ever tried unifying, say, (Bogus Char) with )Bogus Bool), the
755 unifier would blithely try to unify Char with Bool and would fail,
756 even though the expanded forms (both Int) should match. Similarly,
757 unifying (Bogus Char) with (Bogus t) would unnecessarily bind t to
758 Char.
759
760 ... You could explicitly test for the problem synonyms and mark them
761 somehow as needing expansion, perhaps also issuing a warning to the
762 user.
763
764 Note [Deferred Unification]
765 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
766 We may encounter a unification ty1 ~ ty2 that cannot be performed syntactically,
767 and yet its consistency is undetermined. Previously, there was no way to still
768 make it consistent. So a mismatch error was issued.
769
770 Now these unfications are deferred until constraint simplification, where type
771 family instances and given equations may (or may not) establish the consistency.
772 Deferred unifications are of the form
773                 F ... ~ ...
774 or              x ~ ...
775 where F is a type function and x is a type variable.
776 E.g.
777         id :: x ~ y => x -> y
778         id e = e
779
780 involves the unfication x = y. It is deferred until we bring into account the
781 context x ~ y to establish that it holds.
782
783 If available, we defer original types (rather than those where closed type
784 synonyms have already been expanded via tcCoreView).  This is, as usual, to
785 improve error messages.
786
787
788 %************************************************************************
789 %*                                                                      *
790                  uVar and friends
791 %*                                                                      *
792 %************************************************************************
793
794 @uVar@ is called when at least one of the types being unified is a
795 variable.  It does {\em not} assume that the variable is a fixed point
796 of the substitution; rather, notice that @uVar@ (defined below) nips
797 back into @uTys@ if it turns out that the variable is already bound.
798
799 \begin{code}
800 uVar :: [EqOrigin] -> SwapFlag -> TcTyVar -> TcTauType -> TcM CoercionI
801 uVar origin swapped tv1 ty2
802   = do  { traceTc "uVar" (vcat [ ppr origin
803                                 , ppr swapped
804                                 , ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
805                                 , nest 2 (ptext (sLit " ~ "))
806                                 , ppr ty2 <+> dcolon <+> ppr (typeKind ty2)])
807         ; details <- lookupTcTyVar tv1
808         ; case details of
809             Filled ty1  -> unSwap swapped (uType_np origin) ty1 ty2
810             Unfilled details1 -> uUnfilledVar origin swapped tv1 details1 ty2
811         }
812
813 ----------------
814 uUnfilledVar :: [EqOrigin]
815              -> SwapFlag
816              -> TcTyVar -> TcTyVarDetails       -- Tyvar 1
817              -> TcTauType                       -- Type 2
818              -> TcM CoercionI
819 -- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
820 --            It might be a skolem, or untouchable, or meta
821
822 uUnfilledVar origin swapped tv1 details1 (TyVarTy tv2)
823   | tv1 == tv2  -- Same type variable => no-op
824   = return (IdCo (mkTyVarTy tv1))
825
826   | otherwise  -- Distinct type variables
827   = do  { lookup2 <- lookupTcTyVar tv2
828         ; case lookup2 of
829             Filled ty2'       -> uUnfilledVar origin swapped tv1 details1 ty2' 
830             Unfilled details2 -> uUnfilledVars origin swapped tv1 details1 tv2 details2
831         }
832
833 uUnfilledVar origin swapped tv1 details1 non_var_ty2  -- ty2 is not a type variable
834   = case details1 of
835       MetaTv TauTv ref1 
836         -> do { mb_ty2' <- checkTauTvUpdate tv1 non_var_ty2
837               ; case mb_ty2' of
838                   Nothing   -> do { traceTc "Occ/kind defer" (ppr tv1); defer }
839                   Just ty2' -> updateMeta tv1 ref1 ty2'
840               }
841
842       _other -> do { traceTc "Skolem defer" (ppr tv1); defer }          -- Skolems of all sorts
843   where
844     defer = unSwap swapped (uType_defer origin) (mkTyVarTy tv1) non_var_ty2
845           -- Occurs check or an untouchable: just defer
846           -- NB: occurs check isn't necessarily fatal: 
847           --     eg tv1 occured in type family parameter
848
849 ----------------
850 uUnfilledVars :: [EqOrigin]
851               -> SwapFlag
852               -> TcTyVar -> TcTyVarDetails      -- Tyvar 1
853               -> TcTyVar -> TcTyVarDetails      -- Tyvar 2
854               -> TcM CoercionI
855 -- Invarant: The type variables are distinct,
856 --           Neither is filled in yet
857
858 uUnfilledVars origin swapped tv1 details1 tv2 details2
859   = case (details1, details2) of
860       (MetaTv i1 ref1, MetaTv i2 ref2)
861           | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1 i1 i2
862                          then updateMeta tv1 ref1 ty2
863                          else updateMeta tv2 ref2 ty1
864           | k2_sub_k1 -> updateMeta tv1 ref1 ty2
865
866       (_, MetaTv _ ref2) | k1_sub_k2 -> updateMeta tv2 ref2 ty1
867       (MetaTv _ ref1, _) | k2_sub_k1 -> updateMeta tv1 ref1 ty2
868
869       (_, _) -> unSwap swapped (uType_defer origin) ty1 ty2
870                 -- Defer for skolems of all sorts
871   where
872     k1        = tyVarKind tv1
873     k2        = tyVarKind tv2
874     k1_sub_k2 = k1 `isSubKind` k2
875     k2_sub_k1 = k2 `isSubKind` k1
876     ty1       = mkTyVarTy tv1
877     ty2       = mkTyVarTy tv2
878
879     nicer_to_update_tv1 _         (SigTv _) = True
880     nicer_to_update_tv1 (SigTv _) _         = False
881     nicer_to_update_tv1 _         _         = isSystemName (Var.varName tv1)
882         -- Try not to update SigTvs; and try to update sys-y type
883         -- variables in preference to ones gotten (say) by
884         -- instantiating a polymorphic function with a user-written
885         -- type sig
886
887 ----------------
888 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
889 --    (checkTauTvUpdate tv ty)
890 -- We are about to update the TauTv tv with ty.
891 -- Check (a) that tv doesn't occur in ty (occurs check)
892 --       (b) that kind(ty) is a sub-kind of kind(tv)
893 --       (c) that ty does not contain any type families, see Note [Type family sharing]
894 -- 
895 -- We have two possible outcomes:
896 -- (1) Return the type to update the type variable with, 
897 --        [we know the update is ok]
898 -- (2) Return Nothing,
899 --        [the update might be dodgy]
900 --
901 -- Note that "Nothing" does not mean "definite error".  For example
902 --   type family F a
903 --   type instance F Int = Int
904 -- consider
905 --   a ~ F a
906 -- This is perfectly reasonable, if we later get a ~ Int.  For now, though,
907 -- we return Nothing, leaving it to the later constraint simplifier to
908 -- sort matters out.
909
910 checkTauTvUpdate tv ty
911   = do { ty' <- zonkTcType ty
912        ; if ok ty' && (typeKind ty' `isSubKind` tyVarKind tv) 
913          then return (Just ty')
914          else return Nothing }
915   where ok :: TcType -> Bool 
916         -- Check that (a) tv is not among the free variables of 
917         -- the type and that (b) the type is type-family-free.
918         -- Reason: Note [Type family sharing]  
919         ok ty1 | Just ty1' <- tcView ty1 = ok ty1'  
920         ok (TyVarTy tv')      = not (tv == tv') 
921         ok (TyConApp tc tys)  = all ok tys && not (isSynFamilyTyCon tc)
922         ok (PredTy sty)       = ok_pred sty 
923         ok (FunTy arg res)    = ok arg && ok res 
924         ok (AppTy fun arg)    = ok fun && ok arg 
925         ok (ForAllTy _tv1 ty1) = ok ty1       
926
927         ok_pred (IParam _ ty)    = ok ty 
928         ok_pred (ClassP _ tys)   = all ok tys 
929         ok_pred (EqPred ty1 ty2) = ok ty1 && ok ty2 
930
931 \end{code}
932
933 Note [Type family sharing]
934 ~~~~~~~~~~~~~~ 
935 We must avoid eagerly unifying type variables to types that contain function symbols, 
936 because this may lead to loss of sharing, and in turn, in very poor performance of the
937 constraint simplifier. Assume that we have a wanted constraint: 
938
939   m1 ~ [F m2], 
940   m2 ~ [F m3], 
941   m3 ~ [F m4], 
942   D m1, 
943   D m2, 
944   D m3 
945
946 where D is some type class. If we eagerly unify m1 := [F m2], m2 := [F m3], m3 := [F m2], 
947 then, after zonking, our constraint simplifier will be faced with the following wanted 
948 constraint: 
949
950   D [F [F [F m4]]], 
951   D [F [F m4]], 
952   D [F m4] 
953
954 which has to be flattened by the constraint solver. However, because the sharing is lost, 
955 an polynomially larger number of flatten skolems will be created and the constraint sets 
956 we are working with will be polynomially larger. 
957
958 Instead, if we defer the unifications m1 := [F m2], etc. we will only be generating three 
959 flatten skolems, which is the maximum possible sharing arising from the original constraint. 
960
961 \begin{code}
962 data LookupTyVarResult  -- The result of a lookupTcTyVar call
963   = Unfilled TcTyVarDetails     -- SkolemTv or virgin MetaTv
964   | Filled   TcType
965
966 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
967 lookupTcTyVar tyvar 
968   | MetaTv _ ref <- details
969   = do { meta_details <- readMutVar ref
970        ; case meta_details of
971            Indirect ty -> return (Filled ty)
972            Flexi -> do { is_untch <- isUntouchable tyvar
973                        ; let    -- Note [Unifying untouchables]
974                              ret_details | is_untch = SkolemTv UnkSkol
975                                          | otherwise = details
976                        ; return (Unfilled ret_details) } }
977   | otherwise
978   = return (Unfilled details)
979   where
980     details = ASSERT2( isTcTyVar tyvar, ppr tyvar )
981               tcTyVarDetails tyvar
982
983 updateMeta :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM CoercionI
984 updateMeta tv1 ref1 ty2
985   = do { writeMetaTyVarRef tv1 ref1 ty2
986        ; return (IdCo ty2) }
987 \end{code}
988
989 Note [Unifying untouchables]
990 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
991 We treat an untouchable type variable as if it was a skolem.  That
992 ensures it won't unify with anything.  It's a slight had, because
993 we return a made-up TcTyVarDetails, but I think it works smoothly.
994
995
996 %************************************************************************
997 %*                                                                      *
998         Errors and contexts
999 %*                                                                      *
1000 %************************************************************************
1001
1002 \begin{code}
1003 pushOrigin :: TcType -> TcType -> [EqOrigin] -> [EqOrigin]
1004 pushOrigin ty_act ty_exp origin
1005   = UnifyOrigin { uo_actual = ty_act, uo_expected = ty_exp } : origin
1006
1007 ---------------
1008 wrapEqCtxt :: [EqOrigin] -> TcM a -> TcM a
1009 -- Build a suitable error context from the origin and do the thing inside
1010 -- The "couldn't match" error comes from the innermost item on the stack,
1011 -- and, if there is more than one item, the "Expected/inferred" part
1012 -- comes from the outermost item
1013 wrapEqCtxt []    thing_inside = thing_inside
1014 wrapEqCtxt items thing_inside = addErrCtxtM (unifyCtxt (last items)) thing_inside
1015
1016 ---------------
1017 failWithMisMatch :: [EqOrigin] -> TcM a
1018 -- Generate the message when two types fail to match,
1019 -- going to some trouble to make it helpful.
1020 -- We take the failing types from the top of the origin stack
1021 -- rather than reporting the particular ones we are looking 
1022 -- at right now
1023 failWithMisMatch (item:origin)
1024   = wrapEqCtxt origin $
1025     do  { ty_act <- zonkTcType (uo_actual item)
1026         ; ty_exp <- zonkTcType (uo_expected item)
1027         ; env0 <- tcInitTidyEnv
1028         ; let (env1, pp_exp) = tidyOpenType env0 ty_exp
1029               (env2, pp_act) = tidyOpenType env1 ty_act
1030         ; failWithTcM (misMatchMsg env2 pp_act pp_exp) }
1031 failWithMisMatch [] 
1032   = panic "failWithMisMatch"
1033
1034 misMatchMsg :: TidyEnv -> TcType -> TcType -> (TidyEnv, SDoc)
1035 misMatchMsg env ty_act ty_exp
1036   = (env2, sep [sep [ ptext (sLit "Couldn't match expected type") <+> quotes (ppr ty_exp)
1037                     , nest 12 $   ptext (sLit "with actual type") <+> quotes (ppr ty_act)]
1038                , nest 2 (extra1 $$ extra2) ])
1039   where
1040     (env1, extra1) = typeExtraInfoMsg env  ty_exp
1041     (env2, extra2) = typeExtraInfoMsg env1 ty_act
1042 \end{code}
1043
1044
1045 -----------------------------------------
1046         UNUSED FOR NOW
1047 -----------------------------------------
1048
1049 ----------------
1050 ----------------
1051 -- If an error happens we try to figure out whether the function
1052 -- function has been given too many or too few arguments, and say so.
1053 addSubCtxt :: InstOrigin -> TcType -> TcType -> TcM a -> TcM a
1054 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1055   = addErrCtxtM mk_err thing_inside
1056   where
1057     mk_err tidy_env
1058       = do { exp_ty' <- zonkTcType expected_res_ty
1059            ; act_ty' <- zonkTcType actual_res_ty
1060            ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1061                  (env2, act_ty'') = tidyOpenType env1     act_ty'
1062                  (exp_args, _)    = tcSplitFunTys exp_ty''
1063                  (act_args, _)    = tcSplitFunTys act_ty''
1064
1065                  len_act_args     = length act_args
1066                  len_exp_args     = length exp_args
1067
1068                  message = case orig of
1069                              OccurrenceOf fun
1070                                   | len_exp_args < len_act_args -> wrongArgsCtxt "too few"  fun
1071                                   | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1072                              _ -> mkExpectedActualMsg act_ty'' exp_ty''
1073            ; return (env2, message) }
1074
1075
1076 %************************************************************************
1077 %*                                                                      *
1078                 Kind unification
1079 %*                                                                      *
1080 %************************************************************************
1081
1082 Unifying kinds is much, much simpler than unifying types.
1083
1084 \begin{code}
1085 matchExpectedFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1086 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1087
1088 matchExpectedFunKind (TyVarTy kvar) = do
1089     maybe_kind <- readKindVar kvar
1090     case maybe_kind of
1091       Indirect fun_kind -> matchExpectedFunKind fun_kind
1092       Flexi ->
1093           do { arg_kind <- newKindVar
1094              ; res_kind <- newKindVar
1095              ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1096              ; return (Just (arg_kind,res_kind)) }
1097
1098 matchExpectedFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1099 matchExpectedFunKind _                         = return Nothing
1100
1101 -----------------
1102 unifyKind :: TcKind                 -- Expected
1103           -> TcKind                 -- Actual
1104           -> TcM ()
1105
1106 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1107   | isSubKindCon kc2 kc1 = return ()
1108
1109 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1110   = do { unifyKind a2 a1; unifyKind r1 r2 }
1111                 -- Notice the flip in the argument,
1112                 -- so that the sub-kinding works right
1113 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1114 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1115 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1116
1117 ----------------
1118 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1119 uKVar swapped kv1 k2
1120   = do  { mb_k1 <- readKindVar kv1
1121         ; case mb_k1 of
1122             Flexi -> uUnboundKVar swapped kv1 k2
1123             Indirect k1 | swapped   -> unifyKind k2 k1
1124                         | otherwise -> unifyKind k1 k2 }
1125
1126 ----------------
1127 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1128 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1129   | kv1 == kv2 = return ()
1130   | otherwise   -- Distinct kind variables
1131   = do  { mb_k2 <- readKindVar kv2
1132         ; case mb_k2 of
1133             Indirect k2 -> uUnboundKVar swapped kv1 k2
1134             Flexi -> writeKindVar kv1 k2 }
1135
1136 uUnboundKVar swapped kv1 non_var_k2
1137   = do  { k2' <- zonkTcKind non_var_k2
1138         ; kindOccurCheck kv1 k2'
1139         ; k2'' <- kindSimpleKind swapped k2'
1140                 -- KindVars must be bound only to simple kinds
1141                 -- Polarities: (kindSimpleKind True ?) succeeds
1142                 -- returning *, corresponding to unifying
1143                 --      expected: ?
1144                 --      actual:   kind-ver
1145         ; writeKindVar kv1 k2'' }
1146
1147 ----------------
1148 kindOccurCheck :: TyVar -> Type -> TcM ()
1149 kindOccurCheck kv1 k2   -- k2 is zonked
1150   = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1151   where
1152     not_in (TyVarTy kv2) = kv1 /= kv2
1153     not_in (FunTy a2 r2) = not_in a2 && not_in r2
1154     not_in _             = True
1155
1156 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1157 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1158 -- If the flag is False, it requires k <: sk
1159 -- E.g.         kindSimpleKind False ?? = *
1160 -- What about (kv -> *) ~ ?? -> *
1161 kindSimpleKind orig_swapped orig_kind
1162   = go orig_swapped orig_kind
1163   where
1164     go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1165                              ; k2' <- go sw k2
1166                              ; return (mkArrowKind k1' k2') }
1167     go True k
1168      | isOpenTypeKind k = return liftedTypeKind
1169      | isArgTypeKind k  = return liftedTypeKind
1170     go _ k
1171      | isLiftedTypeKind k   = return liftedTypeKind
1172      | isUnliftedTypeKind k = return unliftedTypeKind
1173     go _ k@(TyVarTy _) = return k -- KindVars are always simple
1174     go _ _ = failWithTc (ptext (sLit "Unexpected kind unification failure:")
1175                                   <+> ppr orig_swapped <+> ppr orig_kind)
1176         -- I think this can't actually happen
1177
1178 -- T v = MkT v           v must be a type
1179 -- T v w = MkT (v -> w)  v must not be an umboxed tuple
1180
1181 unifyKindMisMatch :: TcKind -> TcKind -> TcM ()
1182 unifyKindMisMatch ty1 ty2 = do
1183     ty1' <- zonkTcKind ty1
1184     ty2' <- zonkTcKind ty2
1185     let
1186         msg = hang (ptext (sLit "Couldn't match kind"))
1187                    2 (sep [quotes (ppr ty1'), 
1188                            ptext (sLit "against"), 
1189                            quotes (ppr ty2')])
1190     failWithTc msg
1191
1192 ----------------
1193 kindOccurCheckErr :: Var -> Type -> SDoc
1194 kindOccurCheckErr tyvar ty
1195   = hang (ptext (sLit "Occurs check: cannot construct the infinite kind:"))
1196        2 (sep [ppr tyvar, char '=', ppr ty])
1197 \end{code}
1198
1199 %************************************************************************
1200 %*                                                                      *
1201 \subsection{Checking signature type variables}
1202 %*                                                                      *
1203 %************************************************************************
1204
1205 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1206 are not mentioned in the environment.  In particular:
1207
1208         (a) Not mentioned in the type of a variable in the envt
1209                 eg the signature for f in this:
1210
1211                         g x = ... where
1212                                         f :: a->[a]
1213                                         f y = [x,y]
1214
1215                 Here, f is forced to be monorphic by the free occurence of x.
1216
1217         (d) Not (unified with another type variable that is) in scope.
1218                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1219             when checking the expression type signature, we find that
1220             even though there is nothing in scope whose type mentions r,
1221             nevertheless the type signature for the expression isn't right.
1222
1223             Another example is in a class or instance declaration:
1224                 class C a where
1225                    op :: forall b. a -> b
1226                    op x = x
1227             Here, b gets unified with a
1228
1229 Before doing this, the substitution is applied to the signature type variable.
1230
1231 -- \begin{code}
1232 checkSigTyVars :: [TcTyVar] -> TcM ()
1233 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1234
1235 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1236 -- The extra_tvs can include boxy type variables;
1237 --      e.g. TcMatches.tcCheckExistentialPat
1238 checkSigTyVarsWrt extra_tvs sig_tvs
1239   = do  { extra_tvs' <- zonkTcTyVarsAndFV extra_tvs
1240         ; check_sig_tyvars extra_tvs' sig_tvs }
1241
1242 check_sig_tyvars
1243         :: TcTyVarSet   -- Global type variables. The universally quantified
1244                         --      tyvars should not mention any of these
1245                         --      Guaranteed already zonked.
1246         -> [TcTyVar]    -- Universally-quantified type variables in the signature
1247                         --      Guaranteed to be skolems
1248         -> TcM ()
1249 check_sig_tyvars _ []
1250   = return ()
1251 check_sig_tyvars extra_tvs sig_tvs
1252   = ASSERT( all isTcTyVar sig_tvs && all isSkolemTyVar sig_tvs )
1253     do  { gbl_tvs <- tcGetGlobalTyVars
1254         ; traceTc "check_sig_tyvars" $ vcat 
1255                [ text "sig_tys" <+> ppr sig_tvs
1256                , text "gbl_tvs" <+> ppr gbl_tvs
1257                , text "extra_tvs" <+> ppr extra_tvs]
1258
1259         ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1260         ; when (any (`elemVarSet` env_tvs) sig_tvs)
1261                (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1262         }
1263
1264 bleatEscapedTvs :: TcTyVarSet   -- The global tvs
1265                 -> [TcTyVar]    -- The possibly-escaping type variables
1266                 -> [TcTyVar]    -- The zonked versions thereof
1267                 -> TcM ()
1268 -- Complain about escaping type variables
1269 -- We pass a list of type variables, at least one of which
1270 -- escapes.  The first list contains the original signature type variable,
1271 -- while the second  contains the type variable it is unified to (usually itself)
1272 bleatEscapedTvs globals sig_tvs zonked_tvs
1273   = do  { env0 <- tcInitTidyEnv
1274         ; let (env1, tidy_tvs)        = tidyOpenTyVars env0 sig_tvs
1275               (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1276
1277         ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1278         ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1279   where
1280     main_msg = ptext (sLit "Inferred type is less polymorphic than expected")
1281
1282     check (tidy_env, msgs) (sig_tv, zonked_tv)
1283       | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1284       | otherwise
1285       = do { lcl_env <- getLclTypeEnv
1286            ; (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) lcl_env tidy_env
1287            ; return (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1288
1289 -----------------------
1290 escape_msg :: Var -> Var -> [SDoc] -> SDoc
1291 escape_msg sig_tv zonked_tv globs
1292   | notNull globs
1293   = vcat [sep [msg, ptext (sLit "is mentioned in the environment:")],
1294           nest 2 (vcat globs)]
1295   | otherwise
1296   = msg <+> ptext (sLit "escapes")
1297         -- Sigh.  It's really hard to give a good error message
1298         -- all the time.   One bad case is an existential pattern match.
1299         -- We rely on the "When..." context to help.
1300   where
1301     msg = ptext (sLit "Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1302     is_bound_to
1303         | sig_tv == zonked_tv = empty
1304         | otherwise = ptext (sLit "is unified with") <+> quotes (ppr zonked_tv) <+> ptext (sLit "which")
1305 -- \end{code}
1306
1307 These two context are used with checkSigTyVars
1308
1309 \begin{code}
1310 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1311         -> TidyEnv -> TcM (TidyEnv, Message)
1312 sigCtxt id sig_tvs sig_theta sig_tau tidy_env = do
1313     actual_tau <- zonkTcType sig_tau
1314     let
1315         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
1316         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1317         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1318         sub_msg = vcat [ptext (sLit "Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1319                         ptext (sLit "Type to generalise:") <+> pprType tidy_actual_tau
1320                    ]
1321         msg = vcat [ptext (sLit "When trying to generalise the type inferred for") <+> quotes (ppr id),
1322                     nest 2 sub_msg]
1323
1324     return (env3, msg)
1325 \end{code}