2 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 \section[TypeRep]{Type - friends' interface}
9 Type(..), TyNote(..), -- Representation visible
10 PredType(..), -- to friends
12 Kind, ThetaType, -- Synonyms
17 pprType, pprParendType, pprTyThingCategory,
18 pprPred, pprTheta, pprThetaArrow, pprClassPred,
21 liftedTypeKind, unliftedTypeKind, openTypeKind,
22 argTypeKind, ubxTupleKind,
23 isLiftedTypeKindCon, isLiftedTypeKind,
24 mkArrowKind, mkArrowKinds,
26 -- Kind constructors...
27 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
28 argTypeKindTyCon, ubxTupleKindTyCon,
31 unliftedTypeKindTyConName, openTypeKindTyConName,
32 ubxTupleKindTyConName, argTypeKindTyConName,
33 liftedTypeKindTyConName,
36 tySuperKind, coSuperKind,
37 isTySuperKind, isCoSuperKind,
38 tySuperKindTyCon, coSuperKindTyCon,
42 pprKind, pprParendKind
45 #include "HsVersions.h"
47 import {-# SOURCE #-} DataCon( DataCon, dataConName )
48 import Monad ( guard )
51 import Var ( Var, Id, TyVar, tyVarKind )
52 import VarSet ( TyVarSet )
53 import Name ( Name, NamedThing(..), BuiltInSyntax(..), mkWiredInName )
54 import OccName ( mkOccNameFS, tcName, parenSymOcc )
55 import BasicTypes ( IPName, tupleParens )
56 import TyCon ( TyCon, mkFunTyCon, tyConArity, tupleTyConBoxity, isTupleTyCon, isRecursiveTyCon, isNewTyCon, mkVoidPrimTyCon, mkSuperKindTyCon, isSuperKindTyCon, mkCoercionTyCon )
57 import Class ( Class )
60 import PrelNames ( gHC_PRIM, funTyConKey, tySuperKindTyConKey,
61 coSuperKindTyConKey, liftedTypeKindTyConKey,
62 openTypeKindTyConKey, unliftedTypeKindTyConKey,
63 ubxTupleKindTyConKey, argTypeKindTyConKey, listTyConKey,
64 parrTyConKey, hasKey, eqCoercionKindTyConKey )
68 %************************************************************************
70 \subsection{Type Classifications}
72 %************************************************************************
76 *unboxed* iff its representation is other than a pointer
77 Unboxed types are also unlifted.
79 *lifted* A type is lifted iff it has bottom as an element.
80 Closures always have lifted types: i.e. any
81 let-bound identifier in Core must have a lifted
82 type. Operationally, a lifted object is one that
85 Only lifted types may be unified with a type variable.
87 *algebraic* A type with one or more constructors, whether declared
88 with "data" or "newtype".
89 An algebraic type is one that can be deconstructed
90 with a case expression.
91 *NOT* the same as lifted types, because we also
92 include unboxed tuples in this classification.
94 *data* A type declared with "data". Also boxed tuples.
96 *primitive* iff it is a built-in type that can't be expressed
99 Currently, all primitive types are unlifted, but that's not necessarily
100 the case. (E.g. Int could be primitive.)
102 Some primitive types are unboxed, such as Int#, whereas some are boxed
103 but unlifted (such as ByteArray#). The only primitive types that we
104 classify as algebraic are the unboxed tuples.
106 examples of type classifications:
108 Type primitive boxed lifted algebraic
109 -----------------------------------------------------------------------------
111 ByteArray# Yes Yes No No
112 (# a, b #) Yes No No Yes
113 ( a, b ) No Yes Yes Yes
118 ----------------------
119 A note about newtypes
120 ----------------------
125 Then we want N to be represented as an Int, and that's what we arrange.
126 The front end of the compiler [TcType.lhs] treats N as opaque,
127 the back end treats it as transparent [Type.lhs].
129 There's a bit of a problem with recursive newtypes
131 newtype Q = MkQ (Q->Q)
133 Here the 'implicit expansion' we get from treating P and Q as transparent
134 would give rise to infinite types, which in turn makes eqType diverge.
135 Similarly splitForAllTys and splitFunTys can get into a loop.
139 * Newtypes are always represented using TyConApp.
141 * For non-recursive newtypes, P, treat P just like a type synonym after
142 type-checking is done; i.e. it's opaque during type checking (functions
143 from TcType) but transparent afterwards (functions from Type).
144 "Treat P as a type synonym" means "all functions expand NewTcApps
147 Applications of the data constructor P simply vanish:
151 * For recursive newtypes Q, treat the Q and its representation as
152 distinct right through the compiler. Applications of the data consructor
154 Q = \(x::Q->Q). coerce Q x
155 They are rare, so who cares if they are a tiny bit less efficient.
157 The typechecker (TcTyDecls) identifies enough type construtors as 'recursive'
158 to cut all loops. The other members of the loop may be marked 'non-recursive'.
161 %************************************************************************
163 \subsection{The data type}
165 %************************************************************************
173 Type -- Function is *not* a TyConApp
174 Type -- It must be another AppTy, or TyVarTy
175 -- (or NoteTy of these)
177 | TyConApp -- Application of a TyCon, including newtypes *and* synonyms
178 TyCon -- *Invariant* saturated appliations of FunTyCon and
179 -- synonyms have their own constructors, below.
180 -- However, *unsaturated* FunTyCons do appear as TyConApps.
182 [Type] -- Might not be saturated.
183 -- Even type synonyms are not necessarily saturated;
184 -- for example unsaturated type synonyms can appear as the
185 -- RHS of a type synonym.
187 | FunTy -- Special case of TyConApp: TyConApp FunTyCon [t1,t2]
191 | ForAllTy -- A polymorphic type
195 | PredTy -- The type of evidence for a type predictate
196 PredType -- See Note [PredTy], and Note [Equality predicates]
197 -- NB: A PredTy (EqPred _ _) can appear only as the kind
198 -- of a coercion variable; never as the argument or result
199 -- of a FunTy (unlike ClassP, IParam)
201 | NoteTy -- A type with a note attached
203 Type -- The expanded version
205 type Kind = Type -- Invariant: a kind is always
207 -- or TyConApp PrimTyCon [...]
208 -- or TyVar kv (during inference only)
209 -- or ForAll ... (for top-level coercions)
211 type SuperKind = Type -- Invariant: a super kind is always
212 -- TyConApp SuperKindTyCon ...
216 type CoercionKind = Kind
218 data TyNote = FTVNote TyVarSet -- The free type variables of the noted expression
221 -------------------------------------
226 represents a value whose type is the Haskell predicate p,
227 where a predicate is what occurs before the '=>' in a Haskell type.
228 It can be expanded into its representation, but:
230 * The type checker must treat it as opaque
231 * The rest of the compiler treats it as transparent
233 Consider these examples:
234 f :: (Eq a) => a -> Int
235 g :: (?x :: Int -> Int) => a -> Int
236 h :: (r\l) => {r} => {l::Int | r}
238 Here the "Eq a" and "?x :: Int -> Int" and "r\l" are all called *predicates*
239 Predicates are represented inside GHC by PredType:
243 = ClassP Class [Type] -- Class predicate
244 | IParam (IPName Name) Type -- Implicit parameter
245 | EqPred Type Type -- Equality predicate (ty1 :=: ty2)
247 type ThetaType = [PredType]
250 (We don't support TREX records yet, but the setup is designed
251 to expand to allow them.)
253 A Haskell qualified type, such as that for f,g,h above, is
255 * a FunTy for the double arrow
256 * with a PredTy as the function argument
258 The predicate really does turn into a real extra argument to the
259 function. If the argument has type (PredTy p) then the predicate p is
260 represented by evidence (a dictionary, for example, of type (predRepTy p).
262 Note [Equality predicates]
263 ~~~~~~~~~~~~~~~~~~~~~~~~~~
264 forall a b. (a :=: S b) => a -> b
265 could be represented by
266 ForAllTy a (ForAllTy b (FunTy (PredTy (EqPred a (S b))) ...))
268 ForAllTy a (ForAllTy b (ForAllTy (c::PredTy (EqPred a (S b))) ...))
270 The latter is what we do. (Unlike for class and implicit parameter
271 constraints, which do use FunTy.)
274 * FunTy is always a *value* function
275 * ForAllTy is discarded at runtime
277 We often need to make a "wildcard" (c::PredTy..). We always use the same
278 name (wildCoVarName), since it's not mentioned.
281 %************************************************************************
285 %************************************************************************
287 Despite the fact that DataCon has to be imported via a hi-boot route,
288 this module seems the right place for TyThing, because it's needed for
289 funTyCon and all the types in TysPrim.
292 data TyThing = AnId Id
297 instance Outputable TyThing where
298 ppr thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
300 pprTyThingCategory :: TyThing -> SDoc
301 pprTyThingCategory (ATyCon _) = ptext SLIT("Type constructor")
302 pprTyThingCategory (AClass _) = ptext SLIT("Class")
303 pprTyThingCategory (AnId _) = ptext SLIT("Identifier")
304 pprTyThingCategory (ADataCon _) = ptext SLIT("Data constructor")
306 instance NamedThing TyThing where -- Can't put this with the type
307 getName (AnId id) = getName id -- decl, because the DataCon instance
308 getName (ATyCon tc) = getName tc -- isn't visible there
309 getName (AClass cl) = getName cl
310 getName (ADataCon dc) = dataConName dc
314 %************************************************************************
316 Wired-in type constructors
318 %************************************************************************
320 We define a few wired-in type constructors here to avoid module knots
323 --------------------------
324 -- First the TyCons...
326 funTyCon = mkFunTyCon funTyConName (mkArrowKinds [argTypeKind, openTypeKind] liftedTypeKind)
327 -- You might think that (->) should have type (?? -> ? -> *), and you'd be right
328 -- But if we do that we get kind errors when saying
329 -- instance Control.Arrow (->)
330 -- becuase the expected kind is (*->*->*). The trouble is that the
331 -- expected/actual stuff in the unifier does not go contra-variant, whereas
332 -- the kind sub-typing does. Sigh. It really only matters if you use (->) in
333 -- a prefix way, thus: (->) Int# Int#. And this is unusual.
336 tySuperKindTyCon = mkSuperKindTyCon tySuperKindTyConName
337 coSuperKindTyCon = mkSuperKindTyCon coSuperKindTyConName
339 liftedTypeKindTyCon = mkKindTyCon liftedTypeKindTyConName
340 openTypeKindTyCon = mkKindTyCon openTypeKindTyConName
341 unliftedTypeKindTyCon = mkKindTyCon unliftedTypeKindTyConName
342 ubxTupleKindTyCon = mkKindTyCon ubxTupleKindTyConName
343 argTypeKindTyCon = mkKindTyCon argTypeKindTyConName
344 eqCoercionKindTyCon =
345 mkCoercionTyCon eqCoercionKindTyConName 2 (\ _ -> coSuperKind)
347 mkKindTyCon :: Name -> TyCon
348 mkKindTyCon name = mkVoidPrimTyCon name tySuperKind 0
350 --------------------------
351 -- ... and now their names
353 tySuperKindTyConName = mkPrimTyConName FSLIT("BOX") tySuperKindTyConKey tySuperKindTyCon
354 coSuperKindTyConName = mkPrimTyConName FSLIT("COERCION") coSuperKindTyConKey coSuperKindTyCon
355 liftedTypeKindTyConName = mkPrimTyConName FSLIT("*") liftedTypeKindTyConKey liftedTypeKindTyCon
356 openTypeKindTyConName = mkPrimTyConName FSLIT("?") openTypeKindTyConKey openTypeKindTyCon
357 unliftedTypeKindTyConName = mkPrimTyConName FSLIT("#") unliftedTypeKindTyConKey unliftedTypeKindTyCon
358 ubxTupleKindTyConName = mkPrimTyConName FSLIT("(##)") ubxTupleKindTyConKey ubxTupleKindTyCon
359 argTypeKindTyConName = mkPrimTyConName FSLIT("??") argTypeKindTyConKey argTypeKindTyCon
360 funTyConName = mkPrimTyConName FSLIT("(->)") funTyConKey funTyCon
362 eqCoercionKindTyConName = mkWiredInName gHC_PRIM (mkOccNameFS tcName (FSLIT(":=:")))
363 eqCoercionKindTyConKey Nothing (ATyCon eqCoercionKindTyCon)
366 mkPrimTyConName occ key tycon = mkWiredInName gHC_PRIM (mkOccNameFS tcName occ)
368 Nothing -- No parent object
371 -- All of the super kinds and kinds are defined in Prim and use BuiltInSyntax,
372 -- because they are never in scope in the source
375 -- We also need Kinds and SuperKinds, locally and in TyCon
377 kindTyConType :: TyCon -> Type
378 kindTyConType kind = TyConApp kind []
380 liftedTypeKind = kindTyConType liftedTypeKindTyCon
381 unliftedTypeKind = kindTyConType unliftedTypeKindTyCon
382 openTypeKind = kindTyConType openTypeKindTyCon
383 argTypeKind = kindTyConType argTypeKindTyCon
384 ubxTupleKind = kindTyConType ubxTupleKindTyCon
386 mkArrowKind :: Kind -> Kind -> Kind
387 mkArrowKind k1 k2 = FunTy k1 k2
389 mkArrowKinds :: [Kind] -> Kind -> Kind
390 mkArrowKinds arg_kinds result_kind = foldr mkArrowKind result_kind arg_kinds
392 tySuperKind, coSuperKind :: SuperKind
393 tySuperKind = kindTyConType tySuperKindTyCon
394 coSuperKind = kindTyConType coSuperKindTyCon
396 isTySuperKind (NoteTy _ ty) = isTySuperKind ty
397 isTySuperKind (TyConApp kc []) = kc `hasKey` tySuperKindTyConKey
398 isTySuperKind other = False
400 isCoSuperKind :: SuperKind -> Bool
401 isCoSuperKind (NoteTy _ ty) = isCoSuperKind ty
402 isCoSuperKind (TyConApp kc []) = kc `hasKey` coSuperKindTyConKey
403 isCoSuperKind other = False
405 isCoercionKindTyCon kc = kc `hasKey` eqCoercionKindTyConKey
409 -- lastly we need a few functions on Kinds
411 isLiftedTypeKindCon tc = tc `hasKey` liftedTypeKindTyConKey
413 isLiftedTypeKind (TyConApp tc []) = isLiftedTypeKindCon tc
414 isLiftedTypeKind other = False
421 %************************************************************************
423 \subsection{The external interface}
425 %************************************************************************
427 @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
428 defined to use this. @pprParendType@ is the same, except it puts
429 parens around the type, except for the atomic cases. @pprParendType@
430 works just by setting the initial context precedence very high.
433 data Prec = TopPrec -- No parens
434 | FunPrec -- Function args; no parens for tycon apps
435 | TyConPrec -- Tycon args; no parens for atomic
438 maybeParen :: Prec -> Prec -> SDoc -> SDoc
439 maybeParen ctxt_prec inner_prec pretty
440 | ctxt_prec < inner_prec = pretty
441 | otherwise = parens pretty
444 pprType, pprParendType :: Type -> SDoc
445 pprType ty = ppr_type TopPrec ty
446 pprParendType ty = ppr_type TyConPrec ty
449 pprPred :: PredType -> SDoc
450 pprPred (ClassP cls tys) = pprClassPred cls tys
451 pprPred (IParam ip ty) = ppr ip <> dcolon <> pprType ty
452 pprPred (EqPred ty1 ty2) = sep [ppr ty1, nest 2 (ptext SLIT(":=:")), ppr ty2]
454 pprClassPred :: Class -> [Type] -> SDoc
455 pprClassPred clas tys = parenSymOcc (getOccName clas) (ppr clas)
456 <+> sep (map pprParendType tys)
458 pprTheta :: ThetaType -> SDoc
459 pprTheta theta = parens (sep (punctuate comma (map pprPred theta)))
461 pprThetaArrow :: ThetaType -> SDoc
464 | otherwise = parens (sep (punctuate comma (map pprPred theta))) <+> ptext SLIT("=>")
467 instance Outputable Type where
470 instance Outputable PredType where
473 instance Outputable name => OutputableBndr (IPName name) where
474 pprBndr _ n = ppr n -- Simple for now
477 -- OK, here's the main printer
480 pprParendKind = pprParendType
482 ppr_type :: Prec -> Type -> SDoc
483 ppr_type p (TyVarTy tv) = ppr tv
484 ppr_type p (PredTy pred) = braces (ppr pred)
485 ppr_type p (NoteTy other ty2) = ppr_type p ty2
486 ppr_type p (TyConApp tc tys) = ppr_tc_app p tc tys
488 ppr_type p (AppTy t1 t2) = maybeParen p TyConPrec $
489 pprType t1 <+> ppr_type TyConPrec t2
491 ppr_type p ty@(ForAllTy _ _) = ppr_forall_type p ty
492 ppr_type p ty@(FunTy (PredTy _) _) = ppr_forall_type p ty
494 ppr_type p (FunTy ty1 ty2)
495 = -- We don't want to lose synonyms, so we mustn't use splitFunTys here.
496 maybeParen p FunPrec $
497 sep (ppr_type FunPrec ty1 : ppr_fun_tail ty2)
499 ppr_fun_tail (FunTy ty1 ty2) = (arrow <+> ppr_type FunPrec ty1) : ppr_fun_tail ty2
500 ppr_fun_tail other_ty = [arrow <+> pprType other_ty]
502 ppr_forall_type :: Prec -> Type -> SDoc
504 = maybeParen p FunPrec $
505 sep [pprForAll tvs, pprThetaArrow ctxt, pprType tau]
507 (tvs, rho) = split1 [] ty
508 (ctxt, tau) = split2 [] rho
510 split1 tvs (ForAllTy tv ty) = split1 (tv:tvs) ty
511 split1 tvs (NoteTy _ ty) = split1 tvs ty
512 split1 tvs ty = (reverse tvs, ty)
514 split2 ps (NoteTy _ arg -- Rather a disgusting case
515 `FunTy` res) = split2 ps (arg `FunTy` res)
516 split2 ps (PredTy p `FunTy` ty) = split2 (p:ps) ty
517 split2 ps (NoteTy _ ty) = split2 ps ty
518 split2 ps ty = (reverse ps, ty)
520 ppr_tc_app :: Prec -> TyCon -> [Type] -> SDoc
524 | tc `hasKey` listTyConKey = brackets (pprType ty)
525 | tc `hasKey` parrTyConKey = ptext SLIT("[:") <> pprType ty <> ptext SLIT(":]")
526 | tc `hasKey` liftedTypeKindTyConKey = ptext SLIT("*")
527 | tc `hasKey` unliftedTypeKindTyConKey = ptext SLIT("#")
528 | tc `hasKey` openTypeKindTyConKey = ptext SLIT("(?)")
529 | tc `hasKey` ubxTupleKindTyConKey = ptext SLIT("(#)")
530 | tc `hasKey` argTypeKindTyConKey = ptext SLIT("??")
533 | isTupleTyCon tc && tyConArity tc == length tys
534 = tupleParens (tupleTyConBoxity tc) (sep (punctuate comma (map pprType tys)))
536 = maybeParen p TyConPrec $
537 ppr_tc tc <+> sep (map (ppr_type TyConPrec) tys)
539 ppr_tc :: TyCon -> SDoc
540 ppr_tc tc = parenSymOcc (getOccName tc) (pp_nt_debug <> ppr tc)
542 pp_nt_debug | isNewTyCon tc = ifPprDebug (if isRecursiveTyCon tc
543 then ptext SLIT("<recnt>")
544 else ptext SLIT("<nt>"))
549 pprForAll tvs = ptext SLIT("forall") <+> sep (map pprTvBndr tvs) <> dot
551 pprTvBndr tv | isLiftedTypeKind kind = ppr tv
552 | otherwise = parens (ppr tv <+> dcolon <+> pprKind kind)