2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
6 Type - public interface
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
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
16 -- | Main functions for manipulating types and type-related things
18 -- Note some of this is just re-exports from TyCon..
20 -- * Main data types representing Types
21 -- $type_classification
23 -- $representation_types
24 TyThing(..), Type, PredType(..), ThetaType,
26 -- ** Constructing and deconstructing types
27 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
29 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
30 splitAppTy_maybe, repSplitAppTy_maybe,
32 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
33 splitFunTys, splitFunTysN,
34 funResultTy, funArgTy, zipFunTys,
36 mkTyConApp, mkTyConTy,
37 tyConAppTyCon, tyConAppArgs,
38 splitTyConApp_maybe, splitTyConApp,
39 splitNewTyConApp_maybe, splitNewTyConApp,
41 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
42 applyTy, applyTys, applyTysD, isForAllTy, dropForAlls,
51 mkPredTy, mkPredTys, mkFamilyTyConApp,
53 -- ** Common type constructors
56 -- ** Predicates on types
59 -- (Lifting and boxity)
60 isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
61 isPrimitiveType, isStrictType, isStrictPred,
63 -- * Main data types representing Kinds
65 Kind, SimpleKind, KindVar,
67 -- ** Deconstructing Kinds
68 kindFunResult, splitKindFunTys, splitKindFunTysN,
70 -- ** Common Kinds and SuperKinds
71 liftedTypeKind, unliftedTypeKind, openTypeKind,
72 argTypeKind, ubxTupleKind,
74 tySuperKind, coSuperKind,
76 -- ** Common Kind type constructors
77 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
78 argTypeKindTyCon, ubxTupleKindTyCon,
80 -- ** Predicates on Kinds
81 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
82 isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind,
83 isCoSuperKind, isSuperKind, isCoercionKind, isEqPred,
84 mkArrowKind, mkArrowKinds,
86 isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
89 -- * Type free variables
90 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
93 -- * Tidying type related things up for printing
95 tidyOpenType, tidyOpenTypes,
96 tidyTyVarBndr, tidyFreeTyVars,
97 tidyOpenTyVar, tidyOpenTyVars,
98 tidyTopType, tidyPred,
102 coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
103 tcEqPred, tcEqPredX, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
105 -- * Forcing evaluation of types
108 -- * Other views onto Types
109 coreView, tcView, kindView,
113 -- * Type representation for the code generator
116 typePrimRep, predTypeRep,
118 -- * Main type substitution data types
119 TvSubstEnv, -- Representation widely visible
120 TvSubst(..), -- Representation visible to a few friends
122 -- ** Manipulating type substitutions
123 emptyTvSubstEnv, emptyTvSubst,
125 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
126 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
127 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
130 -- ** Performing substitution on types
131 substTy, substTys, substTyWith, substTysWith, substTheta,
132 substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
135 pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
136 pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind,
141 #include "HsVersions.h"
143 -- We import the representation and primitive functions from TypeRep.
144 -- Many things are reexported, but not the representation!
165 import Data.Maybe ( isJust )
169 -- $type_classification
170 -- #type_classification#
174 -- [Unboxed] Iff its representation is other than a pointer
175 -- Unboxed types are also unlifted.
177 -- [Lifted] Iff it has bottom as an element.
178 -- Closures always have lifted types: i.e. any
179 -- let-bound identifier in Core must have a lifted
180 -- type. Operationally, a lifted object is one that
182 -- Only lifted types may be unified with a type variable.
184 -- [Algebraic] Iff it is a type with one or more constructors, whether
185 -- declared with @data@ or @newtype@.
186 -- An algebraic type is one that can be deconstructed
187 -- with a case expression. This is /not/ the same as
188 -- lifted types, because we also include unboxed
189 -- tuples in this classification.
191 -- [Data] Iff it is a type declared with @data@, or a boxed tuple.
193 -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
195 -- Currently, all primitive types are unlifted, but that's not necessarily
196 -- the case: for example, @Int@ could be primitive.
198 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
199 -- but unlifted (such as @ByteArray#@). The only primitive types that we
200 -- classify as algebraic are the unboxed tuples.
202 -- Some examples of type classifications that may make this a bit clearer are:
205 -- Type primitive boxed lifted algebraic
206 -- -----------------------------------------------------------------------------
208 -- ByteArray# Yes Yes No No
209 -- (\# a, b \#) Yes No No Yes
210 -- ( a, b ) No Yes Yes Yes
211 -- [a] No Yes Yes Yes
214 -- $representation_types
215 -- A /source type/ is a type that is a separate type as far as the type checker is
216 -- concerned, but which has a more low-level representation as far as Core-to-Core
217 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
218 -- from the representation type while they do exist in the source types.
220 -- You don't normally have to worry about this, as the utility functions in
221 -- this module will automatically convert a source into a representation type
222 -- if they are spotted, to the best of it's abilities. If you don't want this
223 -- to happen, use the equivalent functions from the "TcType" module.
226 %************************************************************************
230 %************************************************************************
233 {-# INLINE coreView #-}
234 coreView :: Type -> Maybe Type
235 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
236 -- function tries to obtain a different view of the supplied type given this
238 -- Strips off the /top layer only/ of a type to give
239 -- its underlying representation type.
240 -- Returns Nothing if there is nothing to look through.
242 -- In the case of @newtype@s, it returns one of:
244 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
246 -- 2) The newtype representation (otherwise), meaning the
247 -- type written in the RHS of the newtype declaration,
248 -- which may itself be a newtype
250 -- For example, with:
252 -- > newtype R = MkR S
253 -- > newtype S = MkS T
254 -- > newtype T = MkT (T -> T)
256 -- 'expandNewTcApp' on:
258 -- * @R@ gives @Just S@
259 -- * @S@ gives @Just T@
260 -- * @T@ gives @Nothing@ (no expansion)
262 -- By being non-recursive and inlined, this case analysis gets efficiently
263 -- joined onto the case analysis that the caller is already doing
265 | isEqPred p = Nothing
266 | otherwise = Just (predTypeRep p)
267 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
268 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
269 -- Its important to use mkAppTys, rather than (foldl AppTy),
270 -- because the function part might well return a
271 -- partially-applied type constructor; indeed, usually will!
276 -----------------------------------------------
277 {-# INLINE tcView #-}
278 tcView :: Type -> Maybe Type
279 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
280 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
281 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
284 -----------------------------------------------
285 {-# INLINE kindView #-}
286 kindView :: Kind -> Maybe Kind
287 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
289 -- For the moment, we don't even handle synonyms in kinds
294 %************************************************************************
296 \subsection{Constructor-specific functions}
298 %************************************************************************
301 ---------------------------------------------------------------------
305 mkTyVarTy :: TyVar -> Type
308 mkTyVarTys :: [TyVar] -> [Type]
309 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
311 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
312 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
313 getTyVar :: String -> Type -> TyVar
314 getTyVar msg ty = case getTyVar_maybe ty of
316 Nothing -> panic ("getTyVar: " ++ msg)
318 isTyVarTy :: Type -> Bool
319 isTyVarTy ty = isJust (getTyVar_maybe ty)
321 -- | Attempts to obtain the type variable underlying a 'Type'
322 getTyVar_maybe :: Type -> Maybe TyVar
323 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
324 getTyVar_maybe (TyVarTy tv) = Just tv
325 getTyVar_maybe _ = Nothing
330 ---------------------------------------------------------------------
333 We need to be pretty careful with AppTy to make sure we obey the
334 invariant that a TyConApp is always visibly so. mkAppTy maintains the
338 -- | Applies a type to another, as in e.g. @k a@
339 mkAppTy :: Type -> Type -> Type
340 mkAppTy orig_ty1 orig_ty2
343 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
344 mk_app _ = AppTy orig_ty1 orig_ty2
345 -- Note that the TyConApp could be an
346 -- under-saturated type synonym. GHC allows that; e.g.
347 -- type Foo k = k a -> k a
349 -- foo :: Foo Id -> Foo Id
351 -- Here Id is partially applied in the type sig for Foo,
352 -- but once the type synonyms are expanded all is well
354 mkAppTys :: Type -> [Type] -> Type
355 mkAppTys orig_ty1 [] = orig_ty1
356 -- This check for an empty list of type arguments
357 -- avoids the needless loss of a type synonym constructor.
358 -- For example: mkAppTys Rational []
359 -- returns to (Ratio Integer), which has needlessly lost
360 -- the Rational part.
361 mkAppTys orig_ty1 orig_tys2
364 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
365 -- mkTyConApp: see notes with mkAppTy
366 mk_app _ = foldl AppTy orig_ty1 orig_tys2
369 splitAppTy_maybe :: Type -> Maybe (Type, Type)
370 -- ^ Attempt to take a type application apart, whether it is a
371 -- function, type constructor, or plain type application. Note
372 -- that type family applications are NEVER unsaturated by this!
373 splitAppTy_maybe ty | Just ty' <- coreView ty
374 = splitAppTy_maybe ty'
375 splitAppTy_maybe ty = repSplitAppTy_maybe ty
378 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
379 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
380 -- any Core view stuff is already done
381 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
382 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
383 repSplitAppTy_maybe (TyConApp tc tys)
384 | not (isOpenSynTyCon tc) || length tys > tyConArity tc
385 = case snocView tys of -- never create unsaturated type family apps
386 Just (tys', ty') -> Just (TyConApp tc tys', ty')
388 repSplitAppTy_maybe _other = Nothing
390 splitAppTy :: Type -> (Type, Type)
391 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
392 -- and panics if this is not possible
393 splitAppTy ty = case splitAppTy_maybe ty of
395 Nothing -> panic "splitAppTy"
398 splitAppTys :: Type -> (Type, [Type])
399 -- ^ Recursively splits a type as far as is possible, leaving a residual
400 -- type being applied to and the type arguments applied to it. Never fails,
401 -- even if that means returning an empty list of type applications.
402 splitAppTys ty = split ty ty []
404 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
405 split _ (AppTy ty arg) args = split ty ty (arg:args)
406 split _ (TyConApp tc tc_args) args
407 = let -- keep type families saturated
408 n | isOpenSynTyCon tc = tyConArity tc
410 (tc_args1, tc_args2) = splitAt n tc_args
412 (TyConApp tc tc_args1, tc_args2 ++ args)
413 split _ (FunTy ty1 ty2) args = ASSERT( null args )
414 (TyConApp funTyCon [], [ty1,ty2])
415 split orig_ty _ args = (orig_ty, args)
420 ---------------------------------------------------------------------
425 mkFunTy :: Type -> Type -> Type
426 -- ^ Creates a function type from the given argument and result type
427 mkFunTy (PredTy (EqPred ty1 ty2)) res = mkForAllTy (mkWildCoVar (PredTy (EqPred ty1 ty2))) res
428 mkFunTy arg res = FunTy arg res
430 mkFunTys :: [Type] -> Type -> Type
431 mkFunTys tys ty = foldr mkFunTy ty tys
433 isFunTy :: Type -> Bool
434 isFunTy ty = isJust (splitFunTy_maybe ty)
436 splitFunTy :: Type -> (Type, Type)
437 -- ^ Attempts to extract the argument and result types from a type, and
438 -- panics if that is not possible. See also 'splitFunTy_maybe'
439 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
440 splitFunTy (FunTy arg res) = (arg, res)
441 splitFunTy other = pprPanic "splitFunTy" (ppr other)
443 splitFunTy_maybe :: Type -> Maybe (Type, Type)
444 -- ^ Attempts to extract the argument and result types from a type
445 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
446 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
447 splitFunTy_maybe _ = Nothing
449 splitFunTys :: Type -> ([Type], Type)
450 splitFunTys ty = split [] ty ty
452 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
453 split args _ (FunTy arg res) = split (arg:args) res res
454 split args orig_ty _ = (reverse args, orig_ty)
456 splitFunTysN :: Int -> Type -> ([Type], Type)
457 -- ^ Split off exactly the given number argument types, and panics if that is not possible
458 splitFunTysN 0 ty = ([], ty)
459 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
460 case splitFunTysN (n-1) res of { (args, res) ->
463 -- | Splits off argument types from the given type and associating
464 -- them with the things in the input list from left to right. The
465 -- final result type is returned, along with the resulting pairs of
466 -- objects and types, albeit with the list of pairs in reverse order.
467 -- Panics if there are not enough argument types for the input list.
468 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
469 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
471 split acc [] nty _ = (reverse acc, nty)
473 | Just ty' <- coreView ty = split acc xs nty ty'
474 split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
475 split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
477 funResultTy :: Type -> Type
478 -- ^ Extract the function result type and panic if that is not possible
479 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
480 funResultTy (FunTy _arg res) = res
481 funResultTy ty = pprPanic "funResultTy" (ppr ty)
483 funArgTy :: Type -> Type
484 -- ^ Extract the function argument type and panic if that is not possible
485 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
486 funArgTy (FunTy arg _res) = arg
487 funArgTy ty = pprPanic "funArgTy" (ppr ty)
490 ---------------------------------------------------------------------
495 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
496 -- Applies its arguments to the constructor from left to right
497 mkTyConApp :: TyCon -> [Type] -> Type
499 | isFunTyCon tycon, [ty1,ty2] <- tys
505 -- | Create the plain type constructor type which has been applied to no type arguments at all.
506 mkTyConTy :: TyCon -> Type
507 mkTyConTy tycon = mkTyConApp tycon []
509 -- splitTyConApp "looks through" synonyms, because they don't
510 -- mean a distinct type, but all other type-constructor applications
511 -- including functions are returned as Just ..
513 -- | The same as @fst . splitTyConApp@
514 tyConAppTyCon :: Type -> TyCon
515 tyConAppTyCon ty = fst (splitTyConApp ty)
517 -- | The same as @snd . splitTyConApp@
518 tyConAppArgs :: Type -> [Type]
519 tyConAppArgs ty = snd (splitTyConApp ty)
521 -- | Attempts to tease a type apart into a type constructor and the application
522 -- of a number of arguments to that constructor. Panics if that is not possible.
523 -- See also 'splitTyConApp_maybe'
524 splitTyConApp :: Type -> (TyCon, [Type])
525 splitTyConApp ty = case splitTyConApp_maybe ty of
527 Nothing -> pprPanic "splitTyConApp" (ppr ty)
529 -- | Attempts to tease a type apart into a type constructor and the application
530 -- of a number of arguments to that constructor
531 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
532 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
533 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
534 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
535 splitTyConApp_maybe _ = Nothing
537 -- | Sometimes we do NOT want to look through a @newtype@. When case matching
538 -- on a newtype we want a convenient way to access the arguments of a @newtype@
539 -- constructor so as to properly form a coercion, and so we use 'splitNewTyConApp'
540 -- instead of 'splitTyConApp_maybe'
541 splitNewTyConApp :: Type -> (TyCon, [Type])
542 splitNewTyConApp ty = case splitNewTyConApp_maybe ty of
544 Nothing -> pprPanic "splitNewTyConApp" (ppr ty)
545 splitNewTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
546 splitNewTyConApp_maybe ty | Just ty' <- tcView ty = splitNewTyConApp_maybe ty'
547 splitNewTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
548 splitNewTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
549 splitNewTyConApp_maybe _ = Nothing
551 newTyConInstRhs :: TyCon -> [Type] -> Type
552 -- ^ Unwrap one 'layer' of newtype on a type constructor and it's arguments, using an
553 -- eta-reduced version of the @newtype@ if possible
554 newTyConInstRhs tycon tys
555 = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
556 mkAppTys (substTyWith tvs tys1 ty) tys2
558 (tvs, ty) = newTyConEtadRhs tycon
559 (tys1, tys2) = splitAtList tvs tys
563 ---------------------------------------------------------------------
567 Notes on type synonyms
568 ~~~~~~~~~~~~~~~~~~~~~~
569 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
570 to return type synonyms whereever possible. Thus
575 splitFunTys (a -> Foo a) = ([a], Foo a)
578 The reason is that we then get better (shorter) type signatures in
579 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
582 Note [Expanding newtypes]
583 ~~~~~~~~~~~~~~~~~~~~~~~~~
584 When expanding a type to expose a data-type constructor, we need to be
585 careful about newtypes, lest we fall into an infinite loop. Here are
588 newtype Id x = MkId x
589 newtype Fix f = MkFix (f (Fix f))
590 newtype T = MkT (T -> T)
593 --------------------------
595 Fix Maybe Maybe (Fix Maybe)
599 Notice that we can expand T, even though it's recursive.
600 And we can expand Id (Id Int), even though the Id shows up
601 twice at the outer level.
603 So, when expanding, we keep track of when we've seen a recursive
604 newtype at outermost level; and bale out if we see it again.
619 -- 4. Usage annotations
621 -- 5. All newtypes, including recursive ones, but not newtype families
623 -- It's useful in the back end of the compiler.
624 repType :: Type -> Type
625 -- Only applied to types of kind *; hence tycons are saturated
629 go :: [TyCon] -> Type -> Type
630 go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
633 go rec_nts (ForAllTy _ ty) -- Look through foralls
636 go rec_nts ty@(TyConApp tc tys) -- Expand newtypes
637 | Just _co_con <- newTyConCo_maybe tc -- See Note [Expanding newtypes]
638 = if tc `elem` rec_nts -- in Type.lhs
640 else go rec_nts' nt_rhs
642 nt_rhs = newTyConInstRhs tc tys
643 rec_nts' | isRecursiveTyCon tc = tc:rec_nts
644 | otherwise = rec_nts
649 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
650 -- of inspecting the type directly.
652 -- | Discovers the primitive representation of a more abstract 'Type'
653 typePrimRep :: Type -> PrimRep
654 typePrimRep ty = case repType ty of
655 TyConApp tc _ -> tyConPrimRep tc
657 AppTy _ _ -> PtrRep -- See note below
659 _ -> pprPanic "typePrimRep" (ppr ty)
660 -- Types of the form 'f a' must be of kind *, not *#, so
661 -- we are guaranteed that they are represented by pointers.
662 -- The reason is that f must have kind *->*, not *->*#, because
663 -- (we claim) there is no way to constrain f's kind any other
668 ---------------------------------------------------------------------
673 mkForAllTy :: TyVar -> Type -> Type
675 = mkForAllTys [tyvar] ty
677 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
678 mkForAllTys :: [TyVar] -> Type -> Type
679 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
681 isForAllTy :: Type -> Bool
682 isForAllTy (ForAllTy _ _) = True
685 -- | Attempts to take a forall type apart, returning the bound type variable
686 -- and the remainder of the type
687 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
688 splitForAllTy_maybe ty = splitFAT_m ty
690 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
691 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
692 splitFAT_m _ = Nothing
694 -- | Attempts to take a forall type apart, returning all the immediate such bound
695 -- type variables and the remainder of the type. Always suceeds, even if that means
696 -- returning an empty list of 'TyVar's
697 splitForAllTys :: Type -> ([TyVar], Type)
698 splitForAllTys ty = split ty ty []
700 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
701 split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
702 split orig_ty _ tvs = (reverse tvs, orig_ty)
704 -- | Equivalent to @snd . splitForAllTys@
705 dropForAlls :: Type -> Type
706 dropForAlls ty = snd (splitForAllTys ty)
709 -- (mkPiType now in CoreUtils)
715 -- | Instantiate a forall type with one or more type arguments.
716 -- Used when we have a polymorphic function applied to type args:
720 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
721 -- Panics if no application is possible.
722 applyTy :: Type -> Type -> Type
723 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
724 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
725 applyTy _ _ = panic "applyTy"
727 applyTys :: Type -> [Type] -> Type
728 -- ^ This function is interesting because:
730 -- 1. The function may have more for-alls than there are args
732 -- 2. Less obviously, it may have fewer for-alls
734 -- For case 2. think of:
736 -- > applyTys (forall a.a) [forall b.b, Int]
738 -- This really can happen, via dressing up polymorphic types with newtype
739 -- clothing. Here's an example:
741 -- > newtype R = R (forall a. a->a)
742 -- > foo = case undefined :: R of
745 applyTys ty args = applyTysD empty ty args
747 applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version
748 applyTysD _ orig_fun_ty [] = orig_fun_ty
749 applyTysD doc orig_fun_ty arg_tys
750 | n_tvs == n_args -- The vastly common case
751 = substTyWith tvs arg_tys rho_ty
752 | n_tvs > n_args -- Too many for-alls
753 = substTyWith (take n_args tvs) arg_tys
754 (mkForAllTys (drop n_args tvs) rho_ty)
755 | otherwise -- Too many type args
756 = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty ) -- Zero case gives infnite loop!
757 applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
760 (tvs, rho_ty) = splitForAllTys orig_fun_ty
762 n_args = length arg_tys
766 %************************************************************************
768 \subsection{Source types}
770 %************************************************************************
772 Source types are always lifted.
774 The key function is predTypeRep which gives the representation of a source type:
777 mkPredTy :: PredType -> Type
778 mkPredTy pred = PredTy pred
780 mkPredTys :: ThetaType -> [Type]
781 mkPredTys preds = map PredTy preds
783 predTypeRep :: PredType -> Type
784 -- ^ Convert a 'PredType' to its representation type. However, it unwraps
785 -- only the outermost level; for example, the result might be a newtype application
786 predTypeRep (IParam _ ty) = ty
787 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
788 -- Result might be a newtype application, but the consumer will
789 -- look through that too if necessary
790 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
792 mkFamilyTyConApp :: TyCon -> [Type] -> Type
793 -- ^ Given a family instance TyCon and its arg types, return the
794 -- corresponding family type. E.g:
797 -- > data instance T (Maybe b) = MkT b
799 -- Where the instance tycon is :RTL, so:
801 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
802 mkFamilyTyConApp tc tys
803 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
804 , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
805 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
809 -- | Pretty prints a 'TyCon', using the family instance in case of a
810 -- representation tycon. For example:
812 -- > data T [a] = ...
814 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
815 pprSourceTyCon :: TyCon -> SDoc
817 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
818 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
824 %************************************************************************
826 \subsection{Kinds and free variables}
828 %************************************************************************
830 ---------------------------------------------------------------------
831 Finding the kind of a type
832 ~~~~~~~~~~~~~~~~~~~~~~~~~~
834 typeKind :: Type -> Kind
835 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
836 -- We should be looking for the coercion kind,
838 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
839 typeKind (PredTy pred) = predKind pred
840 typeKind (AppTy fun _) = kindFunResult (typeKind fun)
841 typeKind (ForAllTy _ ty) = typeKind ty
842 typeKind (TyVarTy tyvar) = tyVarKind tyvar
843 typeKind (FunTy _arg res)
844 -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
845 -- not unliftedTypKind (#)
846 -- The only things that can be after a function arrow are
847 -- (a) types (of kind openTypeKind or its sub-kinds)
848 -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
849 | isTySuperKind k = k
850 | otherwise = ASSERT( isSubOpenTypeKind k) liftedTypeKind
854 predKind :: PredType -> Kind
855 predKind (EqPred {}) = coSuperKind -- A coercion kind!
856 predKind (ClassP {}) = liftedTypeKind -- Class and implicitPredicates are
857 predKind (IParam {}) = liftedTypeKind -- always represented by lifted types
861 ---------------------------------------------------------------------
862 Free variables of a type
863 ~~~~~~~~~~~~~~~~~~~~~~~~
865 tyVarsOfType :: Type -> TyVarSet
866 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
867 tyVarsOfType (TyVarTy tv) = unitVarSet tv
868 tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
869 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
870 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
871 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
872 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
874 tyVarsOfTypes :: [Type] -> TyVarSet
875 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
877 tyVarsOfPred :: PredType -> TyVarSet
878 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
879 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
880 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
882 tyVarsOfTheta :: ThetaType -> TyVarSet
883 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
887 %************************************************************************
889 \subsection{Type families}
891 %************************************************************************
894 -- | Finds type family instances occuring in a type after expanding synonyms.
895 tyFamInsts :: Type -> [(TyCon, [Type])]
897 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
898 tyFamInsts (TyVarTy _) = []
899 tyFamInsts (TyConApp tc tys)
900 | isOpenSynTyCon tc = [(tc, tys)]
901 | otherwise = concat (map tyFamInsts tys)
902 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
903 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
904 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty
908 %************************************************************************
910 \subsection{TidyType}
912 %************************************************************************
915 -- | This tidies up a type for printing in an error message, or in
916 -- an interface file.
918 -- It doesn't change the uniques at all, just the print names.
919 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
920 tidyTyVarBndr env@(tidy_env, subst) tyvar
921 = case tidyOccName tidy_env (getOccName name) of
922 (tidy', occ') -> ((tidy', subst'), tyvar'')
924 subst' = extendVarEnv subst tyvar tyvar''
925 tyvar' = setTyVarName tyvar name'
926 name' = tidyNameOcc name occ'
927 -- Don't forget to tidy the kind for coercions!
928 tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
930 kind' = tidyType env (tyVarKind tyvar)
932 name = tyVarName tyvar
934 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
935 -- ^ Add the free 'TyVar's to the env in tidy form,
936 -- so that we can tidy the type they are free in
937 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
939 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
940 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
942 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
943 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
944 -- using the environment if one has not already been allocated. See
945 -- also 'tidyTyVarBndr'
946 tidyOpenTyVar env@(_, subst) tyvar
947 = case lookupVarEnv subst tyvar of
948 Just tyvar' -> (env, tyvar') -- Already substituted
949 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
951 tidyType :: TidyEnv -> Type -> Type
952 tidyType env@(_, subst) ty
955 go (TyVarTy tv) = case lookupVarEnv subst tv of
956 Nothing -> TyVarTy tv
957 Just tv' -> TyVarTy tv'
958 go (TyConApp tycon tys) = let args = map go tys
959 in args `seqList` TyConApp tycon args
960 go (PredTy sty) = PredTy (tidyPred env sty)
961 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
962 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
963 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
965 (envp, tvp) = tidyTyVarBndr env tv
967 tidyTypes :: TidyEnv -> [Type] -> [Type]
968 tidyTypes env tys = map (tidyType env) tys
970 tidyPred :: TidyEnv -> PredType -> PredType
971 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
972 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
973 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
978 -- | Grabs the free type variables, tidies them
979 -- and then uses 'tidyType' to work over the type itself
980 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
982 = (env', tidyType env' ty)
984 env' = tidyFreeTyVars env (tyVarsOfType ty)
986 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
987 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
989 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
990 tidyTopType :: Type -> Type
991 tidyTopType ty = tidyType emptyTidyEnv ty
996 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
997 tidyKind env k = tidyOpenType env k
1002 %************************************************************************
1004 \subsection{Liftedness}
1006 %************************************************************************
1009 -- | See "Type#type_classification" for what an unlifted type is
1010 isUnLiftedType :: Type -> Bool
1011 -- isUnLiftedType returns True for forall'd unlifted types:
1012 -- x :: forall a. Int#
1013 -- I found bindings like these were getting floated to the top level.
1014 -- They are pretty bogus types, mind you. It would be better never to
1017 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
1018 isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
1019 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
1020 isUnLiftedType _ = False
1022 isUnboxedTupleType :: Type -> Bool
1023 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
1024 Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
1027 -- | See "Type#type_classification" for what an algebraic type is.
1028 -- Should only be applied to /types/, as opposed to e.g. partially
1029 -- saturated type constructors
1030 isAlgType :: Type -> Bool
1032 = case splitTyConApp_maybe ty of
1033 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1037 -- | See "Type#type_classification" for what an algebraic type is.
1038 -- Should only be applied to /types/, as opposed to e.g. partially
1039 -- saturated type constructors. Closed type constructors are those
1040 -- with a fixed right hand side, as opposed to e.g. associated types
1041 isClosedAlgType :: Type -> Bool
1043 = case splitTyConApp_maybe ty of
1044 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1045 isAlgTyCon tc && not (isOpenTyCon tc)
1050 -- | Computes whether an argument (or let right hand side) should
1051 -- be computed strictly or lazily, based only on its type.
1052 -- Works just like 'isUnLiftedType', except that it has a special case
1053 -- for dictionaries (i.e. does not work purely on representation types)
1055 -- Since it takes account of class 'PredType's, you might think
1056 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
1057 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
1058 isStrictType :: Type -> Bool
1059 isStrictType (PredTy pred) = isStrictPred pred
1060 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
1061 isStrictType (ForAllTy _ ty) = isStrictType ty
1062 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
1063 isStrictType _ = False
1065 -- | We may be strict in dictionary types, but only if it
1066 -- has more than one component.
1068 -- (Being strict in a single-component dictionary risks
1069 -- poking the dictionary component, which is wrong.)
1070 isStrictPred :: PredType -> Bool
1071 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
1072 isStrictPred _ = False
1076 isPrimitiveType :: Type -> Bool
1077 -- ^ Returns true of types that are opaque to Haskell.
1078 -- Most of these are unlifted, but now that we interact with .NET, we
1079 -- may have primtive (foreign-imported) types that are lifted
1080 isPrimitiveType ty = case splitTyConApp_maybe ty of
1081 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1087 %************************************************************************
1089 \subsection{Sequencing on types}
1091 %************************************************************************
1094 seqType :: Type -> ()
1095 seqType (TyVarTy tv) = tv `seq` ()
1096 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
1097 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
1098 seqType (PredTy p) = seqPred p
1099 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1100 seqType (ForAllTy tv ty) = tv `seq` seqType ty
1102 seqTypes :: [Type] -> ()
1104 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1106 seqPred :: PredType -> ()
1107 seqPred (ClassP c tys) = c `seq` seqTypes tys
1108 seqPred (IParam n ty) = n `seq` seqType ty
1109 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
1113 %************************************************************************
1115 Equality for Core types
1116 (We don't use instances so that we know where it happens)
1118 %************************************************************************
1120 Note that eqType works right even for partial applications of newtypes.
1121 See Note [Newtype eta] in TyCon.lhs
1124 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1125 coreEqType :: Type -> Type -> Bool
1129 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1131 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
1132 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1133 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
1134 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
1135 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1136 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1137 -- The lengths should be equal because
1138 -- the two types have the same kind
1139 -- NB: if the type constructors differ that does not
1140 -- necessarily mean that the types aren't equal
1141 -- (synonyms, newtypes)
1142 -- Even if the type constructors are the same, but the arguments
1143 -- differ, the two types could be the same (e.g. if the arg is just
1144 -- ignored in the RHS). In both these cases we fall through to an
1145 -- attempt to expand one side or the other.
1147 -- Now deal with newtypes, synonyms, pred-tys
1148 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
1149 | Just t2' <- coreView t2 = eq env t1 t2'
1151 -- Fall through case; not equal!
1156 %************************************************************************
1158 Comparision for source types
1159 (We don't use instances so that we know where it happens)
1161 %************************************************************************
1164 tcEqType :: Type -> Type -> Bool
1165 -- ^ Type equality on source types. Does not look through @newtypes@ or 'PredType's
1166 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1168 tcEqTypes :: [Type] -> [Type] -> Bool
1169 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1171 tcCmpType :: Type -> Type -> Ordering
1172 -- ^ Type ordering on source types. Does not look through @newtypes@ or 'PredType's
1173 tcCmpType t1 t2 = cmpType t1 t2
1175 tcCmpTypes :: [Type] -> [Type] -> Ordering
1176 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1178 tcEqPred :: PredType -> PredType -> Bool
1179 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1181 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1182 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1184 tcCmpPred :: PredType -> PredType -> Ordering
1185 tcCmpPred p1 p2 = cmpPred p1 p2
1187 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1188 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1192 -- | Checks whether the second argument is a subterm of the first. (We don't care
1193 -- about binders, as we are only interested in syntactic subterms.)
1194 tcPartOfType :: Type -> Type -> Bool
1196 | tcEqType t1 t2 = True
1198 | Just t2' <- tcView t2 = tcPartOfType t1 t2'
1199 tcPartOfType _ (TyVarTy _) = False
1200 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1201 tcPartOfType t1 (AppTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1202 tcPartOfType t1 (FunTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1203 tcPartOfType t1 (PredTy p2) = tcPartOfPred t1 p2
1204 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1206 tcPartOfPred :: Type -> PredType -> Bool
1207 tcPartOfPred t1 (IParam _ t2) = tcPartOfType t1 t2
1208 tcPartOfPred t1 (ClassP _ ts) = any (tcPartOfType t1) ts
1209 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1212 Now here comes the real worker
1215 cmpType :: Type -> Type -> Ordering
1216 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1218 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1220 cmpTypes :: [Type] -> [Type] -> Ordering
1221 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1223 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1225 cmpPred :: PredType -> PredType -> Ordering
1226 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1228 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1230 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
1231 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1232 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1234 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
1235 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1236 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1237 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1238 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
1239 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1241 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1242 cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT
1244 cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT
1245 cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT
1247 cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT
1248 cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT
1249 cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT
1251 cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT
1252 cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT
1253 cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT
1254 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1256 cmpTypeX _ (PredTy _) _ = GT
1261 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1262 cmpTypesX _ [] [] = EQ
1263 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1264 cmpTypesX _ [] _ = LT
1265 cmpTypesX _ _ [] = GT
1268 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1269 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1270 -- Compare names only for implicit parameters
1271 -- This comparison is used exclusively (I believe)
1272 -- for the Avails finite map built in TcSimplify
1273 -- If the types differ we keep them distinct so that we see
1274 -- a distinct pair to run improvement on
1275 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1276 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1278 -- Constructor order: IParam < ClassP < EqPred
1279 cmpPredX _ (IParam {}) _ = LT
1280 cmpPredX _ (ClassP {}) (IParam {}) = GT
1281 cmpPredX _ (ClassP {}) (EqPred {}) = LT
1282 cmpPredX _ (EqPred {}) _ = GT
1285 PredTypes are used as a FM key in TcSimplify,
1286 so we take the easy path and make them an instance of Ord
1289 instance Eq PredType where { (==) = tcEqPred }
1290 instance Ord PredType where { compare = tcCmpPred }
1294 %************************************************************************
1298 %************************************************************************
1301 -- | Type substitution
1303 -- #tvsubst_invariant#
1304 -- The following invariants must hold of a 'TvSubst':
1306 -- 1. The in-scope set is needed /only/ to
1307 -- guide the generation of fresh uniques
1309 -- 2. In particular, the /kind/ of the type variables in
1310 -- the in-scope set is not relevant
1312 -- 3. The substition is only applied ONCE! This is because
1313 -- in general such application will not reached a fixed point.
1315 = TvSubst InScopeSet -- The in-scope type variables
1316 TvSubstEnv -- The substitution itself
1317 -- See Note [Apply Once]
1318 -- and Note [Extending the TvSubstEnv]
1320 {- ----------------------------------------------------------
1324 We use TvSubsts to instantiate things, and we might instantiate
1328 So the substition might go [a->b, b->a]. A similar situation arises in Core
1329 when we find a beta redex like
1330 (/\ a /\ b -> e) b a
1331 Then we also end up with a substition that permutes type variables. Other
1332 variations happen to; for example [a -> (a, b)].
1334 ***************************************************
1335 *** So a TvSubst must be applied precisely once ***
1336 ***************************************************
1338 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1339 we use during unifications, it must not be repeatedly applied.
1341 Note [Extending the TvSubst]
1342 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1343 See #tvsubst_invariant# for the invariants that must hold.
1345 This invariant allows a short-cut when the TvSubstEnv is empty:
1346 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1347 then (substTy subst ty) does nothing.
1349 For example, consider:
1350 (/\a. /\b:(a~Int). ...b..) Int
1351 We substitute Int for 'a'. The Unique of 'b' does not change, but
1352 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1354 This invariant has several crucial consequences:
1356 * In substTyVarBndr, we need extend the TvSubstEnv
1357 - if the unique has changed
1358 - or if the kind has changed
1360 * In substTyVar, we do not need to consult the in-scope set;
1361 the TvSubstEnv is enough
1363 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1366 -------------------------------------------------------------- -}
1368 -- | A substitition of 'Type's for 'TyVar's
1369 type TvSubstEnv = TyVarEnv Type
1370 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1371 -- invariant discussed in Note [Apply Once]), and also independently
1372 -- in the middle of matching, and unification (see Types.Unify)
1373 -- So you have to look at the context to know if it's idempotent or
1374 -- apply-once or whatever
1376 emptyTvSubstEnv :: TvSubstEnv
1377 emptyTvSubstEnv = emptyVarEnv
1379 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1380 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1381 -- It assumes that both are idempotent.
1382 -- Typically, @env1@ is the refinement to a base substitution @env2@
1383 composeTvSubst in_scope env1 env2
1384 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1385 -- First apply env1 to the range of env2
1386 -- Then combine the two, making sure that env1 loses if
1387 -- both bind the same variable; that's why env1 is the
1388 -- *left* argument to plusVarEnv, because the right arg wins
1390 subst1 = TvSubst in_scope env1
1392 emptyTvSubst :: TvSubst
1393 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1395 isEmptyTvSubst :: TvSubst -> Bool
1396 -- See Note [Extending the TvSubstEnv]
1397 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1399 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1402 getTvSubstEnv :: TvSubst -> TvSubstEnv
1403 getTvSubstEnv (TvSubst _ env) = env
1405 getTvInScope :: TvSubst -> InScopeSet
1406 getTvInScope (TvSubst in_scope _) = in_scope
1408 isInScope :: Var -> TvSubst -> Bool
1409 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1411 notElemTvSubst :: TyVar -> TvSubst -> Bool
1412 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1414 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1415 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1417 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1418 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1420 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1421 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1423 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1424 extendTvSubstList (TvSubst in_scope env) tvs tys
1425 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1427 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1428 -- the types given; but it's just a thunk so with a bit of luck
1429 -- it'll never be evaluated
1431 -- Note [Generating the in-scope set for a substitution]
1432 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1433 -- If we want to substitute [a -> ty1, b -> ty2] I used to
1434 -- think it was enough to generate an in-scope set that includes
1435 -- fv(ty1,ty2). But that's not enough; we really should also take the
1436 -- free vars of the type we are substituting into! Example:
1437 -- (forall b. (a,b,x)) [a -> List b]
1438 -- Then if we use the in-scope set {b}, there is a danger we will rename
1439 -- the forall'd variable to 'x' by mistake, getting this:
1440 -- (forall x. (List b, x, x)
1441 -- Urk! This means looking at all the calls to mkOpenTvSubst....
1444 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1445 -- environment, hence "open"
1446 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1447 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1449 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1450 -- environment, hence "open"
1451 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1452 zipOpenTvSubst tyvars tys
1453 | debugIsOn && (length tyvars /= length tys)
1454 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1456 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1458 -- | Called when doing top-level substitutions. Here we expect that the
1459 -- free vars of the range of the substitution will be empty.
1460 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1461 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1463 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1464 zipTopTvSubst tyvars tys
1465 | debugIsOn && (length tyvars /= length tys)
1466 = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1468 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1470 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1472 | debugIsOn && (length tyvars /= length tys)
1473 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1475 = zip_ty_env tyvars tys emptyVarEnv
1477 -- Later substitutions in the list over-ride earlier ones,
1478 -- but there should be no loops
1479 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1480 zip_ty_env [] [] env = env
1481 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1482 -- There used to be a special case for when
1484 -- (a not-uncommon case) in which case the substitution was dropped.
1485 -- But the type-tidier changes the print-name of a type variable without
1486 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1487 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1488 -- And it happened that t was the type variable of the class. Post-tiding,
1489 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1490 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1491 -- and so generated a rep type mentioning t not t2.
1493 -- Simplest fix is to nuke the "optimisation"
1494 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1495 -- zip_ty_env _ _ env = env
1497 instance Outputable TvSubst where
1498 ppr (TvSubst ins env)
1499 = brackets $ sep[ ptext (sLit "TvSubst"),
1500 nest 2 (ptext (sLit "In scope:") <+> ppr ins),
1501 nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1504 %************************************************************************
1506 Performing type substitutions
1508 %************************************************************************
1511 -- | Type substitution making use of an 'TvSubst' that
1512 -- is assumed to be open, see 'zipOpenTvSubst'
1513 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1514 substTyWith tvs tys = ASSERT( length tvs == length tys )
1515 substTy (zipOpenTvSubst tvs tys)
1517 -- | Type substitution making use of an 'TvSubst' that
1518 -- is assumed to be open, see 'zipOpenTvSubst'
1519 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1520 substTysWith tvs tys = ASSERT( length tvs == length tys )
1521 substTys (zipOpenTvSubst tvs tys)
1523 -- | Substitute within a 'Type'
1524 substTy :: TvSubst -> Type -> Type
1525 substTy subst ty | isEmptyTvSubst subst = ty
1526 | otherwise = subst_ty subst ty
1528 -- | Substitute within several 'Type's
1529 substTys :: TvSubst -> [Type] -> [Type]
1530 substTys subst tys | isEmptyTvSubst subst = tys
1531 | otherwise = map (subst_ty subst) tys
1533 -- | Substitute within a 'ThetaType'
1534 substTheta :: TvSubst -> ThetaType -> ThetaType
1535 substTheta subst theta
1536 | isEmptyTvSubst subst = theta
1537 | otherwise = map (substPred subst) theta
1539 -- | Substitute within a 'PredType'
1540 substPred :: TvSubst -> PredType -> PredType
1541 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1542 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1543 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1545 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1546 deShadowTy :: TyVarSet -> Type -> Type
1548 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1550 in_scope = mkInScopeSet tvs
1552 subst_ty :: TvSubst -> Type -> Type
1553 -- subst_ty is the main workhorse for type substitution
1555 -- Note that the in_scope set is poked only if we hit a forall
1556 -- so it may often never be fully computed
1560 go (TyVarTy tv) = substTyVar subst tv
1561 go (TyConApp tc tys) = let args = map go tys
1562 in args `seqList` TyConApp tc args
1564 go (PredTy p) = PredTy $! (substPred subst p)
1566 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1567 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1568 -- The mkAppTy smart constructor is important
1569 -- we might be replacing (a Int), represented with App
1570 -- by [Int], represented with TyConApp
1571 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1573 ForAllTy tv' $! (subst_ty subst' ty)
1575 substTyVar :: TvSubst -> TyVar -> Type
1576 substTyVar subst@(TvSubst _ _) tv
1577 = case lookupTyVar subst tv of {
1578 Nothing -> TyVarTy tv;
1579 Just ty -> ty -- See Note [Apply Once]
1582 substTyVars :: TvSubst -> [TyVar] -> [Type]
1583 substTyVars subst tvs = map (substTyVar subst) tvs
1585 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1586 -- See Note [Extending the TvSubst]
1587 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1589 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1590 substTyVarBndr subst@(TvSubst in_scope env) old_var
1591 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1593 is_co_var = isCoVar old_var
1595 new_env | no_change = delVarEnv env old_var
1596 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1598 no_change = new_var == old_var && not is_co_var
1599 -- no_change means that the new_var is identical in
1600 -- all respects to the old_var (same unique, same kind)
1601 -- See Note [Extending the TvSubst]
1603 -- In that case we don't need to extend the substitution
1604 -- to map old to new. But instead we must zap any
1605 -- current substitution for the variable. For example:
1606 -- (\x.e) with id_subst = [x |-> e']
1607 -- Here we must simply zap the substitution for x
1609 new_var = uniqAway in_scope subst_old_var
1610 -- The uniqAway part makes sure the new variable is not already in scope
1612 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1613 -- It's only worth doing the substitution for coercions,
1614 -- becuase only they can have free type variables
1615 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1616 | otherwise = old_var
1619 ----------------------------------------------------
1628 -- There's a little subtyping at the kind level:
1638 -- Where: \* [LiftedTypeKind] means boxed type
1639 -- \# [UnliftedTypeKind] means unboxed type
1640 -- (\#) [UbxTupleKind] means unboxed tuple
1641 -- ?? [ArgTypeKind] is the lub of {\*, \#}
1642 -- ? [OpenTypeKind] means any type at all
1647 -- > error :: forall a:?. String -> a
1648 -- > (->) :: ?? -> ? -> \*
1649 -- > (\\(x::t) -> ...)
1651 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1653 type KindVar = TyVar -- invariant: KindVar will always be a
1654 -- TcTyVar with details MetaTv TauTv ...
1655 -- kind var constructors and functions are in TcType
1657 type SimpleKind = Kind
1662 During kind inference, a kind variable unifies only with
1664 sk ::= * | sk1 -> sk2
1666 data T a = MkT a (T Int#)
1667 fails. We give T the kind (k -> *), and the kind variable k won't unify
1668 with # (the kind of Int#).
1672 When creating a fresh internal type variable, we give it a kind to express
1673 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1676 During unification we only bind an internal type variable to a type
1677 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1679 When unifying two internal type variables, we collect their kind constraints by
1680 finding the GLB of the two. Since the partial order is a tree, they only
1681 have a glb if one is a sub-kind of the other. In that case, we bind the
1682 less-informative one to the more informative one. Neat, eh?
1689 %************************************************************************
1691 Functions over Kinds
1693 %************************************************************************
1696 -- | Essentially 'funResultTy' on kinds
1697 kindFunResult :: Kind -> Kind
1698 kindFunResult k = funResultTy k
1700 -- | Essentially 'splitFunTys' on kinds
1701 splitKindFunTys :: Kind -> ([Kind],Kind)
1702 splitKindFunTys k = splitFunTys k
1704 -- | Essentially 'splitFunTysN' on kinds
1705 splitKindFunTysN :: Int -> Kind -> ([Kind],Kind)
1706 splitKindFunTysN k = splitFunTysN k
1708 -- | See "Type#kind_subtyping" for details of the distinction between these 'Kind's
1709 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1710 isOpenTypeKindCon, isUbxTupleKindCon, isArgTypeKindCon,
1711 isUnliftedTypeKindCon, isSubArgTypeKindCon :: TyCon -> Bool
1713 isOpenTypeKindCon tc = tyConUnique tc == openTypeKindTyConKey
1715 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1716 isOpenTypeKind _ = False
1718 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1720 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1721 isUbxTupleKind _ = False
1723 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1725 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1726 isArgTypeKind _ = False
1728 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1730 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1731 isUnliftedTypeKind _ = False
1733 isSubOpenTypeKind :: Kind -> Bool
1734 -- ^ True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1735 isSubOpenTypeKind (FunTy k1 k2) = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) )
1736 ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) )
1738 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1739 isSubOpenTypeKind other = ASSERT( isKind other ) False
1740 -- This is a conservative answer
1741 -- It matters in the call to isSubKind in
1742 -- checkExpectedKind.
1744 isSubArgTypeKindCon kc
1745 | isUnliftedTypeKindCon kc = True
1746 | isLiftedTypeKindCon kc = True
1747 | isArgTypeKindCon kc = True
1750 isSubArgTypeKind :: Kind -> Bool
1751 -- ^ True of any sub-kind of ArgTypeKind
1752 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1753 isSubArgTypeKind _ = False
1755 -- | Is this a super-kind (i.e. a type-of-kinds)?
1756 isSuperKind :: Type -> Bool
1757 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1758 isSuperKind _ = False
1760 -- | Is this a kind (i.e. a type-of-types)?
1761 isKind :: Kind -> Bool
1762 isKind k = isSuperKind (typeKind k)
1764 isSubKind :: Kind -> Kind -> Bool
1765 -- ^ @k1 \`isSubKind\` k2@ checks that @k1@ <: @k2@
1766 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc2
1767 isSubKind (FunTy a1 r1) (FunTy a2 r2) = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1768 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2'))
1769 = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1770 isSubKind _ _ = False
1772 eqKind :: Kind -> Kind -> Bool
1775 isSubKindCon :: TyCon -> TyCon -> Bool
1776 -- ^ @kc1 \`isSubKindCon\` kc2@ checks that @kc1@ <: @kc2@
1777 isSubKindCon kc1 kc2
1778 | isLiftedTypeKindCon kc1 && isLiftedTypeKindCon kc2 = True
1779 | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1780 | isUbxTupleKindCon kc1 && isUbxTupleKindCon kc2 = True
1781 | isOpenTypeKindCon kc2 = True
1782 -- we already know kc1 is not a fun, its a TyCon
1783 | isArgTypeKindCon kc2 && isSubArgTypeKindCon kc1 = True
1786 defaultKind :: Kind -> Kind
1787 -- ^ Used when generalising: default kind ? and ?? to *. See "Type#kind_subtyping" for more
1788 -- information on what that means
1790 -- When we generalise, we make generic type variables whose kind is
1791 -- simple (* or *->* etc). So generic type variables (other than
1792 -- built-in constants like 'error') always have simple kinds. This is important;
1795 -- We want f to get type
1796 -- f :: forall (a::*). a -> Bool
1798 -- f :: forall (a::??). a -> Bool
1799 -- because that would allow a call like (f 3#) as well as (f True),
1800 --and the calling conventions differ. This defaulting is done in TcMType.zonkTcTyVarBndr.
1802 | isSubOpenTypeKind k = liftedTypeKind
1803 | isSubArgTypeKind k = liftedTypeKind
1806 isEqPred :: PredType -> Bool
1807 isEqPred (EqPred _ _) = True