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