Add {-# OPTIONS_GHC -w #-} and some blurb to all compiler modules
[ghc-hetmet.git] / compiler / types / TypeRep.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 %
5 \section[TypeRep]{Type - friends' interface}
6
7 \begin{code}
8 {-# OPTIONS_GHC -w #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/WorkingConventions#Warnings
13 -- for details
14
15 module TypeRep (
16         TyThing(..), 
17         Type(..), TyNote(..),           -- Representation visible 
18         PredType(..),                   -- to friends
19         
20         Kind, ThetaType,                -- Synonyms
21
22         funTyCon,
23
24         -- Pretty-printing
25         pprType, pprParendType, pprTypeApp,
26         pprTyThingCategory, 
27         pprPred, pprTheta, pprForAll, pprThetaArrow, pprClassPred,
28
29         -- Kinds
30         liftedTypeKind, unliftedTypeKind, openTypeKind,
31         argTypeKind, ubxTupleKind,
32         isLiftedTypeKindCon, isLiftedTypeKind,
33         mkArrowKind, mkArrowKinds, isCoercionKind,
34
35         -- Kind constructors...
36         liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
37         argTypeKindTyCon, ubxTupleKindTyCon,
38
39         -- And their names
40         unliftedTypeKindTyConName, openTypeKindTyConName,
41         ubxTupleKindTyConName, argTypeKindTyConName,
42         liftedTypeKindTyConName,
43
44         -- Super Kinds
45         tySuperKind, coSuperKind,
46         isTySuperKind, isCoSuperKind,
47         tySuperKindTyCon, coSuperKindTyCon,
48         
49         pprKind, pprParendKind
50     ) where
51
52 #include "HsVersions.h"
53
54 import {-# SOURCE #-} DataCon( DataCon, dataConName )
55
56 -- friends:
57 import Var
58 import VarSet
59 import Name
60 import OccName
61 import BasicTypes
62 import TyCon
63 import Class
64
65 -- others
66 import PrelNames
67 import Outputable
68 \end{code}
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{Type Classifications}
73 %*                                                                      *
74 %************************************************************************
75
76 A type is
77
78         *unboxed*       iff its representation is other than a pointer
79                         Unboxed types are also unlifted.
80
81         *lifted*        A type is lifted iff it has bottom as an element.
82                         Closures always have lifted types:  i.e. any
83                         let-bound identifier in Core must have a lifted
84                         type.  Operationally, a lifted object is one that
85                         can be entered.
86
87                         Only lifted types may be unified with a type variable.
88
89         *algebraic*     A type with one or more constructors, whether declared
90                         with "data" or "newtype".   
91                         An algebraic type is one that can be deconstructed
92                         with a case expression.  
93                         *NOT* the same as lifted types,  because we also 
94                         include unboxed tuples in this classification.
95
96         *data*          A type declared with "data".  Also boxed tuples.
97
98         *primitive*     iff it is a built-in type that can't be expressed
99                         in Haskell.
100
101 Currently, all primitive types are unlifted, but that's not necessarily
102 the case.  (E.g. Int could be primitive.)
103
104 Some primitive types are unboxed, such as Int#, whereas some are boxed
105 but unlifted (such as ByteArray#).  The only primitive types that we
106 classify as algebraic are the unboxed tuples.
107
108 examples of type classifications:
109
110 Type            primitive       boxed           lifted          algebraic    
111 -----------------------------------------------------------------------------
112 Int#,           Yes             No              No              No
113 ByteArray#      Yes             Yes             No              No
114 (# a, b #)      Yes             No              No              Yes
115 (  a, b  )      No              Yes             Yes             Yes
116 [a]             No              Yes             Yes             Yes
117
118
119
120         ----------------------
121         A note about newtypes
122         ----------------------
123
124 Consider
125         newtype N = MkN Int
126
127 Then we want N to be represented as an Int, and that's what we arrange.
128 The front end of the compiler [TcType.lhs] treats N as opaque, 
129 the back end treats it as transparent [Type.lhs].
130
131 There's a bit of a problem with recursive newtypes
132         newtype P = MkP P
133         newtype Q = MkQ (Q->Q)
134
135 Here the 'implicit expansion' we get from treating P and Q as transparent
136 would give rise to infinite types, which in turn makes eqType diverge.
137 Similarly splitForAllTys and splitFunTys can get into a loop.  
138
139 Solution: 
140
141 * Newtypes are always represented using TyConApp.
142
143 * For non-recursive newtypes, P, treat P just like a type synonym after 
144   type-checking is done; i.e. it's opaque during type checking (functions
145   from TcType) but transparent afterwards (functions from Type).  
146   "Treat P as a type synonym" means "all functions expand NewTcApps 
147   on the fly".
148
149   Applications of the data constructor P simply vanish:
150         P x = x
151   
152
153 * For recursive newtypes Q, treat the Q and its representation as 
154   distinct right through the compiler.  Applications of the data consructor
155   use a coerce:
156         Q = \(x::Q->Q). coerce Q x
157   They are rare, so who cares if they are a tiny bit less efficient.
158
159 The typechecker (TcTyDecls) identifies enough type construtors as 'recursive'
160 to cut all loops.  The other members of the loop may be marked 'non-recursive'.
161
162
163 %************************************************************************
164 %*                                                                      *
165 \subsection{The data type}
166 %*                                                                      *
167 %************************************************************************
168
169
170 \begin{code}
171 data Type
172   = TyVarTy TyVar       
173
174   | AppTy
175         Type            -- Function is *not* a TyConApp
176         Type            -- It must be another AppTy, or TyVarTy
177                         -- (or NoteTy of these)
178
179   | TyConApp            -- Application of a TyCon, including newtypes *and* synonyms
180         TyCon           --  *Invariant* saturated appliations of FunTyCon and
181                         --      synonyms have their own constructors, below.
182                         -- However, *unsaturated* FunTyCons do appear as TyConApps.  
183                         -- 
184         [Type]          -- Might not be saturated.
185                         -- Even type synonyms are not necessarily saturated;
186                         -- for example unsaturated type synonyms can appear as the 
187                         -- RHS of a type synonym.
188
189   | FunTy               -- Special case of TyConApp: TyConApp FunTyCon [t1,t2]
190         Type
191         Type
192
193   | ForAllTy            -- A polymorphic type
194         TyVar
195         Type    
196
197   | PredTy              -- The type of evidence for a type predictate
198         PredType        -- See Note [PredTy], and Note [Equality predicates]
199         -- NB: A PredTy (EqPred _ _) can appear only as the kind
200         --     of a coercion variable; never as the argument or result
201         --     of a FunTy (unlike ClassP, IParam)
202
203   | NoteTy              -- A type with a note attached
204         TyNote
205         Type            -- The expanded version
206
207 type Kind = Type        -- Invariant: a kind is always
208                         --      FunTy k1 k2
209                         -- or   TyConApp PrimTyCon [...]
210                         -- or   TyVar kv (during inference only)
211                         -- or   ForAll ... (for top-level coercions)
212
213 type SuperKind = Type   -- Invariant: a super kind is always 
214                         --   TyConApp SuperKindTyCon ...
215
216 data TyNote = FTVNote TyVarSet  -- The free type variables of the noted expression
217 \end{code}
218
219 -------------------------------------
220                 Note [PredTy]
221
222 A type of the form
223         PredTy p
224 represents a value whose type is the Haskell predicate p, 
225 where a predicate is what occurs before the '=>' in a Haskell type.
226 It can be expanded into its representation, but: 
227
228         * The type checker must treat it as opaque
229         * The rest of the compiler treats it as transparent
230
231 Consider these examples:
232         f :: (Eq a) => a -> Int
233         g :: (?x :: Int -> Int) => a -> Int
234         h :: (r\l) => {r} => {l::Int | r}
235
236 Here the "Eq a" and "?x :: Int -> Int" and "r\l" are all called *predicates*
237 Predicates are represented inside GHC by PredType:
238
239 \begin{code}
240 data PredType 
241   = ClassP Class [Type]         -- Class predicate
242   | IParam (IPName Name) Type   -- Implicit parameter
243   | EqPred Type Type            -- Equality predicate (ty1 ~ ty2)
244
245 type ThetaType = [PredType]
246 \end{code}
247
248 (We don't support TREX records yet, but the setup is designed
249 to expand to allow them.)
250
251 A Haskell qualified type, such as that for f,g,h above, is
252 represented using 
253         * a FunTy for the double arrow
254         * with a PredTy as the function argument
255
256 The predicate really does turn into a real extra argument to the
257 function.  If the argument has type (PredTy p) then the predicate p is
258 represented by evidence (a dictionary, for example, of type (predRepTy p).
259
260 Note [Equality predicates]
261 ~~~~~~~~~~~~~~~~~~~~~~~~~~
262         forall a b. (a ~ S b) => a -> b
263 could be represented by
264         ForAllTy a (ForAllTy b (FunTy (PredTy (EqPred a (S b))) ...))
265 OR
266         ForAllTy a (ForAllTy b (ForAllTy (c::PredTy (EqPred a (S b))) ...))
267
268 The latter is what we do.  (Unlike for class and implicit parameter
269 constraints, which do use FunTy.)
270
271 Reason:
272         * FunTy is always a *value* function
273         * ForAllTy is discarded at runtime
274
275 We often need to make a "wildcard" (c::PredTy..).  We always use the same
276 name (wildCoVarName), since it's not mentioned.
277
278
279 %************************************************************************
280 %*                                                                      *
281                         TyThing
282 %*                                                                      *
283 %************************************************************************
284
285 Despite the fact that DataCon has to be imported via a hi-boot route, 
286 this module seems the right place for TyThing, because it's needed for
287 funTyCon and all the types in TysPrim.
288
289 \begin{code}
290 data TyThing = AnId     Id
291              | ADataCon DataCon
292              | ATyCon   TyCon
293              | AClass   Class
294
295 instance Outputable TyThing where
296   ppr thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
297
298 pprTyThingCategory :: TyThing -> SDoc
299 pprTyThingCategory (ATyCon _)   = ptext SLIT("Type constructor")
300 pprTyThingCategory (AClass _)   = ptext SLIT("Class")
301 pprTyThingCategory (AnId   _)   = ptext SLIT("Identifier")
302 pprTyThingCategory (ADataCon _) = ptext SLIT("Data constructor")
303
304 instance NamedThing TyThing where       -- Can't put this with the type
305   getName (AnId id)     = getName id    -- decl, because the DataCon instance
306   getName (ATyCon tc)   = getName tc    -- isn't visible there
307   getName (AClass cl)   = getName cl
308   getName (ADataCon dc) = dataConName dc
309 \end{code}
310
311
312 %************************************************************************
313 %*                                                                      *
314                 Wired-in type constructors
315 %*                                                                      *
316 %************************************************************************
317
318 We define a few wired-in type constructors here to avoid module knots
319
320 \begin{code}
321 --------------------------
322 -- First the TyCons...
323
324 funTyCon = mkFunTyCon funTyConName (mkArrowKinds [argTypeKind, openTypeKind] liftedTypeKind)
325         -- You might think that (->) should have type (?? -> ? -> *), and you'd be right
326         -- But if we do that we get kind errors when saying
327         --      instance Control.Arrow (->)
328         -- becuase the expected kind is (*->*->*).  The trouble is that the
329         -- expected/actual stuff in the unifier does not go contra-variant, whereas
330         -- the kind sub-typing does.  Sigh.  It really only matters if you use (->) in
331         -- a prefix way, thus:  (->) Int# Int#.  And this is unusual.
332
333
334 tySuperKindTyCon     = mkSuperKindTyCon tySuperKindTyConName
335 coSuperKindTyCon     = mkSuperKindTyCon coSuperKindTyConName
336
337 liftedTypeKindTyCon   = mkKindTyCon liftedTypeKindTyConName
338 openTypeKindTyCon     = mkKindTyCon openTypeKindTyConName
339 unliftedTypeKindTyCon = mkKindTyCon unliftedTypeKindTyConName
340 ubxTupleKindTyCon     = mkKindTyCon ubxTupleKindTyConName
341 argTypeKindTyCon      = mkKindTyCon argTypeKindTyConName
342
343 mkKindTyCon :: Name -> TyCon
344 mkKindTyCon name = mkVoidPrimTyCon name tySuperKind 0
345
346 --------------------------
347 -- ... and now their names
348
349 tySuperKindTyConName      = mkPrimTyConName FSLIT("BOX") tySuperKindTyConKey tySuperKindTyCon
350 coSuperKindTyConName      = mkPrimTyConName FSLIT("COERCION") coSuperKindTyConKey coSuperKindTyCon
351 liftedTypeKindTyConName   = mkPrimTyConName FSLIT("*") liftedTypeKindTyConKey liftedTypeKindTyCon
352 openTypeKindTyConName     = mkPrimTyConName FSLIT("?") openTypeKindTyConKey openTypeKindTyCon
353 unliftedTypeKindTyConName = mkPrimTyConName FSLIT("#") unliftedTypeKindTyConKey unliftedTypeKindTyCon
354 ubxTupleKindTyConName     = mkPrimTyConName FSLIT("(#)") ubxTupleKindTyConKey ubxTupleKindTyCon
355 argTypeKindTyConName      = mkPrimTyConName FSLIT("??") argTypeKindTyConKey argTypeKindTyCon
356 funTyConName              = mkPrimTyConName FSLIT("(->)") funTyConKey funTyCon
357
358 mkPrimTyConName occ key tycon = mkWiredInName gHC_PRIM (mkOccNameFS tcName occ) 
359                                               key 
360                                               (ATyCon tycon)
361                                               BuiltInSyntax
362         -- All of the super kinds and kinds are defined in Prim and use BuiltInSyntax,
363         -- because they are never in scope in the source
364
365 ------------------
366 -- We also need Kinds and SuperKinds, locally and in TyCon
367
368 kindTyConType :: TyCon -> Type
369 kindTyConType kind = TyConApp kind []
370
371 liftedTypeKind   = kindTyConType liftedTypeKindTyCon
372 unliftedTypeKind = kindTyConType unliftedTypeKindTyCon
373 openTypeKind     = kindTyConType openTypeKindTyCon
374 argTypeKind      = kindTyConType argTypeKindTyCon
375 ubxTupleKind     = kindTyConType ubxTupleKindTyCon
376
377 mkArrowKind :: Kind -> Kind -> Kind
378 mkArrowKind k1 k2 = FunTy k1 k2
379
380 mkArrowKinds :: [Kind] -> Kind -> Kind
381 mkArrowKinds arg_kinds result_kind = foldr mkArrowKind result_kind arg_kinds
382
383 tySuperKind, coSuperKind :: SuperKind
384 tySuperKind = kindTyConType tySuperKindTyCon 
385 coSuperKind = kindTyConType coSuperKindTyCon 
386
387 isTySuperKind (NoteTy _ ty)    = isTySuperKind ty
388 isTySuperKind (TyConApp kc []) = kc `hasKey` tySuperKindTyConKey
389 isTySuperKind other            = False
390
391 isCoSuperKind :: SuperKind -> Bool
392 isCoSuperKind (NoteTy _ ty)    = isCoSuperKind ty
393 isCoSuperKind (TyConApp kc []) = kc `hasKey` coSuperKindTyConKey
394 isCoSuperKind other            = False
395
396 -------------------
397 -- Lastly we need a few functions on Kinds
398
399 isLiftedTypeKindCon tc    = tc `hasKey` liftedTypeKindTyConKey
400
401 isLiftedTypeKind :: Kind -> Bool
402 isLiftedTypeKind (TyConApp tc []) = isLiftedTypeKindCon tc
403 isLiftedTypeKind other            = False
404
405 isCoercionKind :: Kind -> Bool
406 -- All coercions are of form (ty1 ~ ty2)
407 -- This function is here rather than in Coercion, 
408 -- because it's used in a knot-tied way to enforce invariants in Var
409 isCoercionKind (NoteTy _ k)         = isCoercionKind k
410 isCoercionKind (PredTy (EqPred {})) = True
411 isCoercionKind other                = False
412 \end{code}
413
414
415
416 %************************************************************************
417 %*                                                                      *
418 \subsection{The external interface}
419 %*                                                                      *
420 %************************************************************************
421
422 @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
423 defined to use this.  @pprParendType@ is the same, except it puts
424 parens around the type, except for the atomic cases.  @pprParendType@
425 works just by setting the initial context precedence very high.
426
427 \begin{code}
428 data Prec = TopPrec     -- No parens
429           | FunPrec     -- Function args; no parens for tycon apps
430           | TyConPrec   -- Tycon args; no parens for atomic
431           deriving( Eq, Ord )
432
433 maybeParen :: Prec -> Prec -> SDoc -> SDoc
434 maybeParen ctxt_prec inner_prec pretty
435   | ctxt_prec < inner_prec = pretty
436   | otherwise              = parens pretty
437
438 ------------------
439 pprType, pprParendType :: Type -> SDoc
440 pprType       ty = ppr_type TopPrec   ty
441 pprParendType ty = ppr_type TyConPrec ty
442
443 pprTypeApp :: NamedThing a => a -> SDoc -> [Type] -> SDoc
444 -- The first arg is the tycon; it's used to arrange printing infix 
445 -- if it looks like an operator
446 -- Second arg is the pretty-printed tycon
447 pprTypeApp tc pp_tc tys = ppr_type_app TopPrec (getName tc) pp_tc tys
448
449 ------------------
450 pprPred :: PredType -> SDoc
451 pprPred (ClassP cls tys) = pprClassPred cls tys
452 pprPred (IParam ip ty)   = ppr ip <> dcolon <> pprType ty
453 pprPred (EqPred ty1 ty2) = sep [ppr ty1, nest 2 (ptext SLIT("~")), ppr ty2]
454 pprClassPred :: Class -> [Type] -> SDoc
455 pprClassPred clas tys = ppr_type_app TopPrec (getName clas) (ppr clas) tys
456
457 pprTheta :: ThetaType -> SDoc
458 pprTheta theta = parens (sep (punctuate comma (map pprPred theta)))
459
460 pprThetaArrow :: ThetaType -> SDoc
461 pprThetaArrow theta 
462   | null theta = empty
463   | otherwise  = parens (sep (punctuate comma (map pprPred theta))) <+> ptext SLIT("=>")
464
465 ------------------
466 instance Outputable Type where
467     ppr ty = pprType ty
468
469 instance Outputable PredType where
470     ppr = pprPred
471
472 instance Outputable name => OutputableBndr (IPName name) where
473     pprBndr _ n = ppr n -- Simple for now
474
475 ------------------
476         -- OK, here's the main printer
477
478 pprKind = pprType
479 pprParendKind = pprParendType
480
481 ppr_type :: Prec -> Type -> SDoc
482 ppr_type p (TyVarTy tv)       = ppr tv
483 ppr_type p (PredTy pred)      = ifPprDebug (ptext SLIT("<pred>")) <> (ppr pred)
484 ppr_type p (NoteTy other ty2) = ppr_type p ty2
485 ppr_type p (TyConApp tc tys)  = ppr_tc_app p tc tys
486
487 ppr_type p (AppTy t1 t2) = maybeParen p TyConPrec $
488                            pprType t1 <+> ppr_type TyConPrec t2
489
490 ppr_type p ty@(ForAllTy _ _)       = ppr_forall_type p ty
491 ppr_type p ty@(FunTy (PredTy _) _) = ppr_forall_type p ty
492
493 ppr_type p (FunTy ty1 ty2)
494   = -- We don't want to lose synonyms, so we mustn't use splitFunTys here.
495     maybeParen p FunPrec $
496     sep (ppr_type FunPrec ty1 : ppr_fun_tail ty2)
497   where
498     ppr_fun_tail (FunTy ty1 ty2) = (arrow <+> ppr_type FunPrec ty1) : ppr_fun_tail ty2
499     ppr_fun_tail other_ty        = [arrow <+> pprType other_ty]
500
501 ppr_forall_type :: Prec -> Type -> SDoc
502 ppr_forall_type p ty
503   = maybeParen p FunPrec $
504     sep [pprForAll tvs, pprThetaArrow ctxt, pprType tau]
505   where
506     (tvs,  rho) = split1 [] ty
507     (ctxt, tau) = split2 [] rho
508
509     split1 tvs (ForAllTy tv ty) = split1 (tv:tvs) ty
510     split1 tvs (NoteTy _ ty)    = split1 tvs ty
511     split1 tvs ty               = (reverse tvs, ty)
512  
513     split2 ps (NoteTy _ arg     -- Rather a disgusting case
514                `FunTy` res)           = split2 ps (arg `FunTy` res)
515     split2 ps (PredTy p `FunTy` ty)   = split2 (p:ps) ty
516     split2 ps (NoteTy _ ty)           = split2 ps ty
517     split2 ps ty                      = (reverse ps, ty)
518
519 ppr_tc_app :: Prec -> TyCon -> [Type] -> SDoc
520 ppr_tc_app p tc [] 
521   = ppr_tc tc
522 ppr_tc_app p tc [ty] 
523   | tc `hasKey` listTyConKey = brackets (pprType ty)
524   | tc `hasKey` parrTyConKey = ptext SLIT("[:") <> pprType ty <> ptext SLIT(":]")
525   | tc `hasKey` liftedTypeKindTyConKey   = ptext SLIT("*")
526   | tc `hasKey` unliftedTypeKindTyConKey = ptext SLIT("#")
527   | tc `hasKey` openTypeKindTyConKey     = ptext SLIT("(?)")
528   | tc `hasKey` ubxTupleKindTyConKey     = ptext SLIT("(#)")
529   | tc `hasKey` argTypeKindTyConKey      = ptext SLIT("??")
530
531 ppr_tc_app p tc tys
532   | isTupleTyCon tc && tyConArity tc == length tys
533   = tupleParens (tupleTyConBoxity tc) (sep (punctuate comma (map pprType tys)))
534   | otherwise
535   = ppr_type_app p (getName tc) (ppr_naked_tc tc) tys
536
537 ppr_type_app :: Prec -> Name -> SDoc -> [Type] -> SDoc
538 ppr_type_app p tc pp_tc tys
539   | is_sym_occ          -- Print infix if possible
540   , [ty1,ty2] <- tys    -- We know nothing of precedence though
541   = maybeParen p FunPrec (sep [ppr_type FunPrec ty1, 
542                                pp_tc <+> ppr_type FunPrec ty2])
543   | otherwise
544   = maybeParen p TyConPrec (hang paren_tc 2 (sep (map pprParendType tys)))
545   where
546     is_sym_occ = isSymOcc (getOccName tc)
547     paren_tc | is_sym_occ = parens pp_tc
548              | otherwise  = pp_tc
549
550 ppr_tc :: TyCon -> SDoc
551 ppr_tc tc = parenSymOcc (getOccName tc) (ppr_naked_tc tc)
552
553 ppr_naked_tc :: TyCon -> SDoc   -- No brackets for SymOcc
554 ppr_naked_tc tc 
555   = pp_nt_debug <> ppr tc
556   where
557    pp_nt_debug | isNewTyCon tc = ifPprDebug (if isRecursiveTyCon tc 
558                                              then ptext SLIT("<recnt>")
559                                              else ptext SLIT("<nt>"))
560                | otherwise     = empty
561
562 -------------------
563 pprForAll []  = empty
564 pprForAll tvs = ptext SLIT("forall") <+> sep (map pprTvBndr tvs) <> dot
565
566 pprTvBndr tv | isLiftedTypeKind kind = ppr tv
567              | otherwise             = parens (ppr tv <+> dcolon <+> pprKind kind)
568              where
569                kind = tyVarKind tv
570 \end{code}
571