Improve handling of newtypes (fixes Trac 1495)
[ghc-hetmet.git] / compiler / types / Type.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 %
5
6 Type - public interface
7
8 \begin{code}
9 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module Type (
17         -- re-exports from TypeRep
18         TyThing(..), Type, PredType(..), ThetaType, 
19         funTyCon,
20
21         -- Kinds
22         Kind, SimpleKind, KindVar,
23         kindFunResult, splitKindFunTys, splitKindFunTysN,
24
25         liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
26         argTypeKindTyCon, ubxTupleKindTyCon,
27
28         liftedTypeKind, unliftedTypeKind, openTypeKind,
29         argTypeKind, ubxTupleKind,
30
31         tySuperKind, coSuperKind, 
32
33         isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
34         isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind, 
35         isCoSuperKind, isSuperKind, isCoercionKind, isEqPred,
36         mkArrowKind, mkArrowKinds,
37
38         isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
39         isSubKindCon,
40
41         -- Re-exports from TyCon
42         PrimRep(..),
43
44         mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,
45
46         mkAppTy, mkAppTys, splitAppTy, splitAppTys, 
47         splitAppTy_maybe, repSplitAppTy_maybe,
48
49         mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, 
50         splitFunTys, splitFunTysN,
51         funResultTy, funArgTy, zipFunTys, isFunTy,
52
53         mkTyConApp, mkTyConTy, 
54         tyConAppTyCon, tyConAppArgs, 
55         splitTyConApp_maybe, splitTyConApp, 
56         splitNewTyConApp_maybe, splitNewTyConApp,
57
58         repType, typePrimRep, coreView, tcView, kindView, rttiView,
59
60         mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
61         applyTy, applyTys, isForAllTy, dropForAlls,
62
63         -- Source types
64         predTypeRep, mkPredTy, mkPredTys, pprSourceTyCon, mkFamilyTyConApp,
65
66         -- Newtypes
67         newTyConInstRhs,
68
69         -- Lifting and boxity
70         isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
71         isPrimitiveType, isStrictType, isStrictPred, 
72
73         -- Free variables
74         tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
75         typeKind, addFreeTyVars,
76
77         -- Type families
78         tyFamInsts,
79
80         -- Tidying up for printing
81         tidyType,      tidyTypes,
82         tidyOpenType,  tidyOpenTypes,
83         tidyTyVarBndr, tidyFreeTyVars,
84         tidyOpenTyVar, tidyOpenTyVars,
85         tidyTopType,   tidyPred,
86         tidyKind,
87
88         -- Comparison
89         coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes, 
90         tcEqPred, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
91
92         -- Seq
93         seqType, seqTypes,
94
95         -- Type substitutions
96         TvSubstEnv, emptyTvSubstEnv,    -- Representation widely visible
97         TvSubst(..), emptyTvSubst,      -- Representation visible to a few friends
98         mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
99         getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
100         extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
101         isEmptyTvSubst,
102
103         -- Performing substitution on types
104         substTy, substTys, substTyWith, substTheta, 
105         substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
106
107         -- Pretty-printing
108         pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
109         pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind
110     ) where
111
112 #include "HsVersions.h"
113
114 -- We import the representation and primitive functions from TypeRep.
115 -- Many things are reexported, but not the representation!
116
117 import TypeRep
118
119 -- friends:
120 import Var
121 import VarEnv
122 import VarSet
123
124 import Name
125 import Class
126 import PrelNames
127 import TyCon
128
129 -- others
130 import StaticFlags
131 import Util
132 import Outputable
133 import UniqSet
134
135 import Data.List
136 import Data.Maybe       ( isJust )
137 \end{code}
138
139
140 %************************************************************************
141 %*                                                                      *
142                 Type representation
143 %*                                                                      *
144 %************************************************************************
145
146 In Core, we "look through" non-recursive newtypes and PredTypes.
147
148 \begin{code}
149 {-# INLINE coreView #-}
150 coreView :: Type -> Maybe Type
151 -- Strips off the *top layer only* of a type to give 
152 -- its underlying representation type. 
153 -- Returns Nothing if there is nothing to look through.
154 --
155 -- In the case of newtypes, it returns
156 --      *either* a vanilla TyConApp (recursive newtype, or non-saturated)
157 --      *or*     the newtype representation (otherwise), meaning the
158 --                      type written in the RHS of the newtype decl,
159 --                      which may itself be a newtype
160 --
161 -- Example: newtype R = MkR S
162 --          newtype S = MkS T
163 --          newtype T = MkT (T -> T)
164 --   expandNewTcApp on R gives Just S
165 --                  on S gives Just T
166 --                  on T gives Nothing   (no expansion)
167
168 -- By being non-recursive and inlined, this case analysis gets efficiently
169 -- joined onto the case analysis that the caller is already doing
170 coreView (NoteTy _ ty)     = Just ty
171 coreView (PredTy p)
172   | isEqPred p             = Nothing
173   | otherwise              = Just (predTypeRep p)
174 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys 
175                            = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
176                                 -- Its important to use mkAppTys, rather than (foldl AppTy),
177                                 -- because the function part might well return a 
178                                 -- partially-applied type constructor; indeed, usually will!
179 coreView ty                = Nothing
180
181
182
183 -----------------------------------------------
184 {-# INLINE tcView #-}
185 tcView :: Type -> Maybe Type
186 -- Same, but for the type checker, which just looks through synonyms
187 tcView (NoteTy _ ty)     = Just ty
188 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys 
189                          = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
190 tcView ty                = Nothing
191
192 -----------------------------------------------
193 rttiView :: Type -> Type
194 -- Same, but for the RTTI system, which cannot deal with predicates nor polymorphism
195 rttiView (ForAllTy _ ty) = rttiView ty
196 rttiView (NoteTy   _ ty) = rttiView ty
197 rttiView (FunTy PredTy{} ty) = rttiView ty
198 rttiView (FunTy NoteTy{} ty) = rttiView ty
199 rttiView ty@TyConApp{} | Just ty' <- coreView ty 
200                            = rttiView ty'
201 rttiView (TyConApp tc tys) = mkTyConApp tc (map rttiView tys)
202 rttiView ty = ty
203
204 -----------------------------------------------
205 {-# INLINE kindView #-}
206 kindView :: Kind -> Maybe Kind
207 -- C.f. coreView, tcView
208 -- For the moment, we don't even handle synonyms in kinds
209 kindView (NoteTy _ k) = Just k
210 kindView other        = Nothing
211 \end{code}
212
213
214 %************************************************************************
215 %*                                                                      *
216 \subsection{Constructor-specific functions}
217 %*                                                                      *
218 %************************************************************************
219
220
221 ---------------------------------------------------------------------
222                                 TyVarTy
223                                 ~~~~~~~
224 \begin{code}
225 mkTyVarTy  :: TyVar   -> Type
226 mkTyVarTy  = TyVarTy
227
228 mkTyVarTys :: [TyVar] -> [Type]
229 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
230
231 getTyVar :: String -> Type -> TyVar
232 getTyVar msg ty = case getTyVar_maybe ty of
233                     Just tv -> tv
234                     Nothing -> panic ("getTyVar: " ++ msg)
235
236 isTyVarTy :: Type -> Bool
237 isTyVarTy ty = isJust (getTyVar_maybe ty)
238
239 getTyVar_maybe :: Type -> Maybe TyVar
240 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
241 getTyVar_maybe (TyVarTy tv)                 = Just tv  
242 getTyVar_maybe other                        = Nothing
243
244 \end{code}
245
246
247 ---------------------------------------------------------------------
248                                 AppTy
249                                 ~~~~~
250 We need to be pretty careful with AppTy to make sure we obey the 
251 invariant that a TyConApp is always visibly so.  mkAppTy maintains the
252 invariant: use it.
253
254 \begin{code}
255 mkAppTy orig_ty1 orig_ty2
256   = mk_app orig_ty1
257   where
258     mk_app (NoteTy _ ty1)    = mk_app ty1
259     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
260     mk_app ty1               = AppTy orig_ty1 orig_ty2
261         -- Note that the TyConApp could be an 
262         -- under-saturated type synonym.  GHC allows that; e.g.
263         --      type Foo k = k a -> k a
264         --      type Id x = x
265         --      foo :: Foo Id -> Foo Id
266         --
267         -- Here Id is partially applied in the type sig for Foo,
268         -- but once the type synonyms are expanded all is well
269
270 mkAppTys :: Type -> [Type] -> Type
271 mkAppTys orig_ty1 []        = orig_ty1
272         -- This check for an empty list of type arguments
273         -- avoids the needless loss of a type synonym constructor.
274         -- For example: mkAppTys Rational []
275         --   returns to (Ratio Integer), which has needlessly lost
276         --   the Rational part.
277 mkAppTys orig_ty1 orig_tys2
278   = mk_app orig_ty1
279   where
280     mk_app (NoteTy _ ty1)    = mk_app ty1
281     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
282                                 -- mkTyConApp: see notes with mkAppTy
283     mk_app ty1               = foldl AppTy orig_ty1 orig_tys2
284
285 -------------
286 splitAppTy_maybe :: Type -> Maybe (Type, Type)
287 splitAppTy_maybe ty | Just ty' <- coreView ty
288                     = splitAppTy_maybe ty'
289 splitAppTy_maybe ty = repSplitAppTy_maybe ty
290
291 -------------
292 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
293 -- Does the AppTy split, but assumes that any view stuff is already done
294 repSplitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
295 repSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
296 repSplitAppTy_maybe (TyConApp tc tys) 
297   | not (isOpenSynTyCon tc) || length tys > tyConArity tc 
298   = case snocView tys of       -- never create unsaturated type family apps
299       Just (tys', ty') -> Just (TyConApp tc tys', ty')
300       Nothing          -> Nothing
301 repSplitAppTy_maybe _other = Nothing
302 -------------
303 splitAppTy :: Type -> (Type, Type)
304 splitAppTy ty = case splitAppTy_maybe ty of
305                         Just pr -> pr
306                         Nothing -> panic "splitAppTy"
307
308 -------------
309 splitAppTys :: Type -> (Type, [Type])
310 splitAppTys ty = split ty ty []
311   where
312     split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
313     split orig_ty (AppTy ty arg)        args = split ty ty (arg:args)
314     split orig_ty (TyConApp tc tc_args) args 
315       = let -- keep type families saturated
316             n | isOpenSynTyCon tc = tyConArity tc
317               | otherwise         = 0
318             (tc_args1, tc_args2)  = splitAt n tc_args
319         in
320         (TyConApp tc tc_args1, tc_args2 ++ args)
321     split orig_ty (FunTy ty1 ty2)       args = ASSERT( null args )
322                                                (TyConApp funTyCon [], [ty1,ty2])
323     split orig_ty ty                    args = (orig_ty, args)
324
325 \end{code}
326
327
328 ---------------------------------------------------------------------
329                                 FunTy
330                                 ~~~~~
331
332 \begin{code}
333 mkFunTy :: Type -> Type -> Type
334 mkFunTy (PredTy (EqPred ty1 ty2)) res = mkForAllTy (mkWildCoVar (PredTy (EqPred ty1 ty2))) res
335 mkFunTy arg res = FunTy arg res
336
337 mkFunTys :: [Type] -> Type -> Type
338 mkFunTys tys ty = foldr mkFunTy ty tys
339
340 isFunTy :: Type -> Bool 
341 isFunTy ty = isJust (splitFunTy_maybe ty)
342
343 splitFunTy :: Type -> (Type, Type)
344 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
345 splitFunTy (FunTy arg res)   = (arg, res)
346 splitFunTy other             = pprPanic "splitFunTy" (ppr other)
347
348 splitFunTy_maybe :: Type -> Maybe (Type, Type)
349 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
350 splitFunTy_maybe (FunTy arg res)   = Just (arg, res)
351 splitFunTy_maybe other             = Nothing
352
353 splitFunTys :: Type -> ([Type], Type)
354 splitFunTys ty = split [] ty ty
355   where
356     split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
357     split args orig_ty (FunTy arg res)   = split (arg:args) res res
358     split args orig_ty ty                = (reverse args, orig_ty)
359
360 splitFunTysN :: Int -> Type -> ([Type], Type)
361 -- Split off exactly n arg tys
362 splitFunTysN 0 ty = ([], ty)
363 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
364                     case splitFunTysN (n-1) res of { (args, res) ->
365                     (arg:args, res) }}
366
367 zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
368 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
369   where
370     split acc []     nty ty                = (reverse acc, nty)
371     split acc xs     nty ty 
372           | Just ty' <- coreView ty        = split acc xs nty ty'
373     split acc (x:xs) nty (FunTy arg res)   = split ((x,arg):acc) xs res res
374     split acc (x:xs) nty ty                = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
375     
376 funResultTy :: Type -> Type
377 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
378 funResultTy (FunTy arg res)   = res
379 funResultTy ty                = pprPanic "funResultTy" (ppr ty)
380
381 funArgTy :: Type -> Type
382 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
383 funArgTy (FunTy arg res)   = arg
384 funArgTy ty                = pprPanic "funArgTy" (ppr ty)
385 \end{code}
386
387
388 ---------------------------------------------------------------------
389                                 TyConApp
390                                 ~~~~~~~~
391 @mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or PredTy,
392 as apppropriate.
393
394 \begin{code}
395 mkTyConApp :: TyCon -> [Type] -> Type
396 mkTyConApp tycon tys
397   | isFunTyCon tycon, [ty1,ty2] <- tys
398   = FunTy ty1 ty2
399
400   | otherwise
401   = TyConApp tycon tys
402
403 mkTyConTy :: TyCon -> Type
404 mkTyConTy tycon = mkTyConApp tycon []
405
406 -- splitTyConApp "looks through" synonyms, because they don't
407 -- mean a distinct type, but all other type-constructor applications
408 -- including functions are returned as Just ..
409
410 tyConAppTyCon :: Type -> TyCon
411 tyConAppTyCon ty = fst (splitTyConApp ty)
412
413 tyConAppArgs :: Type -> [Type]
414 tyConAppArgs ty = snd (splitTyConApp ty)
415
416 splitTyConApp :: Type -> (TyCon, [Type])
417 splitTyConApp ty = case splitTyConApp_maybe ty of
418                         Just stuff -> stuff
419                         Nothing    -> pprPanic "splitTyConApp" (ppr ty)
420
421 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
422 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
423 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
424 splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
425 splitTyConApp_maybe other             = Nothing
426
427 -- Sometimes we do NOT want to look throught a newtype.  When case matching
428 -- on a newtype we want a convenient way to access the arguments of a newty
429 -- constructor so as to properly form a coercion.
430 splitNewTyConApp :: Type -> (TyCon, [Type])
431 splitNewTyConApp ty = case splitNewTyConApp_maybe ty of
432                         Just stuff -> stuff
433                         Nothing    -> pprPanic "splitNewTyConApp" (ppr ty)
434 splitNewTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
435 splitNewTyConApp_maybe ty | Just ty' <- tcView ty = splitNewTyConApp_maybe ty'
436 splitNewTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
437 splitNewTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
438 splitNewTyConApp_maybe other          = Nothing
439
440 newTyConInstRhs :: TyCon -> [Type] -> Type
441 -- Unwrap one 'layer' of newtype
442 -- Use the eta'd version if possible
443 newTyConInstRhs tycon tys 
444     = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
445       mkAppTys (substTyWith tvs tys1 ty) tys2
446   where
447     (tvs, ty)    = newTyConEtadRhs tycon
448     (tys1, tys2) = splitAtList tvs tys
449 \end{code}
450
451
452 ---------------------------------------------------------------------
453                                 SynTy
454                                 ~~~~~
455
456 Notes on type synonyms
457 ~~~~~~~~~~~~~~~~~~~~~~
458 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
459 to return type synonyms whereever possible. Thus
460
461         type Foo a = a -> a
462
463 we want 
464         splitFunTys (a -> Foo a) = ([a], Foo a)
465 not                                ([a], a -> a)
466
467 The reason is that we then get better (shorter) type signatures in 
468 interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
469
470
471 Note [Expanding newtypes]
472 ~~~~~~~~~~~~~~~~~~~~~~~~~
473 When expanding a type to expose a data-type constructor, we need to be
474 careful about newtypes, lest we fall into an infinite loop. Here are
475 the key examples:
476
477   newtype Id  x = MkId x
478   newtype Fix f = MkFix (f (Fix f))
479   newtype T     = MkT (T -> T) 
480   
481   Type           Expansion
482  --------------------------
483   T              T -> T
484   Fix Maybe      Maybe (Fix Maybe)
485   Id (Id Int)    Int
486   Fix Id         NO NO NO
487
488 Notice that we can expand T, even though it's recursive.
489 And we can expand Id (Id Int), even though the Id shows up
490 twice at the outer level.  
491
492 So, when expanding, we keep track of when we've seen a recursive
493 newtype at outermost level; and bale out if we see it again.
494
495
496                 Representation types
497                 ~~~~~~~~~~~~~~~~~~~~
498 repType looks through 
499         (a) for-alls, and
500         (b) synonyms
501         (c) predicates
502         (d) usage annotations
503         (e) all newtypes, including recursive ones, but not newtype families
504 It's useful in the back end.
505
506 \begin{code}
507 repType :: Type -> Type
508 -- Only applied to types of kind *; hence tycons are saturated
509 repType ty
510   = go [] ty
511   where
512     go :: [TyCon] -> Type -> Type
513     go rec_nts ty | Just ty' <- coreView ty     -- Expand synonyms
514         = go rec_nts ty'        
515
516     go rec_nts (ForAllTy _ ty)                  -- Look through foralls
517         = go rec_nts ty
518
519     go rec_nts ty@(TyConApp tc tys)             -- Expand newtypes
520         | Just co_con <- newTyConCo_maybe tc    -- See Note [Expanding newtypes]
521         = if tc `elem` rec_nts                  --  in Type.lhs
522           then ty
523           else go rec_nts' nt_rhs
524         where
525           nt_rhs = newTyConInstRhs tc tys
526           rec_nts' | isRecursiveTyCon tc = tc:rec_nts
527                    | otherwise           = rec_nts
528
529     go rec_nts ty = ty
530
531
532 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
533 -- of inspecting the type directly.
534 typePrimRep :: Type -> PrimRep
535 typePrimRep ty = case repType ty of
536                    TyConApp tc _ -> tyConPrimRep tc
537                    FunTy _ _     -> PtrRep
538                    AppTy _ _     -> PtrRep      -- See note below
539                    TyVarTy _     -> PtrRep
540                    other         -> pprPanic "typePrimRep" (ppr ty)
541         -- Types of the form 'f a' must be of kind *, not *#, so
542         -- we are guaranteed that they are represented by pointers.
543         -- The reason is that f must have kind *->*, not *->*#, because
544         -- (we claim) there is no way to constrain f's kind any other
545         -- way.
546 \end{code}
547
548
549 ---------------------------------------------------------------------
550                                 ForAllTy
551                                 ~~~~~~~~
552
553 \begin{code}
554 mkForAllTy :: TyVar -> Type -> Type
555 mkForAllTy tyvar ty
556   = mkForAllTys [tyvar] ty
557
558 mkForAllTys :: [TyVar] -> Type -> Type
559 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
560
561 isForAllTy :: Type -> Bool
562 isForAllTy (NoteTy _ ty)  = isForAllTy ty
563 isForAllTy (ForAllTy _ _) = True
564 isForAllTy other_ty       = False
565
566 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
567 splitForAllTy_maybe ty = splitFAT_m ty
568   where
569     splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
570     splitFAT_m (ForAllTy tyvar ty)          = Just(tyvar, ty)
571     splitFAT_m _                            = Nothing
572
573 splitForAllTys :: Type -> ([TyVar], Type)
574 splitForAllTys ty = split ty ty []
575    where
576      split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
577      split orig_ty (ForAllTy tv ty)  tvs = split ty ty (tv:tvs)
578      split orig_ty t                 tvs = (reverse tvs, orig_ty)
579
580 dropForAlls :: Type -> Type
581 dropForAlls ty = snd (splitForAllTys ty)
582 \end{code}
583
584 -- (mkPiType now in CoreUtils)
585
586 applyTy, applyTys
587 ~~~~~~~~~~~~~~~~~
588 Instantiate a for-all type with one or more type arguments.
589 Used when we have a polymorphic function applied to type args:
590         f t1 t2
591 Then we use (applyTys type-of-f [t1,t2]) to compute the type of
592 the expression. 
593
594 \begin{code}
595 applyTy :: Type -> Type -> Type
596 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
597 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
598 applyTy other            arg = panic "applyTy"
599
600 applyTys :: Type -> [Type] -> Type
601 -- This function is interesting because 
602 --      a) the function may have more for-alls than there are args
603 --      b) less obviously, it may have fewer for-alls
604 -- For case (b) think of 
605 --      applyTys (forall a.a) [forall b.b, Int]
606 -- This really can happen, via dressing up polymorphic types with newtype
607 -- clothing.  Here's an example:
608 --      newtype R = R (forall a. a->a)
609 --      foo = case undefined :: R of
610 --              R f -> f ()
611
612 applyTys orig_fun_ty []      = orig_fun_ty
613 applyTys orig_fun_ty arg_tys 
614   | n_tvs == n_args     -- The vastly common case
615   = substTyWith tvs arg_tys rho_ty
616   | n_tvs > n_args      -- Too many for-alls
617   = substTyWith (take n_args tvs) arg_tys 
618                 (mkForAllTys (drop n_args tvs) rho_ty)
619   | otherwise           -- Too many type args
620   = ASSERT2( n_tvs > 0, ppr orig_fun_ty )       -- Zero case gives infnite loop!
621     applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
622              (drop n_tvs arg_tys)
623   where
624     (tvs, rho_ty) = splitForAllTys orig_fun_ty 
625     n_tvs = length tvs
626     n_args = length arg_tys     
627 \end{code}
628
629
630 %************************************************************************
631 %*                                                                      *
632 \subsection{Source types}
633 %*                                                                      *
634 %************************************************************************
635
636 A "source type" is a type that is a separate type as far as the type checker is
637 concerned, but which has low-level representation as far as the back end is concerned.
638
639 Source types are always lifted.
640
641 The key function is predTypeRep which gives the representation of a source type:
642
643 \begin{code}
644 mkPredTy :: PredType -> Type
645 mkPredTy pred = PredTy pred
646
647 mkPredTys :: ThetaType -> [Type]
648 mkPredTys preds = map PredTy preds
649
650 predTypeRep :: PredType -> Type
651 -- Convert a PredType to its "representation type";
652 -- the post-type-checking type used by all the Core passes of GHC.
653 -- Unwraps only the outermost level; for example, the result might
654 -- be a newtype application
655 predTypeRep (IParam _ ty)     = ty
656 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
657         -- Result might be a newtype application, but the consumer will
658         -- look through that too if necessary
659 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
660
661 mkFamilyTyConApp :: TyCon -> [Type] -> Type
662 -- Given a family instance TyCon and its arg types, return the
663 -- corresponding family type.  E.g.
664 --      data family T a
665 --      data instance T (Maybe b) = MkT b       -- Instance tycon :RTL
666 -- Then 
667 --      mkFamilyTyConApp :RTL Int  =  T (Maybe Int)
668 mkFamilyTyConApp tc tys
669   | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
670   , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
671   = mkTyConApp fam_tc (substTys fam_subst fam_tys)
672   | otherwise
673   = mkTyConApp tc tys
674
675 -- Pretty prints a tycon, using the family instance in case of a
676 -- representation tycon.  For example
677 --      e.g.  data T [a] = ...
678 -- In that case we want to print `T [a]', where T is the family TyCon
679 pprSourceTyCon tycon 
680   | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
681   = ppr $ fam_tc `TyConApp` tys        -- can't be FunTyCon
682   | otherwise
683   = ppr tycon
684 \end{code}
685
686
687 %************************************************************************
688 %*                                                                      *
689 \subsection{Kinds and free variables}
690 %*                                                                      *
691 %************************************************************************
692
693 ---------------------------------------------------------------------
694                 Finding the kind of a type
695                 ~~~~~~~~~~~~~~~~~~~~~~~~~~
696 \begin{code}
697 typeKind :: Type -> Kind
698 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
699                                    -- We should be looking for the coercion kind,
700                                    -- not the type kind
701                                 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
702 typeKind (NoteTy _ ty)        = typeKind ty
703 typeKind (PredTy pred)        = predKind pred
704 typeKind (AppTy fun arg)      = kindFunResult (typeKind fun)
705 typeKind (ForAllTy tv ty)     = typeKind ty
706 typeKind (TyVarTy tyvar)      = tyVarKind tyvar
707 typeKind (FunTy arg res)
708     -- Hack alert.  The kind of (Int -> Int#) is liftedTypeKind (*), 
709     --              not unliftedTypKind (#)
710     -- The only things that can be after a function arrow are
711     --   (a) types (of kind openTypeKind or its sub-kinds)
712     --   (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
713     | isTySuperKind k         = k
714     | otherwise               = ASSERT( isSubOpenTypeKind k) liftedTypeKind 
715     where
716       k = typeKind res
717
718 predKind :: PredType -> Kind
719 predKind (EqPred {}) = coSuperKind      -- A coercion kind!
720 predKind (ClassP {}) = liftedTypeKind   -- Class and implicitPredicates are
721 predKind (IParam {}) = liftedTypeKind   -- always represented by lifted types
722 \end{code}
723
724
725 ---------------------------------------------------------------------
726                 Free variables of a type
727                 ~~~~~~~~~~~~~~~~~~~~~~~~
728 \begin{code}
729 tyVarsOfType :: Type -> TyVarSet
730 -- NB: for type synonyms tyVarsOfType does *not* expand the synonym
731 tyVarsOfType (TyVarTy tv)               = unitVarSet tv
732 tyVarsOfType (TyConApp tycon tys)       = tyVarsOfTypes tys
733 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
734 tyVarsOfType (PredTy sty)               = tyVarsOfPred sty
735 tyVarsOfType (FunTy arg res)            = tyVarsOfType arg `unionVarSet` tyVarsOfType res
736 tyVarsOfType (AppTy fun arg)            = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
737 tyVarsOfType (ForAllTy tyvar ty)        = delVarSet (tyVarsOfType ty) tyvar
738
739 tyVarsOfTypes :: [Type] -> TyVarSet
740 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
741
742 tyVarsOfPred :: PredType -> TyVarSet
743 tyVarsOfPred (IParam _ ty)    = tyVarsOfType ty
744 tyVarsOfPred (ClassP _ tys)   = tyVarsOfTypes tys
745 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
746
747 tyVarsOfTheta :: ThetaType -> TyVarSet
748 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
749
750 -- Add a Note with the free tyvars to the top of the type
751 addFreeTyVars :: Type -> Type
752 addFreeTyVars ty@(NoteTy (FTVNote _) _)      = ty
753 addFreeTyVars ty                             = NoteTy (FTVNote (tyVarsOfType ty)) ty
754 \end{code}
755
756
757 %************************************************************************
758 %*                                                                      *
759 \subsection{Type families}
760 %*                                                                      *
761 %************************************************************************
762
763 Type family instances occuring in a type after expanding synonyms.
764
765 \begin{code}
766 tyFamInsts :: Type -> [(TyCon, [Type])]
767 tyFamInsts ty 
768   | Just exp_ty <- tcView ty    = tyFamInsts exp_ty
769 tyFamInsts (TyVarTy _)          = []
770 tyFamInsts (TyConApp tc tys) 
771   | isOpenSynTyCon tc           = [(tc, tys)]
772   | otherwise                   = concat (map tyFamInsts tys)
773 tyFamInsts (FunTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
774 tyFamInsts (AppTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
775 tyFamInsts (ForAllTy _ ty)      = tyFamInsts ty
776 \end{code}
777
778
779 %************************************************************************
780 %*                                                                      *
781 \subsection{TidyType}
782 %*                                                                      *
783 %************************************************************************
784
785 tidyTy tidies up a type for printing in an error message, or in
786 an interface file.
787
788 It doesn't change the uniques at all, just the print names.
789
790 \begin{code}
791 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
792 tidyTyVarBndr env@(tidy_env, subst) tyvar
793   = case tidyOccName tidy_env (getOccName name) of
794       (tidy', occ') -> ((tidy', subst'), tyvar'')
795         where
796           subst' = extendVarEnv subst tyvar tyvar''
797           tyvar' = setTyVarName tyvar name'
798           name'  = tidyNameOcc name occ'
799                 -- Don't forget to tidy the kind for coercions!
800           tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
801                   | otherwise     = tyvar'
802           kind'  = tidyType env (tyVarKind tyvar)
803   where
804     name = tyVarName tyvar
805
806 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
807 -- Add the free tyvars to the env in tidy form,
808 -- so that we can tidy the type they are free in
809 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
810
811 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
812 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
813
814 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
815 -- Treat a new tyvar as a binder, and give it a fresh tidy name
816 tidyOpenTyVar env@(tidy_env, subst) tyvar
817   = case lookupVarEnv subst tyvar of
818         Just tyvar' -> (env, tyvar')            -- Already substituted
819         Nothing     -> tidyTyVarBndr env tyvar  -- Treat it as a binder
820
821 tidyType :: TidyEnv -> Type -> Type
822 tidyType env@(tidy_env, subst) ty
823   = go ty
824   where
825     go (TyVarTy tv)         = case lookupVarEnv subst tv of
826                                 Nothing  -> TyVarTy tv
827                                 Just tv' -> TyVarTy tv'
828     go (TyConApp tycon tys) = let args = map go tys
829                               in args `seqList` TyConApp tycon args
830     go (NoteTy note ty)     = (NoteTy $! (go_note note)) $! (go ty)
831     go (PredTy sty)         = PredTy (tidyPred env sty)
832     go (AppTy fun arg)      = (AppTy $! (go fun)) $! (go arg)
833     go (FunTy fun arg)      = (FunTy $! (go fun)) $! (go arg)
834     go (ForAllTy tv ty)     = ForAllTy tvp $! (tidyType envp ty)
835                               where
836                                 (envp, tvp) = tidyTyVarBndr env tv
837
838     go_note note@(FTVNote ftvs) = note  -- No need to tidy the free tyvars
839
840 tidyTypes env tys = map (tidyType env) tys
841
842 tidyPred :: TidyEnv -> PredType -> PredType
843 tidyPred env (IParam n ty)     = IParam n (tidyType env ty)
844 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
845 tidyPred env (EqPred ty1 ty2)  = EqPred (tidyType env ty1) (tidyType env ty2)
846 \end{code}
847
848
849 @tidyOpenType@ grabs the free type variables, tidies them
850 and then uses @tidyType@ to work over the type itself
851
852 \begin{code}
853 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
854 tidyOpenType env ty
855   = (env', tidyType env' ty)
856   where
857     env' = tidyFreeTyVars env (tyVarsOfType ty)
858
859 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
860 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
861
862 tidyTopType :: Type -> Type
863 tidyTopType ty = tidyType emptyTidyEnv ty
864 \end{code}
865
866 \begin{code}
867
868 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
869 tidyKind env k = tidyOpenType env k
870
871 \end{code}
872
873
874 %************************************************************************
875 %*                                                                      *
876 \subsection{Liftedness}
877 %*                                                                      *
878 %************************************************************************
879
880 \begin{code}
881 isUnLiftedType :: Type -> Bool
882         -- isUnLiftedType returns True for forall'd unlifted types:
883         --      x :: forall a. Int#
884         -- I found bindings like these were getting floated to the top level.
885         -- They are pretty bogus types, mind you.  It would be better never to
886         -- construct them
887
888 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
889 isUnLiftedType (ForAllTy tv ty)  = isUnLiftedType ty
890 isUnLiftedType (TyConApp tc _)   = isUnLiftedTyCon tc
891 isUnLiftedType other             = False        
892
893 isUnboxedTupleType :: Type -> Bool
894 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
895                            Just (tc, ty_args) -> isUnboxedTupleTyCon tc
896                            other              -> False
897
898 -- Should only be applied to *types*; hence the assert
899 isAlgType :: Type -> Bool
900 isAlgType ty 
901   = case splitTyConApp_maybe ty of
902       Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
903                             isAlgTyCon tc
904       _other             -> False
905
906 -- Should only be applied to *types*; hence the assert
907 isClosedAlgType :: Type -> Bool
908 isClosedAlgType ty
909   = case splitTyConApp_maybe ty of
910       Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
911                             isAlgTyCon tc && not (isOpenTyCon tc)
912       _other             -> False
913 \end{code}
914
915 @isStrictType@ computes whether an argument (or let RHS) should
916 be computed strictly or lazily, based only on its type.
917 Works just like isUnLiftedType, except that it has a special case 
918 for dictionaries.  Since it takes account of ClassP, you might think
919 this function should be in TcType, but isStrictType is used by DataCon,
920 which is below TcType in the hierarchy, so it's convenient to put it here.
921
922 \begin{code}
923 isStrictType (PredTy pred)     = isStrictPred pred
924 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
925 isStrictType (ForAllTy tv ty)  = isStrictType ty
926 isStrictType (TyConApp tc _)   = isUnLiftedTyCon tc
927 isStrictType other             = False  
928
929 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
930 isStrictPred other           = False
931         -- We may be strict in dictionary types, but only if it 
932         -- has more than one component.
933         -- [Being strict in a single-component dictionary risks
934         --  poking the dictionary component, which is wrong.]
935 \end{code}
936
937 \begin{code}
938 isPrimitiveType :: Type -> Bool
939 -- Returns types that are opaque to Haskell.
940 -- Most of these are unlifted, but now that we interact with .NET, we
941 -- may have primtive (foreign-imported) types that are lifted
942 isPrimitiveType ty = case splitTyConApp_maybe ty of
943                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
944                                               isPrimTyCon tc
945                         other              -> False
946 \end{code}
947
948
949 %************************************************************************
950 %*                                                                      *
951 \subsection{Sequencing on types
952 %*                                                                      *
953 %************************************************************************
954
955 \begin{code}
956 seqType :: Type -> ()
957 seqType (TyVarTy tv)      = tv `seq` ()
958 seqType (AppTy t1 t2)     = seqType t1 `seq` seqType t2
959 seqType (FunTy t1 t2)     = seqType t1 `seq` seqType t2
960 seqType (NoteTy note t2)  = seqNote note `seq` seqType t2
961 seqType (PredTy p)        = seqPred p
962 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
963 seqType (ForAllTy tv ty)  = tv `seq` seqType ty
964
965 seqTypes :: [Type] -> ()
966 seqTypes []       = ()
967 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
968
969 seqNote :: TyNote -> ()
970 seqNote (FTVNote set) = sizeUniqSet set `seq` ()
971
972 seqPred :: PredType -> ()
973 seqPred (ClassP c tys)   = c `seq` seqTypes tys
974 seqPred (IParam n ty)    = n `seq` seqType ty
975 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
976 \end{code}
977
978
979 %************************************************************************
980 %*                                                                      *
981                 Equality for Core types 
982         (We don't use instances so that we know where it happens)
983 %*                                                                      *
984 %************************************************************************
985
986 Note that eqType works right even for partial applications of newtypes.
987 See Note [Newtype eta] in TyCon.lhs
988
989 \begin{code}
990 coreEqType :: Type -> Type -> Bool
991 coreEqType t1 t2
992   = eq rn_env t1 t2
993   where
994     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
995
996     eq env (TyVarTy tv1)       (TyVarTy tv2)     = rnOccL env tv1 == rnOccR env tv2
997     eq env (ForAllTy tv1 t1)   (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
998     eq env (AppTy s1 t1)       (AppTy s2 t2)     = eq env s1 s2 && eq env t1 t2
999     eq env (FunTy s1 t1)       (FunTy s2 t2)     = eq env s1 s2 && eq env t1 t2
1000     eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
1001         | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1002                         -- The lengths should be equal because
1003                         -- the two types have the same kind
1004         -- NB: if the type constructors differ that does not 
1005         --     necessarily mean that the types aren't equal
1006         --     (synonyms, newtypes)
1007         -- Even if the type constructors are the same, but the arguments
1008         -- differ, the two types could be the same (e.g. if the arg is just
1009         -- ignored in the RHS).  In both these cases we fall through to an 
1010         -- attempt to expand one side or the other.
1011
1012         -- Now deal with newtypes, synonyms, pred-tys
1013     eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2 
1014                  | Just t2' <- coreView t2 = eq env t1 t2' 
1015
1016         -- Fall through case; not equal!
1017     eq env t1 t2 = False
1018 \end{code}
1019
1020
1021 %************************************************************************
1022 %*                                                                      *
1023                 Comparision for source types 
1024         (We don't use instances so that we know where it happens)
1025 %*                                                                      *
1026 %************************************************************************
1027
1028 Note that 
1029         tcEqType, tcCmpType 
1030 do *not* look through newtypes, PredTypes
1031
1032 \begin{code}
1033 tcEqType :: Type -> Type -> Bool
1034 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1035
1036 tcEqTypes :: [Type] -> [Type] -> Bool
1037 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1038
1039 tcCmpType :: Type -> Type -> Ordering
1040 tcCmpType t1 t2 = cmpType t1 t2
1041
1042 tcCmpTypes :: [Type] -> [Type] -> Ordering
1043 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1044
1045 tcEqPred :: PredType -> PredType -> Bool
1046 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1047
1048 tcCmpPred :: PredType -> PredType -> Ordering
1049 tcCmpPred p1 p2 = cmpPred p1 p2
1050
1051 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1052 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1053 \end{code}
1054
1055 Checks whether the second argument is a subterm of the first.  (We don't care
1056 about binders, as we are only interested in syntactic subterms.)
1057
1058 \begin{code}
1059 tcPartOfType :: Type -> Type -> Bool
1060 tcPartOfType t1              t2 
1061   | tcEqType t1 t2              = True
1062 tcPartOfType t1              t2 
1063   | Just t2' <- tcView t2       = tcPartOfType t1 t2'
1064 tcPartOfType _  (TyVarTy _)     = False
1065 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1066 tcPartOfType t1 (AppTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1067 tcPartOfType t1 (FunTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1068 tcPartOfType t1 (PredTy p2)     = tcPartOfPred t1 p2
1069 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1070 tcPartOfType t1 (NoteTy _ t2)   = tcPartOfType t1 t2
1071
1072 tcPartOfPred :: Type -> PredType -> Bool
1073 tcPartOfPred t1 (IParam _ t2)  = tcPartOfType t1 t2
1074 tcPartOfPred t1 (ClassP _ ts)  = any (tcPartOfType t1) ts
1075 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1076 \end{code}
1077
1078 Now here comes the real worker
1079
1080 \begin{code}
1081 cmpType :: Type -> Type -> Ordering
1082 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1083   where
1084     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1085
1086 cmpTypes :: [Type] -> [Type] -> Ordering
1087 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1088   where
1089     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1090
1091 cmpPred :: PredType -> PredType -> Ordering
1092 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1093   where
1094     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1095
1096 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering  -- Main workhorse
1097 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1098                    | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1099
1100 cmpTypeX env (TyVarTy tv1)       (TyVarTy tv2)       = rnOccL env tv1 `compare` rnOccR env tv2
1101 cmpTypeX env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1102 cmpTypeX env (AppTy s1 t1)       (AppTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1103 cmpTypeX env (FunTy s1 t1)       (FunTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1104 cmpTypeX env (PredTy p1)         (PredTy p2)         = cmpPredX env p1 p2
1105 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1106 cmpTypeX env t1                 (NoteTy _ t2)        = cmpTypeX env t1 t2
1107
1108     -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1109 cmpTypeX env (AppTy _ _) (TyVarTy _) = GT
1110     
1111 cmpTypeX env (FunTy _ _) (TyVarTy _) = GT
1112 cmpTypeX env (FunTy _ _) (AppTy _ _) = GT
1113     
1114 cmpTypeX env (TyConApp _ _) (TyVarTy _) = GT
1115 cmpTypeX env (TyConApp _ _) (AppTy _ _) = GT
1116 cmpTypeX env (TyConApp _ _) (FunTy _ _) = GT
1117     
1118 cmpTypeX env (ForAllTy _ _) (TyVarTy _)    = GT
1119 cmpTypeX env (ForAllTy _ _) (AppTy _ _)    = GT
1120 cmpTypeX env (ForAllTy _ _) (FunTy _ _)    = GT
1121 cmpTypeX env (ForAllTy _ _) (TyConApp _ _) = GT
1122
1123 cmpTypeX env (PredTy _)   t2            = GT
1124
1125 cmpTypeX env _ _ = LT
1126
1127 -------------
1128 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1129 cmpTypesX env []        []        = EQ
1130 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1131 cmpTypesX env []        tys       = LT
1132 cmpTypesX env ty        []        = GT
1133
1134 -------------
1135 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1136 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1137         -- Compare names only for implicit parameters
1138         -- This comparison is used exclusively (I believe) 
1139         -- for the Avails finite map built in TcSimplify
1140         -- If the types differ we keep them distinct so that we see 
1141         -- a distinct pair to run improvement on 
1142 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1143 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1144
1145 -- Constructor order: IParam < ClassP < EqPred
1146 cmpPredX env (IParam {})     _              = LT
1147 cmpPredX env (ClassP {})    (IParam {})     = GT
1148 cmpPredX env (ClassP {})    (EqPred {})     = LT
1149 cmpPredX env (EqPred {})    _               = GT
1150 \end{code}
1151
1152 PredTypes are used as a FM key in TcSimplify, 
1153 so we take the easy path and make them an instance of Ord
1154
1155 \begin{code}
1156 instance Eq  PredType where { (==)    = tcEqPred }
1157 instance Ord PredType where { compare = tcCmpPred }
1158 \end{code}
1159
1160
1161 %************************************************************************
1162 %*                                                                      *
1163                 Type substitutions
1164 %*                                                                      *
1165 %************************************************************************
1166
1167 \begin{code}
1168 data TvSubst            
1169   = TvSubst InScopeSet  -- The in-scope type variables
1170             TvSubstEnv  -- The substitution itself
1171         -- See Note [Apply Once]
1172         -- and Note [Extending the TvSubstEnv]
1173
1174 {- ----------------------------------------------------------
1175
1176 Note [Apply Once]
1177 ~~~~~~~~~~~~~~~~~
1178 We use TvSubsts to instantiate things, and we might instantiate
1179         forall a b. ty
1180 \with the types
1181         [a, b], or [b, a].
1182 So the substition might go [a->b, b->a].  A similar situation arises in Core
1183 when we find a beta redex like
1184         (/\ a /\ b -> e) b a
1185 Then we also end up with a substition that permutes type variables. Other
1186 variations happen to; for example [a -> (a, b)].  
1187
1188         ***************************************************
1189         *** So a TvSubst must be applied precisely once ***
1190         ***************************************************
1191
1192 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1193 we use during unifications, it must not be repeatedly applied.
1194
1195 Note [Extending the TvSubst]
1196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1197 The following invariant should hold of a TvSubst
1198
1199         The in-scope set is needed *only* to
1200         guide the generation of fresh uniques
1201
1202         In particular, the *kind* of the type variables in 
1203         the in-scope set is not relevant
1204
1205 This invariant allows a short-cut when the TvSubstEnv is empty:
1206 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1207 then (substTy subst ty) does nothing.
1208
1209 For example, consider:
1210         (/\a. /\b:(a~Int). ...b..) Int
1211 We substitute Int for 'a'.  The Unique of 'b' does not change, but
1212 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1213
1214 This invariant has several crucial consequences:
1215
1216 * In substTyVarBndr, we need extend the TvSubstEnv 
1217         - if the unique has changed
1218         - or if the kind has changed
1219
1220 * In substTyVar, we do not need to consult the in-scope set;
1221   the TvSubstEnv is enough
1222
1223 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1224   
1225
1226 -------------------------------------------------------------- -}
1227
1228
1229 type TvSubstEnv = TyVarEnv Type
1230         -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1231         -- invariant discussed in Note [Apply Once]), and also independently
1232         -- in the middle of matching, and unification (see Types.Unify)
1233         -- So you have to look at the context to know if it's idempotent or
1234         -- apply-once or whatever
1235 emptyTvSubstEnv :: TvSubstEnv
1236 emptyTvSubstEnv = emptyVarEnv
1237
1238 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1239 -- (compose env1 env2)(x) is env1(env2(x)); i.e. apply env2 then env1
1240 -- It assumes that both are idempotent
1241 -- Typically, env1 is the refinement to a base substitution env2
1242 composeTvSubst in_scope env1 env2
1243   = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1244         -- First apply env1 to the range of env2
1245         -- Then combine the two, making sure that env1 loses if
1246         -- both bind the same variable; that's why env1 is the
1247         --  *left* argument to plusVarEnv, because the right arg wins
1248   where
1249     subst1 = TvSubst in_scope env1
1250
1251 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1252
1253 isEmptyTvSubst :: TvSubst -> Bool
1254          -- See Note [Extending the TvSubstEnv]
1255 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1256
1257 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1258 mkTvSubst = TvSubst
1259
1260 getTvSubstEnv :: TvSubst -> TvSubstEnv
1261 getTvSubstEnv (TvSubst _ env) = env
1262
1263 getTvInScope :: TvSubst -> InScopeSet
1264 getTvInScope (TvSubst in_scope _) = in_scope
1265
1266 isInScope :: Var -> TvSubst -> Bool
1267 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1268
1269 notElemTvSubst :: TyVar -> TvSubst -> Bool
1270 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1271
1272 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1273 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1274
1275 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1276 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1277
1278 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1279 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1280
1281 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1282 extendTvSubstList (TvSubst in_scope env) tvs tys 
1283   = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1284
1285 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1286 -- the types given; but it's just a thunk so with a bit of luck
1287 -- it'll never be evaluated
1288
1289 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1290 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1291
1292 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1293 zipOpenTvSubst tyvars tys 
1294 #ifdef DEBUG
1295   | length tyvars /= length tys
1296   = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1297   | otherwise
1298 #endif
1299   = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1300
1301 -- mkTopTvSubst is called when doing top-level substitutions.
1302 -- Here we expect that the free vars of the range of the
1303 -- substitution will be empty.
1304 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1305 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1306
1307 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1308 zipTopTvSubst tyvars tys 
1309 #ifdef DEBUG
1310   | length tyvars /= length tys
1311   = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1312   | otherwise
1313 #endif
1314   = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1315
1316 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1317 zipTyEnv tyvars tys
1318 #ifdef DEBUG
1319   | length tyvars /= length tys
1320   = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1321   | otherwise
1322 #endif
1323   = zip_ty_env tyvars tys emptyVarEnv
1324
1325 -- Later substitutions in the list over-ride earlier ones, 
1326 -- but there should be no loops
1327 zip_ty_env []       []       env = env
1328 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1329         -- There used to be a special case for when 
1330         --      ty == TyVarTy tv
1331         -- (a not-uncommon case) in which case the substitution was dropped.
1332         -- But the type-tidier changes the print-name of a type variable without
1333         -- changing the unique, and that led to a bug.   Why?  Pre-tidying, we had 
1334         -- a type {Foo t}, where Foo is a one-method class.  So Foo is really a newtype.
1335         -- And it happened that t was the type variable of the class.  Post-tiding, 
1336         -- it got turned into {Foo t2}.  The ext-core printer expanded this using
1337         -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1338         -- and so generated a rep type mentioning t not t2.  
1339         --
1340         -- Simplest fix is to nuke the "optimisation"
1341 zip_ty_env tvs      tys      env   = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1342 -- zip_ty_env _ _ env = env
1343
1344 instance Outputable TvSubst where
1345   ppr (TvSubst ins env) 
1346     = brackets $ sep[ ptext SLIT("TvSubst"),
1347                       nest 2 (ptext SLIT("In scope:") <+> ppr ins), 
1348                       nest 2 (ptext SLIT("Env:") <+> ppr env) ]
1349 \end{code}
1350
1351 %************************************************************************
1352 %*                                                                      *
1353                 Performing type substitutions
1354 %*                                                                      *
1355 %************************************************************************
1356
1357 \begin{code}
1358 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1359 substTyWith tvs tys = ASSERT( length tvs == length tys )
1360                       substTy (zipOpenTvSubst tvs tys)
1361
1362 substTy :: TvSubst -> Type  -> Type
1363 substTy subst ty | isEmptyTvSubst subst = ty
1364                  | otherwise            = subst_ty subst ty
1365
1366 substTys :: TvSubst -> [Type] -> [Type]
1367 substTys subst tys | isEmptyTvSubst subst = tys
1368                    | otherwise            = map (subst_ty subst) tys
1369
1370 substTheta :: TvSubst -> ThetaType -> ThetaType
1371 substTheta subst theta
1372   | isEmptyTvSubst subst = theta
1373   | otherwise            = map (substPred subst) theta
1374
1375 substPred :: TvSubst -> PredType -> PredType
1376 substPred subst (IParam n ty)     = IParam n (subst_ty subst ty)
1377 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1378 substPred subst (EqPred ty1 ty2)  = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1379
1380 deShadowTy :: TyVarSet -> Type -> Type  -- Remove any nested binders mentioning tvs
1381 deShadowTy tvs ty 
1382   = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1383   where
1384     in_scope = mkInScopeSet tvs
1385
1386 subst_ty :: TvSubst -> Type -> Type
1387 -- subst_ty is the main workhorse for type substitution
1388 --
1389 -- Note that the in_scope set is poked only if we hit a forall
1390 -- so it may often never be fully computed 
1391 subst_ty subst ty
1392    = go ty
1393   where
1394     go (TyVarTy tv)                = substTyVar subst tv
1395     go (TyConApp tc tys)           = let args = map go tys
1396                                      in  args `seqList` TyConApp tc args
1397
1398     go (PredTy p)                  = PredTy $! (substPred subst p)
1399
1400     go (NoteTy (FTVNote _) ty2)    = go ty2             -- Discard the free tyvar note
1401
1402     go (FunTy arg res)             = (FunTy $! (go arg)) $! (go res)
1403     go (AppTy fun arg)             = mkAppTy (go fun) $! (go arg)
1404                 -- The mkAppTy smart constructor is important
1405                 -- we might be replacing (a Int), represented with App
1406                 -- by [Int], represented with TyConApp
1407     go (ForAllTy tv ty)            = case substTyVarBndr subst tv of
1408                                         (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty)
1409
1410 substTyVar :: TvSubst -> TyVar  -> Type
1411 substTyVar subst@(TvSubst in_scope env) tv
1412   = case lookupTyVar subst tv of {
1413         Nothing -> TyVarTy tv;
1414         Just ty -> ty   -- See Note [Apply Once]
1415     } 
1416
1417 substTyVars :: TvSubst -> [TyVar] -> [Type]
1418 substTyVars subst tvs = map (substTyVar subst) tvs
1419
1420 lookupTyVar :: TvSubst -> TyVar  -> Maybe Type
1421         -- See Note [Extending the TvSubst]
1422 lookupTyVar (TvSubst in_scope env) tv = lookupVarEnv env tv
1423
1424 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)  
1425 substTyVarBndr subst@(TvSubst in_scope env) old_var
1426   = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1427   where
1428     is_co_var = isCoVar old_var
1429
1430     new_env | no_change = delVarEnv env old_var
1431             | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1432
1433     no_change = new_var == old_var && not is_co_var
1434         -- no_change means that the new_var is identical in
1435         -- all respects to the old_var (same unique, same kind)
1436         -- See Note [Extending the TvSubst]
1437         --
1438         -- In that case we don't need to extend the substitution
1439         -- to map old to new.  But instead we must zap any 
1440         -- current substitution for the variable. For example:
1441         --      (\x.e) with id_subst = [x |-> e']
1442         -- Here we must simply zap the substitution for x
1443
1444     new_var = uniqAway in_scope subst_old_var
1445         -- The uniqAway part makes sure the new variable is not already in scope
1446
1447     subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1448                   -- It's only worth doing the substitution for coercions,
1449                   -- becuase only they can have free type variables
1450         | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1451         | otherwise = old_var
1452 \end{code}
1453
1454 ----------------------------------------------------
1455 -- Kind Stuff
1456
1457 Kinds
1458 ~~~~~
1459 There's a little subtyping at the kind level:  
1460
1461                  ?
1462                 / \
1463                /   \
1464               ??   (#)
1465              /  \
1466             *   #
1467
1468 where   *    [LiftedTypeKind]   means boxed type
1469         #    [UnliftedTypeKind] means unboxed type
1470         (#)  [UbxTupleKind]     means unboxed tuple
1471         ??   [ArgTypeKind]      is the lub of *,#
1472         ?    [OpenTypeKind]     means any type at all
1473
1474 In particular:
1475
1476         error :: forall a:?. String -> a
1477         (->)  :: ?? -> ? -> *
1478         (\(x::t) -> ...)        Here t::?? (i.e. not unboxed tuple)
1479
1480 \begin{code}
1481 type KindVar = TyVar  -- invariant: KindVar will always be a 
1482                       -- TcTyVar with details MetaTv TauTv ...
1483 -- kind var constructors and functions are in TcType
1484
1485 type SimpleKind = Kind
1486 \end{code}
1487
1488 Kind inference
1489 ~~~~~~~~~~~~~~
1490 During kind inference, a kind variable unifies only with 
1491 a "simple kind", sk
1492         sk ::= * | sk1 -> sk2
1493 For example 
1494         data T a = MkT a (T Int#)
1495 fails.  We give T the kind (k -> *), and the kind variable k won't unify
1496 with # (the kind of Int#).
1497
1498 Type inference
1499 ~~~~~~~~~~~~~~
1500 When creating a fresh internal type variable, we give it a kind to express 
1501 constraints on it.  E.g. in (\x->e) we make up a fresh type variable for x, 
1502 with kind ??.  
1503
1504 During unification we only bind an internal type variable to a type
1505 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1506
1507 When unifying two internal type variables, we collect their kind constraints by
1508 finding the GLB of the two.  Since the partial order is a tree, they only
1509 have a glb if one is a sub-kind of the other.  In that case, we bind the
1510 less-informative one to the more informative one.  Neat, eh?
1511
1512
1513 \begin{code}
1514
1515 \end{code}
1516
1517 %************************************************************************
1518 %*                                                                      *
1519         Functions over Kinds            
1520 %*                                                                      *
1521 %************************************************************************
1522
1523 \begin{code}
1524 kindFunResult :: Kind -> Kind
1525 kindFunResult k = funResultTy k
1526
1527 splitKindFunTys :: Kind -> ([Kind],Kind)
1528 splitKindFunTys k = splitFunTys k
1529
1530 splitKindFunTysN :: Int -> Kind -> ([Kind],Kind)
1531 splitKindFunTysN k = splitFunTysN k
1532
1533 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1534
1535 isOpenTypeKindCon tc    = tyConUnique tc == openTypeKindTyConKey
1536
1537 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1538 isOpenTypeKind other           = False
1539
1540 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1541
1542 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1543 isUbxTupleKind other           = False
1544
1545 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1546
1547 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1548 isArgTypeKind other = False
1549
1550 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1551
1552 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1553 isUnliftedTypeKind other           = False
1554
1555 isSubOpenTypeKind :: Kind -> Bool
1556 -- True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1557 isSubOpenTypeKind (FunTy k1 k2)    = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) ) 
1558                                      ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) ) 
1559                                      False
1560 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1561 isSubOpenTypeKind other            = ASSERT( isKind other ) False
1562          -- This is a conservative answer
1563          -- It matters in the call to isSubKind in
1564          -- checkExpectedKind.
1565
1566 isSubArgTypeKindCon kc
1567   | isUnliftedTypeKindCon kc = True
1568   | isLiftedTypeKindCon kc   = True
1569   | isArgTypeKindCon kc      = True
1570   | otherwise                = False
1571
1572 isSubArgTypeKind :: Kind -> Bool
1573 -- True of any sub-kind of ArgTypeKind 
1574 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1575 isSubArgTypeKind other            = False
1576
1577 isSuperKind :: Type -> Bool
1578 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1579 isSuperKind other = False
1580
1581 isKind :: Kind -> Bool
1582 isKind k = isSuperKind (typeKind k)
1583
1584 isSubKind :: Kind -> Kind -> Bool
1585 -- (k1 `isSubKind` k2) checks that k1 <: k2
1586 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc2
1587 isSubKind (FunTy a1 r1) (FunTy a2 r2)         = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1588 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2')) 
1589   = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1590 isSubKind k1            k2                    = False
1591
1592 eqKind :: Kind -> Kind -> Bool
1593 eqKind = tcEqType
1594
1595 isSubKindCon :: TyCon -> TyCon -> Bool
1596 -- (kc1 `isSubKindCon` kc2) checks that kc1 <: kc2
1597 isSubKindCon kc1 kc2
1598   | isLiftedTypeKindCon kc1   && isLiftedTypeKindCon kc2   = True
1599   | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1600   | isUbxTupleKindCon kc1     && isUbxTupleKindCon kc2     = True
1601   | isOpenTypeKindCon kc2                                  = True 
1602                            -- we already know kc1 is not a fun, its a TyCon
1603   | isArgTypeKindCon kc2      && isSubArgTypeKindCon kc1   = True
1604   | otherwise                                              = False
1605
1606 defaultKind :: Kind -> Kind
1607 -- Used when generalising: default kind '?' and '??' to '*'
1608 -- 
1609 -- When we generalise, we make generic type variables whose kind is
1610 -- simple (* or *->* etc).  So generic type variables (other than
1611 -- built-in constants like 'error') always have simple kinds.  This is important;
1612 -- consider
1613 --      f x = True
1614 -- We want f to get type
1615 --      f :: forall (a::*). a -> Bool
1616 -- Not 
1617 --      f :: forall (a::??). a -> Bool
1618 -- because that would allow a call like (f 3#) as well as (f True),
1619 --and the calling conventions differ.  This defaulting is done in TcMType.zonkTcTyVarBndr.
1620 defaultKind k 
1621   | isSubOpenTypeKind k = liftedTypeKind
1622   | isSubArgTypeKind k  = liftedTypeKind
1623   | otherwise        = k
1624
1625 isEqPred :: PredType -> Bool
1626 isEqPred (EqPred _ _) = True
1627 isEqPred other        = False
1628 \end{code}