2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
5 \section[TypeRep]{Type - friends' interface}
8 -- We expose the relevant stuff from this module via the Type module
9 {-# OPTIONS_HADDOCK hide #-}
10 {-# LANGUAGE DeriveDataTypeable #-}
15 PredType(..), -- to friends
17 Kind, ThetaType, -- Synonyms
19 funTyCon, funTyConName,
22 pprType, pprParendType, pprTypeApp,
23 pprTyThing, pprTyThingCategory,
24 pprPred, pprEqPred, pprTheta, pprForAll, pprThetaArrow, pprClassPred,
27 liftedTypeKind, unliftedTypeKind, openTypeKind,
28 argTypeKind, ubxTupleKind, ecKind,
29 isLiftedTypeKindCon, isLiftedTypeKind,
30 mkArrowKind, mkArrowKinds, isCoercionKind,
33 -- Kind constructors...
34 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
35 argTypeKindTyCon, ubxTupleKindTyCon,
38 unliftedTypeKindTyConName, openTypeKindTyConName,
39 ubxTupleKindTyConName, argTypeKindTyConName,
40 liftedTypeKindTyConName,
43 tySuperKind, coSuperKind,
44 isTySuperKind, isCoSuperKind,
45 tySuperKindTyCon, coSuperKindTyCon,
47 pprKind, pprParendKind
50 #include "HsVersions.h"
52 import {-# SOURCE #-} DataCon( DataCon, dataConName )
67 import Data.Data hiding ( TyCon )
70 ----------------------
72 ----------------------
77 Then we want N to be represented as an Int, and that's what we arrange.
78 The front end of the compiler [TcType.lhs] treats N as opaque,
79 the back end treats it as transparent [Type.lhs].
81 There's a bit of a problem with recursive newtypes
83 newtype Q = MkQ (Q->Q)
85 Here the 'implicit expansion' we get from treating P and Q as transparent
86 would give rise to infinite types, which in turn makes eqType diverge.
87 Similarly splitForAllTys and splitFunTys can get into a loop.
91 * Newtypes are always represented using TyConApp.
93 * For non-recursive newtypes, P, treat P just like a type synonym after
94 type-checking is done; i.e. it's opaque during type checking (functions
95 from TcType) but transparent afterwards (functions from Type).
96 "Treat P as a type synonym" means "all functions expand NewTcApps
99 Applications of the data constructor P simply vanish:
103 * For recursive newtypes Q, treat the Q and its representation as
104 distinct right through the compiler. Applications of the data consructor
106 Q = \(x::Q->Q). coerce Q x
107 They are rare, so who cares if they are a tiny bit less efficient.
109 The typechecker (TcTyDecls) identifies enough type construtors as 'recursive'
110 to cut all loops. The other members of the loop may be marked 'non-recursive'.
113 %************************************************************************
115 \subsection{The data type}
117 %************************************************************************
121 -- | The key representation of types within the compiler
123 = TyVarTy TyVar -- ^ Vanilla type variable
127 Type -- ^ Type application to something other than a 'TyCon'. Parameters:
129 -- 1) Function: must /not/ be a 'TyConApp', must be another 'AppTy', or 'TyVarTy'
135 [Type] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
136 -- Invariant: saturated appliations of 'FunTyCon' must
137 -- use 'FunTy' and saturated synonyms must use their own
138 -- constructors. However, /unsaturated/ 'FunTyCon's do appear as 'TyConApp's.
141 -- 1) Type constructor being applied to.
143 -- 2) Type arguments. Might not have enough type arguments here to saturate the constructor.
144 -- Even type synonyms are not necessarily saturated; for example unsaturated type synonyms
145 -- can appear as the right hand side of a type synonym.
149 Type -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@
153 Type -- ^ A polymorphic type
156 PredType -- ^ The type of evidence for a type predictate.
157 -- Note that a @PredTy (EqPred _ _)@ can appear only as the kind
158 -- of a coercion variable; never as the argument or result
159 -- of a 'FunTy' (unlike the 'PredType' constructors 'ClassP' or 'IParam')
161 -- See Note [PredTy], and Note [Equality predicates]
162 deriving (Data, Typeable)
164 -- | The key type representing kinds in the compiler.
165 -- Invariant: a kind is always in one of these forms:
168 -- > TyConApp PrimTyCon [...]
169 -- > TyVar kv -- (during inference only)
170 -- > ForAll ... -- (for top-level coercions)
173 -- | "Super kinds", used to help encode 'Kind's as types.
174 -- Invariant: a super kind is always of this form:
176 -- > TyConApp SuperKindTyCon ...
177 type SuperKind = Type
180 -------------------------------------
184 -- | A type of the form @PredTy p@ represents a value whose type is
185 -- the Haskell predicate @p@, where a predicate is what occurs before
186 -- the @=>@ in a Haskell type.
187 -- It can be expanded into its representation, but:
189 -- * The type checker must treat it as opaque
191 -- * The rest of the compiler treats it as transparent
193 -- Consider these examples:
195 -- > f :: (Eq a) => a -> Int
196 -- > g :: (?x :: Int -> Int) => a -> Int
197 -- > h :: (r\l) => {r} => {l::Int | r}
199 -- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
201 = ClassP Class [Type] -- ^ Class predicate e.g. @Eq a@
202 | IParam (IPName Name) Type -- ^ Implicit parameter e.g. @?x :: Int@
203 | EqPred Type Type -- ^ Equality predicate e.g @ty1 ~ ty2@
204 deriving (Data, Typeable)
206 -- | A collection of 'PredType's
207 type ThetaType = [PredType]
210 (We don't support TREX records yet, but the setup is designed
211 to expand to allow them.)
213 A Haskell qualified type, such as that for f,g,h above, is
215 * a FunTy for the double arrow
216 * with a PredTy as the function argument
218 The predicate really does turn into a real extra argument to the
219 function. If the argument has type (PredTy p) then the predicate p is
220 represented by evidence (a dictionary, for example, of type (predRepTy p).
222 Note [Equality predicates]
223 ~~~~~~~~~~~~~~~~~~~~~~~~~~
224 forall a b. (a ~ S b) => a -> b
225 could be represented by
226 ForAllTy a (ForAllTy b (FunTy (PredTy (EqPred a (S b))) ...))
228 ForAllTy a (ForAllTy b (ForAllTy (c::PredTy (EqPred a (S b))) ...))
230 The latter is what we do. (Unlike for class and implicit parameter
231 constraints, which do use FunTy.)
234 * FunTy is always a *value* function
235 * ForAllTy is discarded at runtime
237 We often need to make a "wildcard" (c::PredTy..). We always use the same
238 name (wildCoVarName), since it's not mentioned.
241 %************************************************************************
245 %************************************************************************
247 Despite the fact that DataCon has to be imported via a hi-boot route,
248 this module seems the right place for TyThing, because it's needed for
249 funTyCon and all the types in TysPrim.
252 -- | A typecheckable-thing, essentially anything that has a name
253 data TyThing = AnId Id
258 instance Outputable TyThing where
261 pprTyThing :: TyThing -> SDoc
262 pprTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
264 pprTyThingCategory :: TyThing -> SDoc
265 pprTyThingCategory (ATyCon _) = ptext (sLit "Type constructor")
266 pprTyThingCategory (AClass _) = ptext (sLit "Class")
267 pprTyThingCategory (AnId _) = ptext (sLit "Identifier")
268 pprTyThingCategory (ADataCon _) = ptext (sLit "Data constructor")
270 instance NamedThing TyThing where -- Can't put this with the type
271 getName (AnId id) = getName id -- decl, because the DataCon instance
272 getName (ATyCon tc) = getName tc -- isn't visible there
273 getName (AClass cl) = getName cl
274 getName (ADataCon dc) = dataConName dc
278 %************************************************************************
280 Wired-in type constructors
282 %************************************************************************
284 We define a few wired-in type constructors here to avoid module knots
287 --------------------------
288 -- First the TyCons...
290 -- | See "Type#kind_subtyping" for details of the distinction between the 'Kind' 'TyCon's
291 funTyCon, tySuperKindTyCon, coSuperKindTyCon, liftedTypeKindTyCon,
292 openTypeKindTyCon, unliftedTypeKindTyCon,
293 ubxTupleKindTyCon, argTypeKindTyCon
295 funTyConName, tySuperKindTyConName, coSuperKindTyConName, liftedTypeKindTyConName,
296 openTypeKindTyConName, unliftedTypeKindTyConName,
297 ubxTupleKindTyConName, argTypeKindTyConName
300 funTyCon = mkFunTyCon funTyConName (mkArrowKinds [argTypeKind, openTypeKind] liftedTypeKind)
301 -- You might think that (->) should have type (?? -> ? -> *), and you'd be right
302 -- But if we do that we get kind errors when saying
303 -- instance Control.Arrow (->)
304 -- becuase the expected kind is (*->*->*). The trouble is that the
305 -- expected/actual stuff in the unifier does not go contra-variant, whereas
306 -- the kind sub-typing does. Sigh. It really only matters if you use (->) in
307 -- a prefix way, thus: (->) Int# Int#. And this is unusual.
310 tySuperKindTyCon = mkSuperKindTyCon tySuperKindTyConName
311 coSuperKindTyCon = mkSuperKindTyCon coSuperKindTyConName
313 liftedTypeKindTyCon = mkKindTyCon liftedTypeKindTyConName tySuperKind
314 openTypeKindTyCon = mkKindTyCon openTypeKindTyConName tySuperKind
315 unliftedTypeKindTyCon = mkKindTyCon unliftedTypeKindTyConName tySuperKind
316 ubxTupleKindTyCon = mkKindTyCon ubxTupleKindTyConName tySuperKind
317 argTypeKindTyCon = mkKindTyCon argTypeKindTyConName tySuperKind
319 --------------------------
320 -- ... and now their names
322 tySuperKindTyConName = mkPrimTyConName (fsLit "BOX") tySuperKindTyConKey tySuperKindTyCon
323 coSuperKindTyConName = mkPrimTyConName (fsLit "COERCION") coSuperKindTyConKey coSuperKindTyCon
324 liftedTypeKindTyConName = mkPrimTyConName (fsLit "*") liftedTypeKindTyConKey liftedTypeKindTyCon
325 openTypeKindTyConName = mkPrimTyConName (fsLit "?") openTypeKindTyConKey openTypeKindTyCon
326 unliftedTypeKindTyConName = mkPrimTyConName (fsLit "#") unliftedTypeKindTyConKey unliftedTypeKindTyCon
327 ubxTupleKindTyConName = mkPrimTyConName (fsLit "(#)") ubxTupleKindTyConKey ubxTupleKindTyCon
328 argTypeKindTyConName = mkPrimTyConName (fsLit "??") argTypeKindTyConKey argTypeKindTyCon
329 funTyConName = mkPrimTyConName (fsLit "(->)") funTyConKey funTyCon
331 mkPrimTyConName :: FastString -> Unique -> TyCon -> Name
332 mkPrimTyConName occ key tycon = mkWiredInName gHC_PRIM (mkTcOccFS occ)
336 -- All of the super kinds and kinds are defined in Prim and use BuiltInSyntax,
337 -- because they are never in scope in the source
340 -- We also need Kinds and SuperKinds, locally and in TyCon
342 kindTyConType :: TyCon -> Type
343 kindTyConType kind = TyConApp kind []
345 -- | See "Type#kind_subtyping" for details of the distinction between these 'Kind's
346 liftedTypeKind, unliftedTypeKind, openTypeKind, argTypeKind, ubxTupleKind, ecKind :: Kind
348 liftedTypeKind = kindTyConType liftedTypeKindTyCon
349 unliftedTypeKind = kindTyConType unliftedTypeKindTyCon
350 openTypeKind = kindTyConType openTypeKindTyCon
351 argTypeKind = kindTyConType argTypeKindTyCon
352 ubxTupleKind = kindTyConType ubxTupleKindTyCon
353 ecKind = liftedTypeKind `mkArrowKind` (liftedTypeKind `mkArrowKind` liftedTypeKind)
354 -- NOTE: if you change ecKind, you must also change the explicit kind signatures
355 -- on hetmet_{brak,esc,csp} in GHC.Hetmet.CodeTypes
357 -- | Given two kinds @k1@ and @k2@, creates the 'Kind' @k1 -> k2@
358 mkArrowKind :: Kind -> Kind -> Kind
359 mkArrowKind k1 k2 = FunTy k1 k2
361 -- | Iterated application of 'mkArrowKind'
362 mkArrowKinds :: [Kind] -> Kind -> Kind
363 mkArrowKinds arg_kinds result_kind = foldr mkArrowKind result_kind arg_kinds
365 tySuperKind, coSuperKind :: SuperKind
366 tySuperKind = kindTyConType tySuperKindTyCon
367 coSuperKind = kindTyConType coSuperKindTyCon
369 isTySuperKind :: SuperKind -> Bool
370 isTySuperKind (TyConApp kc []) = kc `hasKey` tySuperKindTyConKey
371 isTySuperKind _ = False
373 isCoSuperKind :: SuperKind -> Bool
374 isCoSuperKind (TyConApp kc []) = kc `hasKey` coSuperKindTyConKey
375 isCoSuperKind _ = False
378 -- Lastly we need a few functions on Kinds
380 isLiftedTypeKindCon :: TyCon -> Bool
381 isLiftedTypeKindCon tc = tc `hasKey` liftedTypeKindTyConKey
383 isLiftedTypeKind :: Kind -> Bool
384 isLiftedTypeKind (TyConApp tc []) = isLiftedTypeKindCon tc
385 isLiftedTypeKind _ = False
387 isCoercionKind :: Kind -> Bool
388 -- All coercions are of form (ty1 ~ ty2)
389 -- This function is here rather than in Coercion,
390 -- because it's used in a knot-tied way to enforce invariants in Var
391 isCoercionKind (PredTy (EqPred {})) = True
392 isCoercionKind _ = False
394 coVarPred :: CoVar -> PredType
396 = ASSERT( isCoVar tv )
399 other -> pprPanic "coVarPred" (ppr tv $$ ppr other)
404 %************************************************************************
406 \subsection{The external interface}
408 %************************************************************************
410 @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
411 defined to use this. @pprParendType@ is the same, except it puts
412 parens around the type, except for the atomic cases. @pprParendType@
413 works just by setting the initial context precedence very high.
416 data Prec = TopPrec -- No parens
417 | FunPrec -- Function args; no parens for tycon apps
418 | TyConPrec -- Tycon args; no parens for atomic
421 maybeParen :: Prec -> Prec -> SDoc -> SDoc
422 maybeParen ctxt_prec inner_prec pretty
423 | ctxt_prec < inner_prec = pretty
424 | otherwise = parens pretty
427 pprType, pprParendType :: Type -> SDoc
428 pprType ty = ppr_type TopPrec ty
429 pprParendType ty = ppr_type TyConPrec ty
431 pprTypeApp :: NamedThing a => a -> [Type] -> SDoc
432 -- The first arg is the tycon, or sometimes class
433 -- Print infix if the tycon/class looks like an operator
434 pprTypeApp tc tys = ppr_type_app TopPrec (getName tc) tys
437 pprPred :: PredType -> SDoc
438 pprPred (ClassP cls tys) = pprClassPred cls tys
439 pprPred (IParam ip ty) = ppr ip <> dcolon <> pprType ty
440 pprPred (EqPred ty1 ty2) = pprEqPred (ty1,ty2)
442 pprEqPred :: (Type,Type) -> SDoc
443 pprEqPred (ty1,ty2) = sep [ ppr_type FunPrec ty1
444 , nest 2 (ptext (sLit "~"))
445 , ppr_type FunPrec ty2]
446 -- Precedence looks like (->) so that we get
449 -- Note parens on the latter!
451 pprClassPred :: Class -> [Type] -> SDoc
452 pprClassPred clas tys = ppr_type_app TopPrec (getName clas) tys
454 pprTheta :: ThetaType -> SDoc
455 -- pprTheta [pred] = pprPred pred -- I'm in two minds about this
456 pprTheta theta = parens (sep (punctuate comma (map pprPred theta)))
458 pprThetaArrow :: ThetaType -> SDoc
459 pprThetaArrow [] = empty
461 | noParenPred pred = pprPred pred <+> darrow
462 pprThetaArrow preds = parens (sep (punctuate comma (map pprPred preds))) <+> darrow
464 noParenPred :: PredType -> Bool
465 -- A predicate that can appear without parens before a "=>"
468 -- But (?x::Int) => Int -> Int
469 noParenPred (ClassP {}) = True
470 noParenPred (EqPred {}) = True
471 noParenPred (IParam {}) = False
474 instance Outputable Type where
477 instance Outputable PredType where
480 instance Outputable name => OutputableBndr (IPName name) where
481 pprBndr _ n = ppr n -- Simple for now
484 -- OK, here's the main printer
486 pprKind, pprParendKind :: Kind -> SDoc
488 pprParendKind = pprParendType
490 ppr_type :: Prec -> Type -> SDoc
491 ppr_type _ (TyVarTy tv) = ppr_tvar tv
492 ppr_type p (PredTy pred) = maybeParen p TyConPrec $
493 ifPprDebug (ptext (sLit "<pred>")) <> (ppr pred)
494 ppr_type p (TyConApp tc tys) = ppr_tc_app p tc tys
496 ppr_type p (AppTy t1 t2) = maybeParen p TyConPrec $
497 pprType t1 <+> ppr_type TyConPrec t2
499 ppr_type p ty@(ForAllTy _ _) = ppr_forall_type p ty
500 ppr_type p ty@(FunTy (PredTy _) _) = ppr_forall_type p ty
502 ppr_type p (FunTy ty1 ty2)
503 = -- We don't want to lose synonyms, so we mustn't use splitFunTys here.
504 maybeParen p FunPrec $
505 sep (ppr_type FunPrec ty1 : ppr_fun_tail ty2)
507 ppr_fun_tail (FunTy ty1 ty2)
508 | not (is_pred ty1) = (arrow <+> ppr_type FunPrec ty1) : ppr_fun_tail ty2
509 ppr_fun_tail other_ty = [arrow <+> pprType other_ty]
510 is_pred (PredTy {}) = True
513 ppr_forall_type :: Prec -> Type -> SDoc
515 = maybeParen p FunPrec $
516 sep [pprForAll tvs, pprThetaArrow ctxt, pprType tau]
518 (tvs, rho) = split1 [] ty
519 (ctxt, tau) = split2 [] rho
521 -- We need to be extra careful here as equality constraints will occur as
522 -- type variables with an equality kind. So, while collecting quantified
523 -- variables, we separate the coercion variables out and turn them into
524 -- equality predicates.
525 split1 tvs (ForAllTy tv ty)
526 | not (isCoVar tv) = split1 (tv:tvs) ty
527 split1 tvs ty = (reverse tvs, ty)
529 split2 ps (PredTy p `FunTy` ty) = split2 (p:ps) ty
530 split2 ps (ForAllTy tv ty)
531 | isCoVar tv = split2 (coVarPred tv : ps) ty
532 split2 ps ty = (reverse ps, ty)
534 ppr_tc_app :: Prec -> TyCon -> [Type] -> SDoc
538 | tc `hasKey` listTyConKey = brackets (pprType ty)
539 | tc `hasKey` parrTyConKey = ptext (sLit "[:") <> pprType ty <> ptext (sLit ":]")
540 | tc `hasKey` liftedTypeKindTyConKey = ptext (sLit "*")
541 | tc `hasKey` unliftedTypeKindTyConKey = ptext (sLit "#")
542 | tc `hasKey` openTypeKindTyConKey = ptext (sLit "(?)")
543 | tc `hasKey` ubxTupleKindTyConKey = ptext (sLit "(#)")
544 | tc `hasKey` argTypeKindTyConKey = ptext (sLit "??")
547 | [ecvar,ty] <- tys, tc `hasKey` hetMetCodeTypeTyConKey
548 = ptext (sLit "<[") <> pprType ty <> ptext (sLit "]>@") <> ppr ecvar
549 | isTupleTyCon tc && tyConArity tc == length tys
550 = tupleParens (tupleTyConBoxity tc) (sep (punctuate comma (map pprType tys)))
552 = ppr_type_app p (getName tc) tys
554 ppr_type_app :: Prec -> Name -> [Type] -> SDoc
555 -- Used for classes as well as types; that's why it's separate from ppr_tc_app
556 ppr_type_app p tc tys
557 | is_sym_occ -- Print infix if possible
558 , [ty1,ty2] <- tys -- We know nothing of precedence though
559 = maybeParen p FunPrec (sep [ppr_type FunPrec ty1,
560 pprInfixVar True (ppr tc) <+> ppr_type FunPrec ty2])
562 = maybeParen p TyConPrec (hang (pprPrefixVar is_sym_occ (ppr tc))
563 2 (sep (map pprParendType tys)))
565 is_sym_occ = isSymOcc (getOccName tc)
567 ppr_tc :: TyCon -> SDoc -- No brackets for SymOcc
569 = pp_nt_debug <> ppr tc
571 pp_nt_debug | isNewTyCon tc = ifPprDebug (if isRecursiveTyCon tc
572 then ptext (sLit "<recnt>")
573 else ptext (sLit "<nt>"))
576 ppr_tvar :: TyVar -> SDoc
577 ppr_tvar tv -- Note [Infix type variables]
578 | isSymOcc (getOccName tv) = parens (ppr tv)
582 pprForAll :: [TyVar] -> SDoc
584 pprForAll tvs = ptext (sLit "forall") <+> sep (map pprTvBndr tvs) <> dot
586 pprTvBndr :: TyVar -> SDoc
587 pprTvBndr tv | isLiftedTypeKind kind = ppr_tvar tv
588 | otherwise = parens (ppr_tvar tv <+> dcolon <+> pprKind kind)
593 Note [Infix type variables]
594 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
595 With TypeOperators you can say
599 and the (~>) is considered a type variable. However, the type
600 pretty-printer in this module will just see (a ~> b) as
602 App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b")
604 So it'll print the type in prefix form. To avoid confusion we must
605 remember to parenthesise the operator, thus