Fix Trac #4127 (and hence #4173)
[ghc-hetmet.git] / compiler / types / TyCon.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 The @TyCon@ datatype
7
8 \begin{code}
9 module TyCon(
10         -- * Main TyCon data types
11         TyCon, FieldLabel, 
12
13         AlgTyConRhs(..), visibleDataCons, 
14         TyConParent(..), 
15         SynTyConRhs(..),
16         CoTyConDesc(..),
17         AssocFamilyPermutation,
18
19         -- ** Constructing TyCons
20         mkAlgTyCon,
21         mkClassTyCon,
22         mkFunTyCon,
23         mkPrimTyCon,
24         mkKindTyCon,
25         mkLiftedPrimTyCon,
26         mkTupleTyCon,
27         mkSynTyCon,
28         mkSuperKindTyCon,
29         mkCoercionTyCon,
30         mkForeignTyCon,
31         mkAnyTyCon,
32
33         -- ** Predicates on TyCons
34         isAlgTyCon,
35         isClassTyCon, isFamInstTyCon, 
36         isFunTyCon, 
37         isPrimTyCon,
38         isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, 
39         isSynTyCon, isClosedSynTyCon, isOpenSynTyCon,
40         isSuperKindTyCon, isDecomposableTyCon,
41         isCoercionTyCon, isCoercionTyCon_maybe,
42         isForeignTyCon, isAnyTyCon, tyConHasKind,
43
44         isInjectiveTyCon,
45         isDataTyCon, isProductTyCon, isEnumerationTyCon, 
46         isNewTyCon, isAbstractTyCon, isOpenTyCon,
47         isUnLiftedTyCon,
48         isGadtSyntaxTyCon,
49         isTyConAssoc,
50         isRecursiveTyCon,
51         isHiBootTyCon,
52         isImplicitTyCon, tyConHasGenerics,
53
54         -- ** Extracting information out of TyCons
55         tyConName,
56         tyConKind,
57         tyConUnique,
58         tyConTyVars,
59         tyConDataCons, tyConDataCons_maybe, tyConSingleDataCon_maybe,
60         tyConFamilySize,
61         tyConStupidTheta,
62         tyConArity,
63         tyConClass_maybe,
64         tyConFamInst_maybe, tyConFamilyCoercion_maybe,
65         synTyConDefn, synTyConRhs, synTyConType, synTyConResKind,
66         tyConExtName,           -- External name for foreign types
67         algTyConRhs,
68         newTyConRhs, newTyConEtadRhs, unwrapNewTyCon_maybe, 
69         assocTyConArgPoss_maybe,
70         tupleTyConBoxity,
71
72         -- ** Manipulating TyCons
73         tcExpandTyCon_maybe, coreExpandTyCon_maybe,
74         makeTyConAbstract,
75         newTyConCo_maybe,
76         setTyConArgPoss, 
77
78         -- * Primitive representations of Types
79         PrimRep(..),
80         tyConPrimRep,
81         primRepSizeW
82 ) where
83
84 #include "HsVersions.h"
85
86 import {-# SOURCE #-} TypeRep ( Kind, Type, PredType )
87 import {-# SOURCE #-} DataCon ( DataCon, isVanillaDataCon )
88
89 import Var
90 import Class
91 import BasicTypes
92 import Name
93 import PrelNames
94 import Maybes
95 import Outputable
96 import FastString
97 import Constants
98 import Util
99 import qualified Data.Data as Data
100 import Data.List( elemIndex )
101 \end{code}
102
103 -----------------------------------------------
104         Notes about type families
105 -----------------------------------------------
106
107 Type synonym families
108 ~~~~~~~~~~~~~~~~~~~~~~
109 * Type synonym families, also known as "type functions", map directly
110   onto the type functions in FC:
111
112         type family F a :: *
113         type instance F Int = Bool
114         ..etc...
115
116 * From the user's point of view (F Int) and Bool are simply equivalent
117   types.
118
119 * A Haskell 98 type synonym is a degenerate form of a type synonym
120   family.
121
122 * Type functions can't appear in the LHS of a type function:
123         type instance F (F Int) = ...   -- BAD!
124
125 * In the future we might want to support
126     * closed type families (esp when we have proper kinds)
127     * injective type families (allow decomposition)
128   but we don't at the moment [2010]
129
130 Data type families
131 ~~~~~~~~~~~~~~~~~~
132 * Data type families are declared thus
133         data family T a :: *
134         data instance T Int = T1 | T2 Bool
135         data instance T [a] where
136           X1 :: T [Int]
137           X2 :: a -> T [a]
138
139 * The user does not see any "equivalent types" as he did with type
140   synonym families.  He just sees constructors with types
141         T1 :: T Int
142         T2 :: Bool -> T Int
143         X1 :: T [Int]
144         X2 :: a -> T [a]
145   Note that X2 is a fully-fledged GADT constructor; that's fine
146
147 * The conversion into FC is interesting, and is the point where I was
148   getting mixed up.  Here's the FC version of the above declarations:
149
150         data T a
151         data TI = T1 | T2 Bool
152         axiom ax_ti : T Int ~ TI
153
154         data TL a where
155           X1 :: TL Int
156           X2 :: a -> TL a
157         axiom ax_tl :: T [a] ~ TL a
158
159 * Notice that T is NOT translated to a FC type function; it just
160   becomes a "data type" with no constructors, into which TI, TL, TB
161   are cast using their respective axioms.
162
163 * As a result
164   - T behaves just like a data type so far as decomposition is concerned
165   - It's fine to have T in the LHS of a type function:
166         type instance F (T a) = [a]
167
168 It was this last point that confused me!  The big thing is that you
169 should not think of a data family T as a *type function* at all, not
170 even an injective one!  We can't allow even injective type functions
171 on the LHS of a type function:
172         type family injective G a :: *
173         type instance F (G Int) = Bool
174 is no good, even if G is injective, because consider
175         type instance G Int = Bool
176         type instance F Bool = Char
177
178 So a data type family is not an injective type function. It's just a
179 data type with some axioms that connect it to other data types. These
180 axioms come into play when (and only when) you
181         - use a data constructor
182         - do pattern matching
183
184 %************************************************************************
185 %*                                                                      *
186 \subsection{The data type}
187 %*                                                                      *
188 %************************************************************************
189
190 \begin{code}
191 -- | TyCons represent type constructors. Type constructors are introduced by things such as:
192 --
193 -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of kind @*@
194 --
195 -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
196 --
197 -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor of kind @* -> *@
198 --
199 -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor of kind @*@
200 --
201 -- 5) Type coercions! This is because we represent a coercion from @t1@ to @t2@ as a 'Type', where
202 --    that type has kind @t1 ~ t2@. See "Coercion" for more on this
203 --
204 -- This data type also encodes a number of primitive, built in type constructors such as those
205 -- for function and tuple types.
206 data TyCon
207   = -- | The function type constructor, @(->)@
208     FunTyCon {
209         tyConUnique :: Unique,
210         tyConName   :: Name,
211         tc_kind   :: Kind,
212         tyConArity  :: Arity
213     }
214
215   -- | Algebraic type constructors, which are defined to be those arising @data@ type and @newtype@ declarations.
216   -- All these constructors are lifted and boxed. See 'AlgTyConRhs' for more information.
217   | AlgTyCon {          
218         tyConUnique :: Unique,
219         tyConName   :: Name,
220         tc_kind   :: Kind,
221         tyConArity  :: Arity,
222
223         tyConTyVars :: [TyVar],         -- ^ The type variables used in the type constructor.
224                                         -- Precisely, this list scopes over:
225                                         --
226                                         -- 1. The 'algTcStupidTheta'
227                                         --
228                                         -- 2. The cached types in 'algTyConRhs.NewTyCon'
229                                         -- 
230                                         -- 3. The family instance types if present
231                                         --
232                                         -- Note that it does /not/ scope over the data constructors.
233
234         algTcGadtSyntax  :: Bool,       -- ^ Was the data type declared with GADT syntax? If so,
235                                         -- that doesn't mean it's a true GADT; only that the "where"
236                                         --      form was used. This field is used only to guide
237                                         --      pretty-printing
238
239         algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data type (always empty for GADTs).
240                                         -- A \"stupid theta\" is the context to the left of an algebraic type
241                                         -- declaration, e.g. @Eq a@ in the declaration @data Eq a => T a ...@.
242
243         algTcRhs :: AlgTyConRhs,        -- ^ Contains information about the data constructors of the algebraic type
244
245         algTcRec :: RecFlag,            -- ^ Tells us whether the data type is part of a mutually-recursive group or not
246
247         hasGenerics :: Bool,            -- ^ Whether generic (in the -XGenerics sense) to\/from functions are
248                                         -- available in the exports of the data type's source module.
249
250         algTcParent :: TyConParent      -- ^ Gives the class or family declaration 'TyCon' for derived 'TyCon's
251                                         -- representing class or family instances, respectively. See also 'synTcParent'
252     }
253
254   -- | Represents the infinite family of tuple type constructors, @()@, @(a,b)@, @(# a, b #)@ etc.
255   | TupleTyCon {
256         tyConUnique :: Unique,
257         tyConName   :: Name,
258         tc_kind   :: Kind,
259         tyConArity  :: Arity,
260         tyConBoxed  :: Boxity,
261         tyConTyVars :: [TyVar],
262         dataCon     :: DataCon, -- ^ Corresponding tuple data constructor
263         hasGenerics :: Bool
264     }
265
266   -- | Represents type synonyms
267   | SynTyCon {
268         tyConUnique  :: Unique,
269         tyConName    :: Name,
270         tc_kind    :: Kind,
271         tyConArity   :: Arity,
272
273         tyConTyVars  :: [TyVar],        -- Bound tyvars
274
275         synTcRhs     :: SynTyConRhs,    -- ^ Contains information about the expansion of the synonym
276
277         synTcParent  :: TyConParent     -- ^ Gives the family declaration 'TyCon' of 'TyCon's representing family instances
278
279     }
280
281   -- | Primitive types; cannot be defined in Haskell. This includes the usual suspects (such as @Int#@)
282   -- as well as foreign-imported types and kinds
283   | PrimTyCon {                 
284         tyConUnique   :: Unique,
285         tyConName     :: Name,
286         tc_kind       :: Kind,
287         tyConArity    :: Arity,                 -- SLPJ Oct06: I'm not sure what the significance
288                                                 --             of the arity of a primtycon is!
289
290         primTyConRep  :: PrimRep,               -- ^ Many primitive tycons are unboxed, but some are
291                                                 --   boxed (represented by pointers). This 'PrimRep' holds
292                                                 --   that information.
293                                                 -- Only relevant if tc_kind = *
294
295         isUnLifted   :: Bool,                   -- ^ Most primitive tycons are unlifted (may not contain bottom)
296                                                 --   but foreign-imported ones may be lifted
297
298         tyConExtName :: Maybe FastString        -- ^ @Just e@ for foreign-imported types, 
299                                                 --   holds the name of the imported thing
300     }
301
302   -- | Type coercions, such as @(~)@, @sym@, @trans@, @left@ and @right@.
303   -- INVARIANT: Coercion TyCons are always fully applied
304   --            But note that a CoTyCon can be *over*-saturated in a type.
305   --            E.g.  (sym g1) Int  will be represented as (TyConApp sym [g1,Int])
306   | CoTyCon {   
307         tyConUnique :: Unique,
308         tyConName   :: Name,
309         tyConArity  :: Arity,
310         coTcDesc    :: CoTyConDesc
311     }
312
313   -- | Any types.  Like tuples, this is a potentially-infinite family of TyCons
314   --   one for each distinct Kind. They have no values at all.
315   --   Because there are infinitely many of them (like tuples) they are 
316   --   defined in GHC.Prim and have names like "Any(*->*)".  
317   --   Their Unique is derived from the OccName.
318   -- See Note [Any types] in TysPrim
319   | AnyTyCon {
320         tyConUnique  :: Unique,
321         tyConName    :: Name,
322         tc_kind    :: Kind      -- Never = *; that is done via PrimTyCon
323                                 -- See Note [Any types] in TysPrim
324     }
325
326   -- | Super-kinds. These are "kinds-of-kinds" and are never seen in Haskell source programs.
327   -- There are only two super-kinds: TY (aka "box"), which is the super-kind of kinds that 
328   -- construct types eventually, and CO (aka "diamond"), which is the super-kind of kinds
329   -- that just represent coercions.
330   --
331   -- Super-kinds have no kind themselves, and have arity zero
332   | SuperKindTyCon {
333         tyConUnique :: Unique,
334         tyConName   :: Name
335     }
336
337 -- | Names of the fields in an algebraic record type
338 type FieldLabel = Name
339
340 -- | Represents right-hand-sides of 'TyCon's for algebraic types
341 data AlgTyConRhs
342
343   -- | Says that we know nothing about this data type, except that it's represented
344   -- by a pointer.  Used when we export a data type abstractly into an .hi file.
345   = AbstractTyCon
346
347   -- | Represents an open type family without a fixed right hand
348   -- side.  Additional instances can appear at any time.
349   -- 
350   -- These are introduced by either a top level declaration:
351   --
352   -- > data T a :: *
353   --
354   -- Or an assoicated data type declaration, within a class declaration:
355   --
356   -- > class C a b where
357   -- >   data T b :: *
358
359   | OpenTyCon {
360       otArgPoss :: AssocFamilyPermutation
361     }
362
363   -- | Information about those 'TyCon's derived from a @data@ declaration. This includes 
364   -- data types with no constructors at all.
365   | DataTyCon {
366         data_cons :: [DataCon],
367                         -- ^ The data type constructors; can be empty if the user declares
368                         --   the type to have no constructors
369                         --
370                         -- INVARIANT: Kept in order of increasing 'DataCon' tag
371                         
372                         --        (see the tag assignment in DataCon.mkDataCon)
373         is_enum :: Bool         -- ^ Cached value: is this an enumeration type? (See 'isEnumerationTyCon')
374     }
375
376   -- | Information about those 'TyCon's derived from a @newtype@ declaration
377   | NewTyCon {
378         data_con :: DataCon,    -- ^ The unique constructor for the @newtype@. It has no existentials
379
380         nt_rhs :: Type,         -- ^ Cached value: the argument type of the constructor, which
381                                 -- is just the representation type of the 'TyCon' (remember that
382                                 -- @newtype@s do not exist at runtime so need a different representation
383                                 -- type).
384                                 --
385                                 -- The free 'TyVar's of this type are the 'tyConTyVars' from the corresponding
386                                 -- 'TyCon'
387
388         nt_etad_rhs :: ([TyVar], Type),
389                         -- ^ Same as the 'nt_rhs', but this time eta-reduced. Hence the list of 'TyVar's in 
390                         -- this field may be shorter than the declared arity of the 'TyCon'.
391                         
392                         -- See Note [Newtype eta]
393       
394         nt_co :: Maybe TyCon   -- ^ A 'TyCon' (which is always a 'CoTyCon') that can have a 'Coercion' 
395                                 -- extracted from it to create the @newtype@ from the representation 'Type'.
396                                 --
397                                 -- This field is optional for non-recursive @newtype@s only.
398                                 
399                                 -- See Note [Newtype coercions]
400                                 -- Invariant: arity = #tvs in nt_etad_rhs;
401                                 --      See Note [Newtype eta]
402                                 -- Watch out!  If any newtypes become transparent
403                                 -- again check Trac #1072.
404     }
405
406 type AssocFamilyPermutation
407   = Maybe [Int]  -- Nothing for *top-level* type families
408                  -- For *associated* type families, gives the position
409                  -- of that 'TyVar' in the class argument list (0-indexed)
410                  -- e.g.  class C a b c where { type F c a :: *->* }
411                  --       Then we get Just [2,0]
412          -- For *synonyms*, the length of the list is identical to
413          --                 the TyCon's arity
414          -- For *data types*, the length may be smaller than the
415          --     TyCon's arity; e.g. class C a where { data D a :: *->* }
416          --                    here D gets arity 2
417
418 -- | Extract those 'DataCon's that we are able to learn about. Note that visibility in this sense does not
419 -- correspond to visibility in the context of any particular user program!
420 visibleDataCons :: AlgTyConRhs -> [DataCon]
421 visibleDataCons AbstractTyCon                 = []
422 visibleDataCons OpenTyCon {}                  = []
423 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
424 visibleDataCons (NewTyCon{ data_con = c })    = [c]
425
426 -- ^ Both type classes as well as family instances imply implicit
427 -- type constructors.  These implicit type constructors refer to their parent
428 -- structure (ie, the class or family from which they derive) using a type of
429 -- the following form.  We use 'TyConParent' for both algebraic and synonym 
430 -- types, but the variant 'ClassTyCon' will only be used by algebraic 'TyCon's.
431 data TyConParent 
432   = -- | An ordinary type constructor has no parent.
433     NoParentTyCon
434
435   -- | Type constructors representing a class dictionary.
436   | ClassTyCon          
437         Class           -- INVARIANT: the classTyCon of this Class is the current tycon
438
439   -- | Type constructors representing an instance of a type family. Parameters:
440   --
441   --  1) The type family in question
442   --
443   --  2) Instance types; free variables are the 'tyConTyVars'
444   --  of the current 'TyCon' (not the family one). INVARIANT: 
445   --  the number of types matches the arity of the family 'TyCon'
446   --
447   --  3) A 'CoTyCon' identifying the representation
448   --  type with the type instance family
449   | FamilyTyCon   -- See Note [Data type families]
450         TyCon
451         [Type]
452         TyCon  -- c.f. Note [Newtype coercions]
453
454
455 -- | Checks the invariants of a 'TyConParent' given the appropriate type class name, if any
456 okParent :: Name -> TyConParent -> Bool
457 okParent _       NoParentTyCon                   = True
458 okParent tc_name (ClassTyCon cls)                = tyConName (classTyCon cls) == tc_name
459 okParent _       (FamilyTyCon fam_tc tys _co_tc) = tyConArity fam_tc == length tys
460
461 --------------------
462
463 -- | Information pertaining to the expansion of a type synonym (@type@)
464 data SynTyConRhs
465   = OpenSynTyCon      -- e.g. type family F x y :: * -> *
466        Kind           -- Kind of the "rhs"; ie *excluding type indices*
467                       --     In the example, the kind is (*->*)
468        AssocFamilyPermutation
469
470   | SynonymTyCon Type   -- ^ The synonym mentions head type variables. It acts as a
471                         -- template for the expansion when the 'TyCon' is applied to some
472                         -- types.
473
474 --------------------
475 data CoTyConDesc
476   = CoSym   | CoTrans
477   | CoLeft  | CoRight
478   | CoCsel1 | CoCsel2 | CoCselR
479   | CoInst
480
481   | CoAxiom     -- C tvs : F lhs-tys ~ rhs-ty
482       { co_ax_tvs :: [TyVar]
483       , co_ax_lhs :: Type
484       , co_ax_rhs :: Type }
485
486   | CoUnsafe 
487 \end{code}
488
489 Note [Newtype coercions]
490 ~~~~~~~~~~~~~~~~~~~~~~~~
491 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
492 which is used for coercing from the representation type of the
493 newtype, to the newtype itself. For example,
494
495    newtype T a = MkT (a -> a)
496
497 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t ->
498 t.  This TyCon is a CoTyCon, so it does not have a kind on its
499 own; it basically has its own typing rule for the fully-applied
500 version.  If the newtype T has k type variables then CoT has arity at
501 most k.  In the case that the right hand side is a type application
502 ending with the same type variables as the left hand side, we
503 "eta-contract" the coercion.  So if we had
504
505    newtype S a = MkT [a]
506
507 then we would generate the arity 0 coercion CoS : S ~ [].  The
508 primary reason we do this is to make newtype deriving cleaner.
509
510 In the paper we'd write
511         axiom CoT : (forall t. T t) ~ (forall t. [t])
512 and then when we used CoT at a particular type, s, we'd say
513         CoT @ s
514 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
515
516 But in GHC we instead make CoT into a new piece of type syntax, CoTyCon,
517 (like instCoercionTyCon, symCoercionTyCon etc), which must always
518 be saturated, but which encodes as
519         TyConApp CoT [s]
520 In the vocabulary of the paper it's as if we had axiom declarations
521 like
522         axiom CoT t :  T t ~ [t]
523
524 Note [Newtype eta]
525 ~~~~~~~~~~~~~~~~~~
526 Consider
527         newtype Parser m a = MkParser (Foogle m a)
528 Are these two types equal (to Core)?
529         Monad (Parser m) 
530         Monad (Foogle m)
531 Well, yes.  But to see that easily we eta-reduce the RHS type of
532 Parser, in this case to ([], Froogle), so that even unsaturated applications
533 of Parser will work right.  This eta reduction is done when the type 
534 constructor is built, and cached in NewTyCon.  The cached field is
535 only used in coreExpandTyCon_maybe.
536  
537 Here's an example that I think showed up in practice
538 Source code:
539         newtype T a = MkT [a]
540         newtype Foo m = MkFoo (forall a. m a -> Int)
541
542         w1 :: Foo []
543         w1 = ...
544         
545         w2 :: Foo T
546         w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
547
548 After desugaring, and discarding the data constructors for the newtypes,
549 we get:
550         w2 :: Foo T
551         w2 = w1
552 And now Lint complains unless Foo T == Foo [], and that requires T==[]
553
554 This point carries over to the newtype coercion, because we need to
555 say 
556         w2 = w1 `cast` Foo CoT
557
558 so the coercion tycon CoT must have 
559         kind:    T ~ []
560  and    arity:   0
561
562
563 Note [Data type families]
564 ~~~~~~~~~~~~~~~~~~~~~~~~~
565 See also Note [Wrappers for data instance tycons] in MkId.lhs
566
567 Consider
568         data family T a
569
570         data instance T (b,c) where
571           T1 :: b -> c -> T (b,c)
572           T2 :: T (Int,Bool)
573
574 Notice that the 'data instance' can be a fully-fledged GADT
575
576   * T is the "family TyCon".  It is a data type 
577     whose AlgTyConRhs is OpenTyCon
578
579   * For each 'data instance' we make "representation TyCon" 
580     :R1T, thus:
581         data :R1T b c where
582           T1 :: forall b c. b -> c -> :R1T b c
583           T1 :: :R1T Int Bool
584     We have a bit of work to do, to unpick the result types of the
585     data instance declaration to get the result type in the
586     representation; e.g.  T (Int,Bool) -->  :R1T Int Bool
587
588   * We defind a top-level coercion connecting it to the family TyCon
589
590         axiom :Co:R1T b c : T (b,c) ~ :R1T b c
591
592   * The data contructor T1 has a wrapper (which is what the 
593     source-level "T1" invokes):
594
595         $WT1 :: forall b c. b -> c -> T (b,c)
596         $WT1 b c (x::b) (y::c) = T1 b c x y `cast` sym (:Co:R1T b c)
597
598   * The representation TyCon, :R1T, has an AlgTyConParent of
599
600         FamilyTyCon T [(b,c)] :Co:R1T
601
602
603
604 %************************************************************************
605 %*                                                                      *
606 \subsection{PrimRep}
607 %*                                                                      *
608 %************************************************************************
609
610 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
611 MachRep (see cmm/CmmExpr), although each of these types has a distinct
612 and clearly defined purpose:
613
614   - A PrimRep is a CgRep + information about signedness + information
615     about primitive pointers (AddrRep).  Signedness and primitive
616     pointers are required when passing a primitive type to a foreign
617     function, but aren't needed for call/return conventions of Haskell
618     functions.
619
620   - A MachRep is a basic machine type (non-void, doesn't contain
621     information on pointerhood or signedness, but contains some
622     reps that don't have corresponding Haskell types).
623
624 \begin{code}
625 -- | A 'PrimRep' is an abstraction of a type.  It contains information that
626 -- the code generator needs in order to pass arguments, return results,
627 -- and store values of this type.
628 data PrimRep
629   = VoidRep
630   | PtrRep
631   | IntRep              -- ^ Signed, word-sized value
632   | WordRep             -- ^ Unsigned, word-sized value
633   | Int64Rep            -- ^ Signed, 64 bit value (with 32-bit words only)
634   | Word64Rep           -- ^ Unsigned, 64 bit value (with 32-bit words only)
635   | AddrRep             -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
636   | FloatRep
637   | DoubleRep
638   deriving( Eq, Show )
639
640 instance Outputable PrimRep where
641   ppr r = text (show r)
642
643 -- | Find the size of a 'PrimRep', in words
644 primRepSizeW :: PrimRep -> Int
645 primRepSizeW IntRep   = 1
646 primRepSizeW WordRep  = 1
647 primRepSizeW Int64Rep = wORD64_SIZE `quot` wORD_SIZE
648 primRepSizeW Word64Rep= wORD64_SIZE `quot` wORD_SIZE
649 primRepSizeW FloatRep = 1    -- NB. might not take a full word
650 primRepSizeW DoubleRep= dOUBLE_SIZE `quot` wORD_SIZE
651 primRepSizeW AddrRep  = 1
652 primRepSizeW PtrRep   = 1
653 primRepSizeW VoidRep  = 0
654 \end{code}
655
656 %************************************************************************
657 %*                                                                      *
658 \subsection{TyCon Construction}
659 %*                                                                      *
660 %************************************************************************
661
662 Note: the TyCon constructors all take a Kind as one argument, even though
663 they could, in principle, work out their Kind from their other arguments.
664 But to do so they need functions from Types, and that makes a nasty
665 module mutual-recursion.  And they aren't called from many places.
666 So we compromise, and move their Kind calculation to the call site.
667
668 \begin{code}
669 -- | Given the name of the function type constructor and it's kind, create the
670 -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want 
671 -- this functionality
672 mkFunTyCon :: Name -> Kind -> TyCon
673 mkFunTyCon name kind 
674   = FunTyCon { 
675         tyConUnique = nameUnique name,
676         tyConName   = name,
677         tc_kind   = kind,
678         tyConArity  = 2
679     }
680
681 -- | This is the making of an algebraic 'TyCon'. Notably, you have to pass in the generic (in the -XGenerics sense)
682 -- information about the type constructor - you can get hold of it easily (see Generics module)
683 mkAlgTyCon :: Name
684            -> Kind              -- ^ Kind of the resulting 'TyCon'
685            -> [TyVar]           -- ^ 'TyVar's scoped over: see 'tyConTyVars'. Arity is inferred from the length of this list
686            -> [PredType]        -- ^ Stupid theta: see 'algTcStupidTheta'
687            -> AlgTyConRhs       -- ^ Information about dat aconstructors
688            -> TyConParent
689            -> RecFlag           -- ^ Is the 'TyCon' recursive?
690            -> Bool              -- ^ Does it have generic functions? See 'hasGenerics'
691            -> Bool              -- ^ Was the 'TyCon' declared with GADT syntax?
692            -> TyCon
693 mkAlgTyCon name kind tyvars stupid rhs parent is_rec gen_info gadt_syn
694   = AlgTyCon {  
695         tyConName        = name,
696         tyConUnique      = nameUnique name,
697         tc_kind  = kind,
698         tyConArity       = length tyvars,
699         tyConTyVars      = tyvars,
700         algTcStupidTheta = stupid,
701         algTcRhs         = rhs,
702         algTcParent      = ASSERT( okParent name parent ) parent,
703         algTcRec         = is_rec,
704         algTcGadtSyntax  = gadt_syn,
705         hasGenerics = gen_info
706     }
707
708 -- | Simpler specialization of 'mkAlgTyCon' for classes
709 mkClassTyCon :: Name -> Kind -> [TyVar] -> AlgTyConRhs -> Class -> RecFlag -> TyCon
710 mkClassTyCon name kind tyvars rhs clas is_rec =
711   mkAlgTyCon name kind tyvars [] rhs (ClassTyCon clas) is_rec False False
712
713 mkTupleTyCon :: Name 
714              -> Kind    -- ^ Kind of the resulting 'TyCon'
715              -> Arity   -- ^ Arity of the tuple
716              -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
717              -> DataCon 
718              -> Boxity  -- ^ Whether the tuple is boxed or unboxed
719              -> Bool    -- ^ Does it have generic functions? See 'hasGenerics'
720              -> TyCon
721 mkTupleTyCon name kind arity tyvars con boxed gen_info
722   = TupleTyCon {
723         tyConUnique = nameUnique name,
724         tyConName = name,
725         tc_kind = kind,
726         tyConArity = arity,
727         tyConBoxed = boxed,
728         tyConTyVars = tyvars,
729         dataCon = con,
730         hasGenerics = gen_info
731     }
732
733 -- ^ Foreign-imported (.NET) type constructors are represented
734 -- as primitive, but /lifted/, 'TyCons' for now. They are lifted
735 -- because the Haskell type @T@ representing the (foreign) .NET
736 -- type @T@ is actually implemented (in ILX) as a @thunk<T>@
737 mkForeignTyCon :: Name 
738                -> Maybe FastString -- ^ Name of the foreign imported thing, maybe
739                -> Kind 
740                -> Arity 
741                -> TyCon
742 mkForeignTyCon name ext_name kind arity
743   = PrimTyCon {
744         tyConName    = name,
745         tyConUnique  = nameUnique name,
746         tc_kind    = kind,
747         tyConArity   = arity,
748         primTyConRep = PtrRep, -- they all do
749         isUnLifted   = False,
750         tyConExtName = ext_name
751     }
752
753
754 -- | Create an unlifted primitive 'TyCon', such as @Int#@
755 mkPrimTyCon :: Name  -> Kind -> Arity -> PrimRep -> TyCon
756 mkPrimTyCon name kind arity rep
757   = mkPrimTyCon' name kind arity rep True  
758
759 -- | Kind constructors
760 mkKindTyCon :: Name -> Kind -> TyCon
761 mkKindTyCon name kind
762   = mkPrimTyCon' name kind 0 VoidRep True  
763
764 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
765 mkLiftedPrimTyCon :: Name  -> Kind -> Arity -> PrimRep -> TyCon
766 mkLiftedPrimTyCon name kind arity rep
767   = mkPrimTyCon' name kind arity rep False
768
769 mkPrimTyCon' :: Name  -> Kind -> Arity -> PrimRep -> Bool -> TyCon
770 mkPrimTyCon' name kind arity rep is_unlifted
771   = PrimTyCon {
772         tyConName    = name,
773         tyConUnique  = nameUnique name,
774         tc_kind    = kind,
775         tyConArity   = arity,
776         primTyConRep = rep,
777         isUnLifted   = is_unlifted,
778         tyConExtName = Nothing
779     }
780
781 -- | Create a type synonym 'TyCon'
782 mkSynTyCon :: Name -> Kind -> [TyVar] -> SynTyConRhs -> TyConParent -> TyCon
783 mkSynTyCon name kind tyvars rhs parent
784   = SynTyCon {  
785         tyConName = name,
786         tyConUnique = nameUnique name,
787         tc_kind = kind,
788         tyConArity = length tyvars,
789         tyConTyVars = tyvars,
790         synTcRhs = rhs,
791         synTcParent = parent
792     }
793
794 -- | Create a coercion 'TyCon'
795 mkCoercionTyCon :: Name -> Arity 
796                 -> CoTyConDesc
797                 -> TyCon
798 mkCoercionTyCon name arity desc
799   = CoTyCon {
800         tyConName   = name,
801         tyConUnique = nameUnique name,
802         tyConArity  = arity,
803         coTcDesc    = desc }
804
805 mkAnyTyCon :: Name -> Kind -> TyCon
806 mkAnyTyCon name kind 
807   = AnyTyCon {  tyConName = name,
808                 tc_kind = kind,
809                 tyConUnique = nameUnique name }
810
811 -- | Create a super-kind 'TyCon'
812 mkSuperKindTyCon :: Name -> TyCon -- Super kinds always have arity zero
813 mkSuperKindTyCon name
814   = SuperKindTyCon {
815         tyConName = name,
816         tyConUnique = nameUnique name
817   }
818 \end{code}
819
820 \begin{code}
821 isFunTyCon :: TyCon -> Bool
822 isFunTyCon (FunTyCon {}) = True
823 isFunTyCon _             = False
824
825 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
826 isAbstractTyCon :: TyCon -> Bool
827 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
828 isAbstractTyCon _ = False
829
830 -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not algebraic
831 makeTyConAbstract :: TyCon -> TyCon
832 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
833 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
834
835 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
836 isPrimTyCon :: TyCon -> Bool
837 isPrimTyCon (PrimTyCon {}) = True
838 isPrimTyCon _              = False
839
840 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can only
841 -- be true for primitive and unboxed-tuple 'TyCon's
842 isUnLiftedTyCon :: TyCon -> Bool
843 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
844 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
845 isUnLiftedTyCon _                                       = False
846
847 -- | Returns @True@ if the supplied 'TyCon' resulted from either a @data@ or @newtype@ declaration
848 isAlgTyCon :: TyCon -> Bool
849 isAlgTyCon (AlgTyCon {})   = True
850 isAlgTyCon (TupleTyCon {}) = True
851 isAlgTyCon _               = False
852
853 isDataTyCon :: TyCon -> Bool
854 -- ^ Returns @True@ for data types that are /definitely/ represented by 
855 -- heap-allocated constructors.  These are scrutinised by Core-level 
856 -- @case@ expressions, and they get info tables allocated for them.
857 -- 
858 -- Generally, the function will be true for all @data@ types and false
859 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
860 -- not guarenteed to return @True@ in all cases that it could.
861 -- 
862 -- NB: for a data type family, only the /instance/ 'TyCon's
863 --     get an info table.  The family declaration 'TyCon' does not
864 isDataTyCon (AlgTyCon {algTcRhs = rhs})
865   = case rhs of
866         OpenTyCon {}  -> False
867         DataTyCon {}  -> True
868         NewTyCon {}   -> False
869         AbstractTyCon -> False   -- We don't know, so return False
870 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
871 isDataTyCon _ = False
872
873 -- | Is this 'TyCon' that for a @newtype@
874 isNewTyCon :: TyCon -> Bool
875 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
876 isNewTyCon _                                   = False
877
878 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
879 -- into, and (possibly) a coercion from the representation type to the @newtype@.
880 -- Returns @Nothing@ if this is not possible.
881 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
882 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, 
883                                  algTcRhs = NewTyCon { nt_co = mb_co, 
884                                                        nt_rhs = rhs }})
885                            = Just (tvs, rhs, mb_co)
886 unwrapNewTyCon_maybe _     = Nothing
887
888 isProductTyCon :: TyCon -> Bool
889 -- | A /product/ 'TyCon' must both:
890 --
891 -- 1. Have /one/ constructor
892 -- 
893 -- 2. /Not/ be existential
894 -- 
895 -- However other than this there are few restrictions: they may be @data@ or @newtype@ 
896 -- 'TyCon's of any boxity and may even be recursive.
897 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
898                                     DataTyCon{ data_cons = [data_con] } 
899                                                 -> isVanillaDataCon data_con
900                                     NewTyCon {} -> True
901                                     _           -> False
902 isProductTyCon (TupleTyCon {})  = True   
903 isProductTyCon _                = False
904
905 -- | Is this a 'TyCon' representing a type synonym (@type@)?
906 isSynTyCon :: TyCon -> Bool
907 isSynTyCon (SynTyCon {}) = True
908 isSynTyCon _             = False
909
910 -- As for newtypes, it is in some contexts important to distinguish between
911 -- closed synonyms and synonym families, as synonym families have no unique
912 -- right hand side to which a synonym family application can expand.
913 --
914
915 -- | Is this a synonym 'TyCon' that can have no further instances appear?
916 isClosedSynTyCon :: TyCon -> Bool
917 isClosedSynTyCon tycon = isSynTyCon tycon && not (isOpenTyCon tycon)
918
919 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
920 isOpenSynTyCon :: TyCon -> Bool
921 isOpenSynTyCon tycon = isSynTyCon tycon && isOpenTyCon tycon
922
923 isDecomposableTyCon :: TyCon -> Bool
924 -- True iff we can decompose (T a b c) into ((T a b) c)
925 -- Specifically NOT true of synonyms (open and otherwise) and coercions
926 isDecomposableTyCon (SynTyCon {}) = False
927 isDecomposableTyCon (CoTyCon {})  = False
928 isDecomposableTyCon _other        = True
929
930 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
931 isGadtSyntaxTyCon :: TyCon -> Bool
932 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
933 isGadtSyntaxTyCon _                                    = False
934
935 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
936 isEnumerationTyCon :: TyCon -> Bool
937 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
938 isEnumerationTyCon (TupleTyCon {tyConArity = arity}) = arity == 0
939 isEnumerationTyCon _                                                   = False
940
941 -- | Is this a 'TyCon', synonym or otherwise, that may have further instances appear?
942 isOpenTyCon :: TyCon -> Bool
943 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon {}}) = True
944 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {}})    = True
945 isOpenTyCon _                                       = False
946
947 -- | Injective 'TyCon's can be decomposed, so that
948 --     T ty1 ~ T ty2  =>  ty1 ~ ty2
949 isInjectiveTyCon :: TyCon -> Bool
950 isInjectiveTyCon tc = not (isSynTyCon tc)
951         -- Ultimately we may have injective associated types
952         -- in which case this test will become more interesting
953         --
954         -- It'd be unusual to call isInjectiveTyCon on a regular H98
955         -- type synonym, because you should probably have expanded it first
956         -- But regardless, it's not injective!
957
958 -- | Extract the mapping from 'TyVar' indexes to indexes in the corresponding family
959 -- argument lists form an open 'TyCon' of any sort, if the given 'TyCon' is indeed
960 -- such a beast and that information is available
961 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
962 assocTyConArgPoss_maybe (AlgTyCon { 
963                            algTcRhs = OpenTyCon {otArgPoss = poss}})  = poss
964 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
965 assocTyConArgPoss_maybe _ = Nothing
966
967 -- | Are we able to extract informationa 'TyVar' to class argument list
968 -- mappping from a given 'TyCon'?
969 isTyConAssoc :: TyCon -> Bool
970 isTyConAssoc = isJust . assocTyConArgPoss_maybe
971
972 -- | Set the AssocFamilyPermutation structure in an 
973 -- associated data or type synonym.  The [TyVar] are the
974 -- class type variables.  Remember, the tyvars of an associated
975 -- data/type are a subset of the class tyvars; except that an
976 -- associated data type can have extra type variables at the
977 -- end (see Note [Avoid name clashes for associated data types] in TcHsType)
978 setTyConArgPoss :: [TyVar] -> TyCon -> TyCon
979 setTyConArgPoss clas_tvs tc
980   = case tc of
981       AlgTyCon { algTcRhs = rhs }               -> tc { algTcRhs = rhs {otArgPoss = Just ps} }
982       SynTyCon { synTcRhs = OpenSynTyCon ki _ } -> tc { synTcRhs = OpenSynTyCon ki (Just ps) }
983       _                                         -> pprPanic "setTyConArgPoss" (ppr tc)
984   where
985     ps = catMaybes [tv `elemIndex` clas_tvs | tv <- tyConTyVars tc]
986        -- We will get Nothings for the "extra" type variables in an
987        -- associated data type
988
989 -- The unit tycon didn't used to be classed as a tuple tycon
990 -- but I thought that was silly so I've undone it
991 -- If it can't be for some reason, it should be a AlgTyCon
992 isTupleTyCon :: TyCon -> Bool
993 -- ^ Does this 'TyCon' represent a tuple?
994 --
995 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
996 -- 'isTupleTyCon', becuase they are built as 'AlgTyCons'.  However they
997 -- get spat into the interface file as tuple tycons, so I don't think
998 -- it matters.
999 isTupleTyCon (TupleTyCon {}) = True
1000 isTupleTyCon _               = False
1001
1002 -- | Is this the 'TyCon' for an unboxed tuple?
1003 isUnboxedTupleTyCon :: TyCon -> Bool
1004 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
1005 isUnboxedTupleTyCon _                                  = False
1006
1007 -- | Is this the 'TyCon' for a boxed tuple?
1008 isBoxedTupleTyCon :: TyCon -> Bool
1009 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
1010 isBoxedTupleTyCon _                                  = False
1011
1012 -- | Extract the boxity of the given 'TyCon', if it is a 'TupleTyCon'.
1013 -- Panics otherwise
1014 tupleTyConBoxity :: TyCon -> Boxity
1015 tupleTyConBoxity tc = tyConBoxed tc
1016
1017 -- | Is this a recursive 'TyCon'?
1018 isRecursiveTyCon :: TyCon -> Bool
1019 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
1020 isRecursiveTyCon _                                 = False
1021
1022 -- | Did this 'TyCon' originate from type-checking a .h*-boot file?
1023 isHiBootTyCon :: TyCon -> Bool
1024 -- Used for knot-tying in hi-boot files
1025 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
1026 isHiBootTyCon _                                     = False
1027
1028 -- | Is this the 'TyCon' of a foreign-imported type constructor?
1029 isForeignTyCon :: TyCon -> Bool
1030 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
1031 isForeignTyCon _                                   = False
1032
1033 -- | Is this a super-kind 'TyCon'?
1034 isSuperKindTyCon :: TyCon -> Bool
1035 isSuperKindTyCon (SuperKindTyCon {}) = True
1036 isSuperKindTyCon _                   = False
1037
1038 -- | Is this an AnyTyCon?
1039 isAnyTyCon :: TyCon -> Bool
1040 isAnyTyCon (AnyTyCon {}) = True
1041 isAnyTyCon _              = False
1042
1043 -- | Attempt to pull a 'TyCon' apart into the arity and 'coKindFun' of
1044 -- a coercion 'TyCon'. Returns @Nothing@ if the 'TyCon' is not of the
1045 -- appropriate kind
1046 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, CoTyConDesc)
1047 isCoercionTyCon_maybe (CoTyCon {tyConArity = ar, coTcDesc = desc}) 
1048   = Just (ar, desc)
1049 isCoercionTyCon_maybe _ = Nothing
1050
1051 -- | Is this a 'TyCon' that represents a coercion?
1052 isCoercionTyCon :: TyCon -> Bool
1053 isCoercionTyCon (CoTyCon {}) = True
1054 isCoercionTyCon _            = False
1055
1056 -- | Identifies implicit tycons that, in particular, do not go into interface
1057 -- files (because they are implicitly reconstructed when the interface is
1058 -- read).
1059 --
1060 -- Note that:
1061 --
1062 -- * Associated families are implicit, as they are re-constructed from
1063 --   the class declaration in which they reside, and 
1064 --
1065 -- * Family instances are /not/ implicit as they represent the instance body
1066 --   (similar to a @dfun@ does that for a class instance).
1067 isImplicitTyCon :: TyCon -> Bool
1068 isImplicitTyCon tycon | isTyConAssoc tycon           = True
1069                       | isSynTyCon tycon             = False
1070                       | isAlgTyCon tycon             = isClassTyCon tycon ||
1071                                                        isTupleTyCon tycon
1072 isImplicitTyCon _other                               = True
1073         -- catches: FunTyCon, PrimTyCon, 
1074         -- CoTyCon, SuperKindTyCon
1075 \end{code}
1076
1077
1078 -----------------------------------------------
1079 --      Expand type-constructor applications
1080 -----------------------------------------------
1081
1082 \begin{code}
1083 tcExpandTyCon_maybe, coreExpandTyCon_maybe 
1084         :: TyCon 
1085         -> [Type]                       -- ^ Arguments to 'TyCon'
1086         -> Maybe ([(TyVar,Type)],       
1087                   Type,                 
1088                   [Type])               -- ^ Returns a 'TyVar' substitution, the body type
1089                                         -- of the synonym (not yet substituted) and any arguments
1090                                         -- remaining from the application
1091
1092 -- ^ Used to create the view the /typechecker/ has on 'TyCon's. We expand (closed) synonyms only, cf. 'coreExpandTyCon_maybe'
1093 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs, 
1094                                synTcRhs = SynonymTyCon rhs }) tys
1095    = expand tvs rhs tys
1096 tcExpandTyCon_maybe _ _ = Nothing
1097
1098 ---------------
1099
1100 -- ^ Used to create the view /Core/ has on 'TyCon's. We expand not only closed synonyms like 'tcExpandTyCon_maybe',
1101 -- but also non-recursive @newtype@s
1102 coreExpandTyCon_maybe (AlgTyCon {
1103          algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
1104    = case etad_rhs of   -- Don't do this in the pattern match, lest we accidentally
1105                         -- match the etad_rhs of a *recursive* newtype
1106         (tvs,rhs) -> expand tvs rhs tys
1107
1108 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
1109
1110
1111 ----------------
1112 expand  :: [TyVar] -> Type                      -- Template
1113         -> [Type]                               -- Args
1114         -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
1115 expand tvs rhs tys
1116   = case n_tvs `compare` length tys of
1117         LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
1118         EQ -> Just (tvs `zip` tys, rhs, [])
1119         GT -> Nothing
1120    where
1121      n_tvs = length tvs
1122 \end{code}
1123
1124 \begin{code}
1125 -- | Does this 'TyCon' have any generic to\/from functions available? See also 'hasGenerics'
1126 tyConHasGenerics :: TyCon -> Bool
1127 tyConHasGenerics (AlgTyCon {hasGenerics = hg})   = hg
1128 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
1129 tyConHasGenerics _                               = False        -- Synonyms
1130
1131 tyConKind :: TyCon -> Kind
1132 tyConKind (FunTyCon   { tc_kind = k }) = k
1133 tyConKind (AlgTyCon   { tc_kind = k }) = k
1134 tyConKind (TupleTyCon { tc_kind = k }) = k
1135 tyConKind (SynTyCon   { tc_kind = k }) = k
1136 tyConKind (PrimTyCon  { tc_kind = k }) = k
1137 tyConKind (AnyTyCon   { tc_kind = k }) = k
1138 tyConKind tc = pprPanic "tyConKind" (ppr tc)    -- SuperKindTyCon and CoTyCon
1139
1140 tyConHasKind :: TyCon -> Bool
1141 tyConHasKind (SuperKindTyCon {}) = False
1142 tyConHasKind (CoTyCon {})        = False
1143 tyConHasKind _                   = True
1144
1145 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no constructors
1146 -- could be found
1147 tyConDataCons :: TyCon -> [DataCon]
1148 -- It's convenient for tyConDataCons to return the
1149 -- empty list for type synonyms etc
1150 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1151
1152 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' is the
1153 -- sort that can have any constructors (note: this does not include abstract algebraic types)
1154 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1155 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
1156 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }})    = Just [con]
1157 tyConDataCons_maybe (TupleTyCon {dataCon = con})                           = Just [con]
1158 tyConDataCons_maybe _                                                      = Nothing
1159
1160 -- | Determine the number of value constructors a 'TyCon' has. Panics if the 'TyCon'
1161 -- is not algebraic or a tuple
1162 tyConFamilySize  :: TyCon -> Int
1163 tyConFamilySize (AlgTyCon   {algTcRhs = DataTyCon {data_cons = cons}}) = 
1164   length cons
1165 tyConFamilySize (AlgTyCon   {algTcRhs = NewTyCon {}})                  = 1
1166 tyConFamilySize (AlgTyCon   {algTcRhs = OpenTyCon {}})                 = 0
1167 tyConFamilySize (TupleTyCon {})                                        = 1
1168 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
1169
1170 -- | Extract an 'AlgTyConRhs' with information about data constructors from an algebraic or tuple
1171 -- 'TyCon'. Panics for any other sort of 'TyCon'
1172 algTyConRhs :: TyCon -> AlgTyConRhs
1173 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1174 algTyConRhs (TupleTyCon {dataCon = con, tyConArity = arity})
1175     = DataTyCon { data_cons = [con], is_enum = arity == 0 }
1176 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1177 \end{code}
1178
1179 \begin{code}
1180 -- | Extract the bound type variables and type expansion of a type synonym 'TyCon'. Panics if the
1181 -- 'TyCon' is not a synonym
1182 newTyConRhs :: TyCon -> ([TyVar], Type)
1183 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
1184 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
1185
1186 -- | Extract the bound type variables and type expansion of an eta-contracted type synonym 'TyCon'.
1187 -- Panics if the 'TyCon' is not a synonym
1188 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
1189 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
1190 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
1191
1192 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to construct something
1193 -- with the @newtype@s type from its representation type (right hand side). If the supplied 'TyCon'
1194 -- is not a @newtype@, returns @Nothing@
1195 newTyConCo_maybe :: TyCon -> Maybe TyCon
1196 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
1197 newTyConCo_maybe _                                               = Nothing
1198
1199 -- | Find the primitive representation of a 'TyCon'
1200 tyConPrimRep :: TyCon -> PrimRep
1201 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
1202 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
1203 \end{code}
1204
1205 \begin{code}
1206 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context to the left of
1207 -- an algebraic type declaration, e.g. @Eq a@ in the declaration @data Eq a => T a ...@
1208 tyConStupidTheta :: TyCon -> [PredType]
1209 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
1210 tyConStupidTheta (TupleTyCon {})                        = []
1211 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
1212 \end{code}
1213
1214 \begin{code}
1215 -- | Extract the 'TyVar's bound by a type synonym and the corresponding (unsubstituted) right hand side.
1216 -- If the given 'TyCon' is not a type synonym, panics
1217 synTyConDefn :: TyCon -> ([TyVar], Type)
1218 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty}) 
1219   = (tyvars, ty)
1220 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
1221
1222 -- | Extract the information pertaining to the right hand side of a type synonym (@type@) declaration. Panics
1223 -- if the given 'TyCon' is not a type synonym
1224 synTyConRhs :: TyCon -> SynTyConRhs
1225 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
1226 synTyConRhs tc                          = pprPanic "synTyConRhs" (ppr tc)
1227
1228 -- | Find the expansion of the type synonym represented by the given 'TyCon'. The free variables of this
1229 -- type will typically include those 'TyVar's bound by the 'TyCon'. Panics if the 'TyCon' is not that of
1230 -- a type synonym
1231 synTyConType :: TyCon -> Type
1232 synTyConType tc = case synTcRhs tc of
1233                     SynonymTyCon t -> t
1234                     _              -> pprPanic "synTyConType" (ppr tc)
1235
1236 -- | Find the 'Kind' of an open type synonym. Panics if the 'TyCon' is not an open type synonym
1237 synTyConResKind :: TyCon -> Kind
1238 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
1239 synTyConResKind tycon  = pprPanic "synTyConResKind" (ppr tycon)
1240 \end{code}
1241
1242 \begin{code}
1243 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ type with one
1244 -- alternative, a tuple type or a @newtype@ then that constructor is returned. If the 'TyCon'
1245 -- has more than one constructor, or represents a primitive or function type constructor then
1246 -- @Nothing@ is returned. In any other case, the function panics
1247 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1248 tyConSingleDataCon_maybe (TupleTyCon {dataCon = c})                            = Just c
1249 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = [c] }}) = Just c
1250 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})     = Just c
1251 tyConSingleDataCon_maybe _                                                     = Nothing
1252 \end{code}
1253
1254 \begin{code}
1255 -- | Is this 'TyCon' that for a class instance?
1256 isClassTyCon :: TyCon -> Bool
1257 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
1258 isClassTyCon _                                       = False
1259
1260 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1261 -- Otherwise returns @Nothing@
1262 tyConClass_maybe :: TyCon -> Maybe Class
1263 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
1264 tyConClass_maybe _                                          = Nothing
1265
1266 -- | Is this 'TyCon' that for a family instance, be that for a synonym or an
1267 -- algebraic family instance?
1268 isFamInstTyCon :: TyCon -> Bool
1269 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
1270 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
1271 isFamInstTyCon _                                             = False
1272
1273 -- | If this 'TyCon' is that of a family instance, return the family in question
1274 -- and the instance types. Otherwise, return @Nothing@
1275 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1276 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) = 
1277   Just (fam, instTys)
1278 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) = 
1279   Just (fam, instTys)
1280 tyConFamInst_maybe _                                                    = 
1281   Nothing
1282
1283 -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which represents 
1284 -- a coercion identifying the representation type with the type instance family.
1285 -- Otherwise, return @Nothing@
1286 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
1287 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) = 
1288   Just coe
1289 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) = 
1290   Just coe
1291 tyConFamilyCoercion_maybe _                                              =
1292   Nothing
1293 \end{code}
1294
1295
1296 %************************************************************************
1297 %*                                                                      *
1298 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1299 %*                                                                      *
1300 %************************************************************************
1301
1302 @TyCon@s are compared by comparing their @Unique@s.
1303
1304 The strictness analyser needs @Ord@. It is a lexicographic order with
1305 the property @(a<=b) || (b<=a)@.
1306
1307 \begin{code}
1308 instance Eq TyCon where
1309     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
1310     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
1311
1312 instance Ord TyCon where
1313     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
1314     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
1315     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
1316     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
1317     compare a b = getUnique a `compare` getUnique b
1318
1319 instance Uniquable TyCon where
1320     getUnique tc = tyConUnique tc
1321
1322 instance Outputable CoTyConDesc where
1323     ppr CoSym    = ptext (sLit "SYM")
1324     ppr CoTrans  = ptext (sLit "TRANS")
1325     ppr CoLeft   = ptext (sLit "LEFT")
1326     ppr CoRight  = ptext (sLit "RIGHT")
1327     ppr CoCsel1  = ptext (sLit "CSEL1")
1328     ppr CoCsel2  = ptext (sLit "CSEL2")
1329     ppr CoCselR  = ptext (sLit "CSELR")
1330     ppr CoInst   = ptext (sLit "INST")
1331     ppr CoUnsafe = ptext (sLit "UNSAFE")
1332     ppr (CoAxiom {}) = ptext (sLit "AXIOM")
1333
1334 instance Outputable TyCon where
1335     ppr tc  = ppr (getName tc) 
1336
1337 instance NamedThing TyCon where
1338     getName = tyConName
1339
1340 instance Data.Typeable TyCon where
1341     typeOf _ = Data.mkTyConApp (Data.mkTyCon "TyCon") []
1342
1343 instance Data.Data TyCon where
1344     -- don't traverse?
1345     toConstr _   = abstractConstr "TyCon"
1346     gunfold _ _  = error "gunfold"
1347     dataTypeOf _ = mkNoRepType "TyCon"
1348 \end{code}