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