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