Super-monster patch implementing the new typechecker -- at last
[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(..), isNoParent,
15         SynTyConRhs(..),
16         CoTyConDesc(..),
17
18         -- ** Constructing TyCons
19         mkAlgTyCon,
20         mkClassTyCon,
21         mkFunTyCon,
22         mkPrimTyCon,
23         mkKindTyCon,
24         mkLiftedPrimTyCon,
25         mkTupleTyCon,
26         mkSynTyCon,
27         mkSuperKindTyCon,
28         mkCoercionTyCon,
29         mkForeignTyCon,
30         mkAnyTyCon,
31
32         -- ** Predicates on TyCons
33         isAlgTyCon,
34         isClassTyCon, isFamInstTyCon, 
35         isFunTyCon, 
36         isPrimTyCon,
37         isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, 
38         isSynTyCon, isClosedSynTyCon, 
39         isSuperKindTyCon, isDecomposableTyCon,
40         isCoercionTyCon, isCoercionTyCon_maybe,
41         isForeignTyCon, isAnyTyCon, tyConHasKind,
42
43         isInjectiveTyCon,
44         isDataTyCon, isProductTyCon, isEnumerationTyCon, 
45         isNewTyCon, isAbstractTyCon, 
46         isFamilyTyCon, isSynFamilyTyCon, isDataFamilyTyCon,
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         tyConParent,
64         tyConClass_maybe,
65         tyConFamInst_maybe, tyConFamilyCoercion_maybe,tyConFamInstSig_maybe,
66         synTyConDefn, synTyConRhs, synTyConType, 
67         tyConExtName,           -- External name for foreign types
68         algTyConRhs,
69         newTyConRhs, newTyConEtadRhs, unwrapNewTyCon_maybe, 
70         tupleTyConBoxity,
71
72         -- ** Manipulating TyCons
73         tcExpandTyCon_maybe, coreExpandTyCon_maybe,
74         makeTyConAbstract,
75         newTyConCo_maybe,
76
77         -- * Primitive representations of Types
78         PrimRep(..),
79         tyConPrimRep,
80         primRepSizeW
81 ) where
82
83 #include "HsVersions.h"
84
85 import {-# SOURCE #-} TypeRep ( Kind, Type, PredType )
86 import {-# SOURCE #-} DataCon ( DataCon, isVanillaDataCon )
87
88 import Var
89 import Class
90 import BasicTypes
91 import Name
92 import PrelNames
93 import Maybes
94 import Outputable
95 import FastString
96 import Constants
97 import Util
98 import qualified Data.Data as Data
99 \end{code}
100
101 -----------------------------------------------
102         Notes about type families
103 -----------------------------------------------
104
105 Note [Type synonym families]
106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 * Type synonym families, also known as "type functions", map directly
108   onto the type functions in FC:
109
110         type family F a :: *
111         type instance F Int = Bool
112         ..etc...
113
114 * Reply "yes" to isSynFamilyTyCon, and isFamilyTyCon
115
116 * From the user's point of view (F Int) and Bool are simply 
117   equivalent 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 * Translation of type family decl:
126         type family F a :: *
127   translates to
128     a SynTyCon 'F', whose SynTyConRhs is SynFamilyTyCon
129
130 * Translation of type instance decl:
131         type instance F [a] = Maybe a
132   translates to
133     A SynTyCon 'R:FList a', whose 
134        SynTyConRhs is (SynonymTyCon (Maybe a))
135        TyConParent is (FamInstTyCon F [a] co)
136          where co :: F [a] ~ R:FList a
137     Notice that we introduce a gratuitous vanilla type synonym
138        type R:FList a = Maybe a
139     solely so that type and data families can be treated more
140     uniformly, via a single FamInstTyCon descriptor        
141
142 * In the future we might want to support
143     * closed type families (esp when we have proper kinds)
144     * injective type families (allow decomposition)
145   but we don't at the moment [2010]
146
147 Note [Data type families]
148 ~~~~~~~~~~~~~~~~~~~~~~~~~
149 See also Note [Wrappers for data instance tycons] in MkId.lhs
150
151 * Data type families are declared thus
152         data family T a :: *
153         data instance T Int = T1 | T2 Bool
154
155   Here T is the "family TyCon".
156
157 * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon
158
159 * The user does not see any "equivalent types" as he did with type
160   synonym families.  He just sees constructors with types
161         T1 :: T Int
162         T2 :: Bool -> T Int
163
164 * Here's the FC version of the above declarations:
165
166         data T a
167         data R:TInt = T1 | T2 Bool
168         axiom ax_ti : T Int ~ R:TInt
169
170   The R:TInt is the "representation TyCons".
171   It has an AlgTyConParent of
172         FamInstTyCon T [Int] ax_ti
173
174 * The data contructor T2 has a wrapper (which is what the 
175   source-level "T2" invokes):
176
177         $WT2 :: Bool -> T Int
178         $WT2 b = T2 b `cast` sym ax_ti
179
180 * A data instance can declare a fully-fledged GADT:
181
182         data instance T (a,b) where
183           X1 :: T (Int,Bool)
184           X2 :: a -> b -> T (a,b)
185
186   Here's the FC version of the above declaration:
187
188         data R:TPair a where
189           X1 :: R:TPair Int Bool
190           X2 :: a -> b -> R:TPair a b
191         axiom ax_pr :: T (a,b) ~ R:TPair a b
192
193         $WX1 :: forall a b. a -> b -> T (a,b)
194         $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b)
195
196   The R:TPair are the "representation TyCons".
197   We have a bit of work to do, to unpick the result types of the
198   data instance declaration for T (a,b), to get the result type in the
199   representation; e.g.  T (a,b) --> R:TPair a b
200
201   The representation TyCon R:TList, has an AlgTyConParent of
202
203         FamInstTyCon T [(a,b)] ax_pr
204
205 * Notice that T is NOT translated to a FC type function; it just
206   becomes a "data type" with no constructors, which can be coerced inot
207   into R:TInt, R:TPair by the axioms.  These axioms
208   axioms come into play when (and *only* when) you
209         - use a data constructor
210         - do pattern matching
211   Rather like newtype, in fact
212
213   As a result
214
215   - T behaves just like a data type so far as decomposition is concerned
216
217   - (T Int) is not implicitly converted to R:TInt during type inference. 
218     Indeed the latter type is unknown to the programmer.
219
220   - There *is* an instance for (T Int) in the type-family instance 
221     environment, but it is only used for overlap checking
222
223   - It's fine to have T in the LHS of a type function:
224     type instance F (T a) = [a]
225
226   It was this last point that confused me!  The big thing is that you
227   should not think of a data family T as a *type function* at all, not
228   even an injective one!  We can't allow even injective type functions
229   on the LHS of a type function:
230         type family injective G a :: *
231         type instance F (G Int) = Bool
232   is no good, even if G is injective, because consider
233         type instance G Int = Bool
234         type instance F Bool = Char
235
236   So a data type family is not an injective type function. It's just a
237   data type with some axioms that connect it to other data types. 
238
239 %************************************************************************
240 %*                                                                      *
241 \subsection{The data type}
242 %*                                                                      *
243 %************************************************************************
244
245 \begin{code}
246 -- | TyCons represent type constructors. Type constructors are introduced by things such as:
247 --
248 -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of kind @*@
249 --
250 -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
251 --
252 -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor of kind @* -> *@
253 --
254 -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor of kind @*@
255 --
256 -- 5) Type coercions! This is because we represent a coercion from @t1@ to @t2@ 
257 --    as a 'Type', where that type has kind @t1 ~ t2@. See "Coercion" for more on this
258 --
259 -- This data type also encodes a number of primitive, built in type constructors such as those
260 -- for function and tuple types.
261 data TyCon
262   = -- | The function type constructor, @(->)@
263     FunTyCon {
264         tyConUnique :: Unique,
265         tyConName   :: Name,
266         tc_kind   :: Kind,
267         tyConArity  :: Arity
268     }
269
270   -- | Algebraic type constructors, which are defined to be those
271   -- arising @data@ type and @newtype@ declarations.  All these
272   -- constructors are lifted and boxed. See 'AlgTyConRhs' for more
273   -- information.
274   | AlgTyCon {          
275         tyConUnique :: Unique,
276         tyConName   :: Name,
277         tc_kind   :: Kind,
278         tyConArity  :: Arity,
279
280         tyConTyVars :: [TyVar],   -- ^ The type variables used in the type constructor.
281                                   -- Invariant: length tyvars = arity
282                                   -- Precisely, this list scopes over:
283                                   --
284                                   -- 1. The 'algTcStupidTheta'
285                                   -- 2. The cached types in 'algTyConRhs.NewTyCon'
286                                   -- 3. The family instance types if present
287                                   --
288                                   -- Note that it does /not/ scope over the data constructors.
289
290         algTcGadtSyntax  :: Bool,       -- ^ Was the data type declared with GADT syntax? 
291                                         -- If so, that doesn't mean it's a true GADT; 
292                                         -- only that the "where" form was used. 
293                                         -- This field is used only to guide pretty-printing
294
295         algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data type 
296                                         -- (always empty for GADTs).
297                                         -- A \"stupid theta\" is the context to the left 
298                                         -- of an algebraic type declaration, 
299                                         -- e.g. @Eq a@ in the declaration 
300                                         --    @data Eq a => T a ...@.
301
302         algTcRhs :: AlgTyConRhs,  -- ^ Contains information about the 
303                                   -- data constructors of the algebraic type
304
305         algTcRec :: RecFlag,      -- ^ Tells us whether the data type is part 
306                                   -- of a mutually-recursive group or not
307
308         hasGenerics :: Bool,      -- ^ Whether generic (in the -XGenerics sense) 
309                                   -- to\/from functions are available in the exports 
310                                   -- of the data type's source module.
311
312         algTcParent :: TyConParent      -- ^ Gives the class or family declaration 'TyCon' 
313                                         -- for derived 'TyCon's representing class 
314                                         -- or family instances, respectively. 
315                                         -- See also 'synTcParent'
316     }
317
318   -- | Represents the infinite family of tuple type constructors, 
319   --   @()@, @(a,b)@, @(# a, b #)@ etc.
320   | TupleTyCon {
321         tyConUnique :: Unique,
322         tyConName   :: Name,
323         tc_kind   :: Kind,
324         tyConArity  :: Arity,
325         tyConBoxed  :: Boxity,
326         tyConTyVars :: [TyVar],
327         dataCon     :: DataCon, -- ^ Corresponding tuple data constructor
328         hasGenerics :: Bool
329     }
330
331   -- | Represents type synonyms
332   | SynTyCon {
333         tyConUnique  :: Unique,
334         tyConName    :: Name,
335         tc_kind    :: Kind,
336         tyConArity   :: Arity,
337
338         tyConTyVars  :: [TyVar],        -- Bound tyvars
339
340         synTcRhs     :: SynTyConRhs,    -- ^ Contains information about the 
341                                         -- expansion of the synonym
342
343         synTcParent  :: TyConParent     -- ^ Gives the family declaration 'TyCon'
344                                         -- of 'TyCon's representing family instances
345
346     }
347
348   -- | Primitive types; cannot be defined in Haskell. This includes
349   -- the usual suspects (such as @Int#@) as well as foreign-imported
350   -- types and kinds
351   | PrimTyCon {                 
352         tyConUnique   :: Unique,
353         tyConName     :: Name,
354         tc_kind       :: Kind,
355         tyConArity    :: Arity,         -- SLPJ Oct06: I'm not sure what the significance
356                                         --             of the arity of a primtycon is!
357
358         primTyConRep  :: PrimRep,       -- ^ Many primitive tycons are unboxed, but some are
359                                         --   boxed (represented by pointers). This 'PrimRep'
360                                         --   holds that information.
361                                         -- Only relevant if tc_kind = *
362
363         isUnLifted   :: Bool,           -- ^ Most primitive tycons are unlifted 
364                                         --   (may not contain bottom)
365                                         --   but foreign-imported ones may be lifted
366
367         tyConExtName :: Maybe FastString   -- ^ @Just e@ for foreign-imported types, 
368                                            --   holds the name of the imported thing
369     }
370
371   -- | Type coercions, such as @(~)@, @sym@, @trans@, @left@ and @right@.
372   -- INVARIANT: Coercion TyCons are always fully applied
373   --            But note that a CoTyCon can be *over*-saturated in a type.
374   --            E.g.  (sym g1) Int  will be represented as (TyConApp sym [g1,Int])
375   | CoTyCon {   
376         tyConUnique :: Unique,
377         tyConName   :: Name,
378         tyConArity  :: Arity,
379         coTcDesc    :: CoTyConDesc
380     }
381
382   -- | Any types.  Like tuples, this is a potentially-infinite family of TyCons
383   --   one for each distinct Kind. They have no values at all.
384   --   Because there are infinitely many of them (like tuples) they are 
385   --   defined in GHC.Prim and have names like "Any(*->*)".  
386   --   Their Unique is derived from the OccName.
387   -- See Note [Any types] in TysPrim
388   | AnyTyCon {
389         tyConUnique  :: Unique,
390         tyConName    :: Name,
391         tc_kind    :: Kind      -- Never = *; that is done via PrimTyCon
392                                 -- See Note [Any types] in TysPrim
393     }
394
395   -- | Super-kinds. These are "kinds-of-kinds" and are never seen in
396   -- Haskell source programs.  There are only two super-kinds: TY (aka
397   -- "box"), which is the super-kind of kinds that construct types
398   -- eventually, and CO (aka "diamond"), which is the super-kind of
399   -- kinds that just represent coercions.
400   --
401   -- Super-kinds have no kind themselves, and have arity zero
402   | SuperKindTyCon {
403         tyConUnique :: Unique,
404         tyConName   :: Name
405     }
406
407 -- | Names of the fields in an algebraic record type
408 type FieldLabel = Name
409
410 -- | Represents right-hand-sides of 'TyCon's for algebraic types
411 data AlgTyConRhs
412
413     -- | Says that we know nothing about this data type, except that
414     -- it's represented by a pointer.  Used when we export a data type
415     -- abstractly into an .hi file.
416   = AbstractTyCon
417
418     -- | Represents an open type family without a fixed right hand
419     -- side.  Additional instances can appear at any time.
420     -- 
421     -- These are introduced by either a top level declaration:
422     --
423     -- > data T a :: *
424     --
425     -- Or an associated data type declaration, within a class declaration:
426     --
427     -- > class C a b where
428     -- >   data T b :: *
429   | DataFamilyTyCon
430
431     -- | Information about those 'TyCon's derived from a @data@
432     -- declaration. This includes data types with no constructors at
433     -- all.
434   | DataTyCon {
435         data_cons :: [DataCon],
436                           -- ^ The data type constructors; can be empty if the user 
437                           --   declares the type to have no constructors
438                           --
439                           -- INVARIANT: Kept in order of increasing 'DataCon' tag
440                           --      (see the tag assignment in DataCon.mkDataCon)
441
442         is_enum :: Bool   -- ^ Cached value: is this an enumeration type? 
443                           --   (See 'isEnumerationTyCon')
444     }
445
446   -- | Information about those 'TyCon's derived from a @newtype@ declaration
447   | NewTyCon {
448         data_con :: DataCon,    -- ^ The unique constructor for the @newtype@. 
449                                 --   It has no existentials
450
451         nt_rhs :: Type,         -- ^ Cached value: the argument type of the constructor, 
452                                 -- which is just the representation type of the 'TyCon'
453                                 -- (remember that @newtype@s do not exist at runtime 
454                                 -- so need a different representation type).
455                                 --
456                                 -- The free 'TyVar's of this type are the 'tyConTyVars' 
457                                 -- from the corresponding 'TyCon'
458
459         nt_etad_rhs :: ([TyVar], Type),
460                         -- ^ Same as the 'nt_rhs', but this time eta-reduced. 
461                         -- Hence the list of 'TyVar's in this field may be 
462                         -- shorter than the declared arity of the 'TyCon'.
463                         
464                         -- See Note [Newtype eta]
465       
466         nt_co :: Maybe TyCon   -- ^ A 'TyCon' (which is always a 'CoTyCon') that can 
467                                -- have a 'Coercion' extracted from it to create 
468                                -- the @newtype@ from the representation 'Type'.
469                                --
470                                -- This field is optional for non-recursive @newtype@s only.
471                                
472                                -- See Note [Newtype coercions]
473                                -- Invariant: arity = #tvs in nt_etad_rhs;
474                                --       See Note [Newtype eta]
475                                -- Watch out!  If any newtypes become transparent
476                                -- again check Trac #1072.
477     }
478
479 -- | Extract those 'DataCon's that we are able to learn about.  Note
480 -- that visibility in this sense does not correspond to visibility in
481 -- the context of any particular user program!
482 visibleDataCons :: AlgTyConRhs -> [DataCon]
483 visibleDataCons AbstractTyCon                 = []
484 visibleDataCons DataFamilyTyCon {}                    = []
485 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
486 visibleDataCons (NewTyCon{ data_con = c })    = [c]
487
488 -- ^ Both type classes as well as family instances imply implicit
489 -- type constructors.  These implicit type constructors refer to their parent
490 -- structure (ie, the class or family from which they derive) using a type of
491 -- the following form.  We use 'TyConParent' for both algebraic and synonym 
492 -- types, but the variant 'ClassTyCon' will only be used by algebraic 'TyCon's.
493 data TyConParent 
494   = -- | An ordinary type constructor has no parent.
495     NoParentTyCon
496
497   -- | Type constructors representing a class dictionary.
498   | ClassTyCon          
499         Class           -- INVARIANT: the classTyCon of this Class is the current tycon
500
501   -- | An *associated* type of a class.  
502   | AssocFamilyTyCon   
503         Class                   -- The class in whose declaration the family is declared
504
505   -- | Type constructors representing an instance of a type family. Parameters:
506   --
507   --  1) The type family in question
508   --
509   --  2) Instance types; free variables are the 'tyConTyVars'
510   --  of the current 'TyCon' (not the family one). INVARIANT: 
511   --  the number of types matches the arity of the family 'TyCon'
512   --
513   --  3) A 'CoTyCon' identifying the representation
514   --  type with the type instance family
515   | FamInstTyCon          -- See Note [Data type families]
516                           -- and Note [Type synonym families]
517         TyCon   -- The family TyCon
518         [Type]  -- Argument types (mentions the tyConTyVars of this TyCon)
519         TyCon   -- The coercion constructor
520
521         -- E.g.  data intance T [a] = ...
522         -- gives a representation tycon:
523         --      data R:TList a = ...
524         --      axiom co a :: T [a] ~ R:TList a
525         -- with R:TList's algTcParent = FamInstTyCon T [a] co
526
527 -- | Checks the invariants of a 'TyConParent' given the appropriate type class name, if any
528 okParent :: Name -> TyConParent -> Bool
529 okParent _       NoParentTyCon                    = True
530 okParent tc_name (AssocFamilyTyCon cls)           = tc_name `elem` map tyConName (classATs cls)
531 okParent tc_name (ClassTyCon cls)                 = tc_name == tyConName (classTyCon cls)
532 okParent _       (FamInstTyCon fam_tc tys _co_tc) = tyConArity fam_tc == length tys
533
534 isNoParent :: TyConParent -> Bool
535 isNoParent NoParentTyCon = True
536 isNoParent _             = False
537
538 --------------------
539
540 -- | Information pertaining to the expansion of a type synonym (@type@)
541 data SynTyConRhs
542   = SynonymTyCon      -- ^ An ordinary type synony
543        Type           -- ^ The rhs, which mentions head type variables. It acts as a
544                       -- template for the expansion when the 'TyCon' is applied to some
545                       -- types.
546
547    | SynFamilyTyCon   -- A type synonym family  e.g. type family F x y :: * -> *
548
549 --------------------
550 data CoTyConDesc
551   = CoSym   | CoTrans
552   | CoLeft  | CoRight
553   | CoCsel1 | CoCsel2 | CoCselR
554   | CoInst
555
556   | CoAxiom     -- C tvs : F lhs-tys ~ rhs-ty
557       { co_ax_tvs :: [TyVar]
558       , co_ax_lhs :: Type
559       , co_ax_rhs :: Type }
560
561   | CoUnsafe 
562 \end{code}
563
564 Note [Newtype coercions]
565 ~~~~~~~~~~~~~~~~~~~~~~~~
566 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
567 which is used for coercing from the representation type of the
568 newtype, to the newtype itself. For example,
569
570    newtype T a = MkT (a -> a)
571
572 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t ->
573 t.  This TyCon is a CoTyCon, so it does not have a kind on its
574 own; it basically has its own typing rule for the fully-applied
575 version.  If the newtype T has k type variables then CoT has arity at
576 most k.  In the case that the right hand side is a type application
577 ending with the same type variables as the left hand side, we
578 "eta-contract" the coercion.  So if we had
579
580    newtype S a = MkT [a]
581
582 then we would generate the arity 0 coercion CoS : S ~ [].  The
583 primary reason we do this is to make newtype deriving cleaner.
584
585 In the paper we'd write
586         axiom CoT : (forall t. T t) ~ (forall t. [t])
587 and then when we used CoT at a particular type, s, we'd say
588         CoT @ s
589 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
590
591 But in GHC we instead make CoT into a new piece of type syntax, CoTyCon,
592 (like instCoercionTyCon, symCoercionTyCon etc), which must always
593 be saturated, but which encodes as
594         TyConApp CoT [s]
595 In the vocabulary of the paper it's as if we had axiom declarations
596 like
597         axiom CoT t :  T t ~ [t]
598
599 Note [Newtype eta]
600 ~~~~~~~~~~~~~~~~~~
601 Consider
602         newtype Parser m a = MkParser (Foogle m a)
603 Are these two types equal (to Core)?
604         Monad (Parser m) 
605         Monad (Foogle m)
606 Well, yes.  But to see that easily we eta-reduce the RHS type of
607 Parser, in this case to ([], Froogle), so that even unsaturated applications
608 of Parser will work right.  This eta reduction is done when the type 
609 constructor is built, and cached in NewTyCon.  The cached field is
610 only used in coreExpandTyCon_maybe.
611  
612 Here's an example that I think showed up in practice
613 Source code:
614         newtype T a = MkT [a]
615         newtype Foo m = MkFoo (forall a. m a -> Int)
616
617         w1 :: Foo []
618         w1 = ...
619         
620         w2 :: Foo T
621         w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
622
623 After desugaring, and discarding the data constructors for the newtypes,
624 we get:
625         w2 :: Foo T
626         w2 = w1
627 And now Lint complains unless Foo T == Foo [], and that requires T==[]
628
629 This point carries over to the newtype coercion, because we need to
630 say 
631         w2 = w1 `cast` Foo CoT
632
633 so the coercion tycon CoT must have 
634         kind:    T ~ []
635  and    arity:   0
636
637
638 %************************************************************************
639 %*                                                                      *
640 \subsection{PrimRep}
641 %*                                                                      *
642 %************************************************************************
643
644 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
645 MachRep (see cmm/CmmExpr), although each of these types has a distinct
646 and clearly defined purpose:
647
648   - A PrimRep is a CgRep + information about signedness + information
649     about primitive pointers (AddrRep).  Signedness and primitive
650     pointers are required when passing a primitive type to a foreign
651     function, but aren't needed for call/return conventions of Haskell
652     functions.
653
654   - A MachRep is a basic machine type (non-void, doesn't contain
655     information on pointerhood or signedness, but contains some
656     reps that don't have corresponding Haskell types).
657
658 \begin{code}
659 -- | A 'PrimRep' is an abstraction of a type.  It contains information that
660 -- the code generator needs in order to pass arguments, return results,
661 -- and store values of this type.
662 data PrimRep
663   = VoidRep
664   | PtrRep
665   | IntRep              -- ^ Signed, word-sized value
666   | WordRep             -- ^ Unsigned, word-sized value
667   | Int64Rep            -- ^ Signed, 64 bit value (with 32-bit words only)
668   | Word64Rep           -- ^ Unsigned, 64 bit value (with 32-bit words only)
669   | AddrRep             -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
670   | FloatRep
671   | DoubleRep
672   deriving( Eq, Show )
673
674 instance Outputable PrimRep where
675   ppr r = text (show r)
676
677 -- | Find the size of a 'PrimRep', in words
678 primRepSizeW :: PrimRep -> Int
679 primRepSizeW IntRep   = 1
680 primRepSizeW WordRep  = 1
681 primRepSizeW Int64Rep = wORD64_SIZE `quot` wORD_SIZE
682 primRepSizeW Word64Rep= wORD64_SIZE `quot` wORD_SIZE
683 primRepSizeW FloatRep = 1    -- NB. might not take a full word
684 primRepSizeW DoubleRep= dOUBLE_SIZE `quot` wORD_SIZE
685 primRepSizeW AddrRep  = 1
686 primRepSizeW PtrRep   = 1
687 primRepSizeW VoidRep  = 0
688 \end{code}
689
690 %************************************************************************
691 %*                                                                      *
692 \subsection{TyCon Construction}
693 %*                                                                      *
694 %************************************************************************
695
696 Note: the TyCon constructors all take a Kind as one argument, even though
697 they could, in principle, work out their Kind from their other arguments.
698 But to do so they need functions from Types, and that makes a nasty
699 module mutual-recursion.  And they aren't called from many places.
700 So we compromise, and move their Kind calculation to the call site.
701
702 \begin{code}
703 -- | Given the name of the function type constructor and it's kind, create the
704 -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want 
705 -- this functionality
706 mkFunTyCon :: Name -> Kind -> TyCon
707 mkFunTyCon name kind 
708   = FunTyCon { 
709         tyConUnique = nameUnique name,
710         tyConName   = name,
711         tc_kind   = kind,
712         tyConArity  = 2
713     }
714
715 -- | This is the making of an algebraic 'TyCon'. Notably, you have to
716 -- pass in the generic (in the -XGenerics sense) information about the
717 -- type constructor - you can get hold of it easily (see Generics
718 -- module)
719 mkAlgTyCon :: Name
720            -> Kind              -- ^ Kind of the resulting 'TyCon'
721            -> [TyVar]           -- ^ 'TyVar's scoped over: see 'tyConTyVars'. 
722                                 --   Arity is inferred from the length of this list
723            -> [PredType]        -- ^ Stupid theta: see 'algTcStupidTheta'
724            -> AlgTyConRhs       -- ^ Information about dat aconstructors
725            -> TyConParent
726            -> RecFlag           -- ^ Is the 'TyCon' recursive?
727            -> Bool              -- ^ Does it have generic functions? See 'hasGenerics'
728            -> Bool              -- ^ Was the 'TyCon' declared with GADT syntax?
729            -> TyCon
730 mkAlgTyCon name kind tyvars stupid rhs parent is_rec gen_info gadt_syn
731   = AlgTyCon {  
732         tyConName        = name,
733         tyConUnique      = nameUnique name,
734         tc_kind          = kind,
735         tyConArity       = length tyvars,
736         tyConTyVars      = tyvars,
737         algTcStupidTheta = stupid,
738         algTcRhs         = rhs,
739         algTcParent      = ASSERT( okParent name parent ) parent,
740         algTcRec         = is_rec,
741         algTcGadtSyntax  = gadt_syn,
742         hasGenerics      = gen_info
743     }
744
745 -- | Simpler specialization of 'mkAlgTyCon' for classes
746 mkClassTyCon :: Name -> Kind -> [TyVar] -> AlgTyConRhs -> Class -> RecFlag -> TyCon
747 mkClassTyCon name kind tyvars rhs clas is_rec =
748   mkAlgTyCon name kind tyvars [] rhs (ClassTyCon clas) is_rec False False
749
750 mkTupleTyCon :: Name 
751              -> Kind    -- ^ Kind of the resulting 'TyCon'
752              -> Arity   -- ^ Arity of the tuple
753              -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
754              -> DataCon 
755              -> Boxity  -- ^ Whether the tuple is boxed or unboxed
756              -> Bool    -- ^ Does it have generic functions? See 'hasGenerics'
757              -> TyCon
758 mkTupleTyCon name kind arity tyvars con boxed gen_info
759   = TupleTyCon {
760         tyConUnique = nameUnique name,
761         tyConName = name,
762         tc_kind = kind,
763         tyConArity = arity,
764         tyConBoxed = boxed,
765         tyConTyVars = tyvars,
766         dataCon = con,
767         hasGenerics = gen_info
768     }
769
770 -- ^ Foreign-imported (.NET) type constructors are represented
771 -- as primitive, but /lifted/, 'TyCons' for now. They are lifted
772 -- because the Haskell type @T@ representing the (foreign) .NET
773 -- type @T@ is actually implemented (in ILX) as a @thunk<T>@
774 mkForeignTyCon :: Name 
775                -> Maybe FastString -- ^ Name of the foreign imported thing, maybe
776                -> Kind 
777                -> Arity 
778                -> TyCon
779 mkForeignTyCon name ext_name kind arity
780   = PrimTyCon {
781         tyConName    = name,
782         tyConUnique  = nameUnique name,
783         tc_kind    = kind,
784         tyConArity   = arity,
785         primTyConRep = PtrRep, -- they all do
786         isUnLifted   = False,
787         tyConExtName = ext_name
788     }
789
790
791 -- | Create an unlifted primitive 'TyCon', such as @Int#@
792 mkPrimTyCon :: Name  -> Kind -> Arity -> PrimRep -> TyCon
793 mkPrimTyCon name kind arity rep
794   = mkPrimTyCon' name kind arity rep True  
795
796 -- | Kind constructors
797 mkKindTyCon :: Name -> Kind -> TyCon
798 mkKindTyCon name kind
799   = mkPrimTyCon' name kind 0 VoidRep True  
800
801 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
802 mkLiftedPrimTyCon :: Name  -> Kind -> Arity -> PrimRep -> TyCon
803 mkLiftedPrimTyCon name kind arity rep
804   = mkPrimTyCon' name kind arity rep False
805
806 mkPrimTyCon' :: Name  -> Kind -> Arity -> PrimRep -> Bool -> TyCon
807 mkPrimTyCon' name kind arity rep is_unlifted
808   = PrimTyCon {
809         tyConName    = name,
810         tyConUnique  = nameUnique name,
811         tc_kind    = kind,
812         tyConArity   = arity,
813         primTyConRep = rep,
814         isUnLifted   = is_unlifted,
815         tyConExtName = Nothing
816     }
817
818 -- | Create a type synonym 'TyCon'
819 mkSynTyCon :: Name -> Kind -> [TyVar] -> SynTyConRhs -> TyConParent -> TyCon
820 mkSynTyCon name kind tyvars rhs parent
821   = SynTyCon {  
822         tyConName = name,
823         tyConUnique = nameUnique name,
824         tc_kind = kind,
825         tyConArity = length tyvars,
826         tyConTyVars = tyvars,
827         synTcRhs = rhs,
828         synTcParent = parent
829     }
830
831 -- | Create a coercion 'TyCon'
832 mkCoercionTyCon :: Name -> Arity 
833                 -> CoTyConDesc
834                 -> TyCon
835 mkCoercionTyCon name arity desc
836   = CoTyCon {
837         tyConName   = name,
838         tyConUnique = nameUnique name,
839         tyConArity  = arity,
840         coTcDesc    = desc }
841
842 mkAnyTyCon :: Name -> Kind -> TyCon
843 mkAnyTyCon name kind 
844   = AnyTyCon {  tyConName = name,
845                 tc_kind = kind,
846                 tyConUnique = nameUnique name }
847
848 -- | Create a super-kind 'TyCon'
849 mkSuperKindTyCon :: Name -> TyCon -- Super kinds always have arity zero
850 mkSuperKindTyCon name
851   = SuperKindTyCon {
852         tyConName = name,
853         tyConUnique = nameUnique name
854   }
855 \end{code}
856
857 \begin{code}
858 isFunTyCon :: TyCon -> Bool
859 isFunTyCon (FunTyCon {}) = True
860 isFunTyCon _             = False
861
862 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
863 isAbstractTyCon :: TyCon -> Bool
864 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
865 isAbstractTyCon _ = False
866
867 -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not algebraic
868 makeTyConAbstract :: TyCon -> TyCon
869 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
870 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
871
872 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
873 isPrimTyCon :: TyCon -> Bool
874 isPrimTyCon (PrimTyCon {}) = True
875 isPrimTyCon _              = False
876
877 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can only
878 -- be true for primitive and unboxed-tuple 'TyCon's
879 isUnLiftedTyCon :: TyCon -> Bool
880 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
881 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
882 isUnLiftedTyCon _                                       = False
883
884 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
885 -- @data@ or @newtype@ declaration
886 isAlgTyCon :: TyCon -> Bool
887 isAlgTyCon (AlgTyCon {})   = True
888 isAlgTyCon (TupleTyCon {}) = True
889 isAlgTyCon _               = False
890
891 isDataTyCon :: TyCon -> Bool
892 -- ^ Returns @True@ for data types that are /definitely/ represented by 
893 -- heap-allocated constructors.  These are scrutinised by Core-level 
894 -- @case@ expressions, and they get info tables allocated for them.
895 -- 
896 -- Generally, the function will be true for all @data@ types and false
897 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
898 -- not guarenteed to return @True@ in all cases that it could.
899 -- 
900 -- NB: for a data type family, only the /instance/ 'TyCon's
901 --     get an info table.  The family declaration 'TyCon' does not
902 isDataTyCon (AlgTyCon {algTcRhs = rhs})
903   = case rhs of
904         DataFamilyTyCon {}  -> False
905         DataTyCon {}  -> True
906         NewTyCon {}   -> False
907         AbstractTyCon -> False   -- We don't know, so return False
908 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
909 isDataTyCon _ = False
910
911 -- | Is this 'TyCon' that for a @newtype@
912 isNewTyCon :: TyCon -> Bool
913 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
914 isNewTyCon _                                   = False
915
916 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
917 -- into, and (possibly) a coercion from the representation type to the @newtype@.
918 -- Returns @Nothing@ if this is not possible.
919 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
920 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, 
921                                  algTcRhs = NewTyCon { nt_co = mb_co, 
922                                                        nt_rhs = rhs }})
923                            = Just (tvs, rhs, mb_co)
924 unwrapNewTyCon_maybe _     = Nothing
925
926 isProductTyCon :: TyCon -> Bool
927 -- | A /product/ 'TyCon' must both:
928 --
929 -- 1. Have /one/ constructor
930 -- 
931 -- 2. /Not/ be existential
932 -- 
933 -- However other than this there are few restrictions: they may be @data@ or @newtype@ 
934 -- 'TyCon's of any boxity and may even be recursive.
935 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
936                                     DataTyCon{ data_cons = [data_con] } 
937                                                 -> isVanillaDataCon data_con
938                                     NewTyCon {} -> True
939                                     _           -> False
940 isProductTyCon (TupleTyCon {})  = True   
941 isProductTyCon _                = False
942
943 -- | Is this a 'TyCon' representing a type synonym (@type@)?
944 isSynTyCon :: TyCon -> Bool
945 isSynTyCon (SynTyCon {}) = True
946 isSynTyCon _             = False
947
948 -- As for newtypes, it is in some contexts important to distinguish between
949 -- closed synonyms and synonym families, as synonym families have no unique
950 -- right hand side to which a synonym family application can expand.
951 --
952
953 isDecomposableTyCon :: TyCon -> Bool
954 -- True iff we can decompose (T a b c) into ((T a b) c)
955 -- Specifically NOT true of synonyms (open and otherwise) and coercions
956 isDecomposableTyCon (SynTyCon {}) = False
957 isDecomposableTyCon (CoTyCon {})  = False
958 isDecomposableTyCon _other        = True
959
960 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
961 isGadtSyntaxTyCon :: TyCon -> Bool
962 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
963 isGadtSyntaxTyCon _                                    = False
964
965 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
966 isEnumerationTyCon :: TyCon -> Bool
967 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
968 isEnumerationTyCon (TupleTyCon {tyConArity = arity}) = arity == 0
969 isEnumerationTyCon _                                                   = False
970
971 -- | Is this a 'TyCon', synonym or otherwise, that may have further instances appear?
972 isFamilyTyCon :: TyCon -> Bool
973 isFamilyTyCon (SynTyCon {synTcRhs = SynFamilyTyCon {}})  = True
974 isFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
975 isFamilyTyCon _ = False
976
977 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
978 isSynFamilyTyCon :: TyCon -> Bool
979 isSynFamilyTyCon (SynTyCon {synTcRhs = SynFamilyTyCon {}}) = True
980 isSynFamilyTyCon _ = False
981
982 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
983 isDataFamilyTyCon :: TyCon -> Bool
984 isDataFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
985 isDataFamilyTyCon _ = False
986
987 -- | Is this a synonym 'TyCon' that can have no further instances appear?
988 isClosedSynTyCon :: TyCon -> Bool
989 isClosedSynTyCon tycon = isSynTyCon tycon && not (isFamilyTyCon tycon)
990
991 -- | Injective 'TyCon's can be decomposed, so that
992 --     T ty1 ~ T ty2  =>  ty1 ~ ty2
993 isInjectiveTyCon :: TyCon -> Bool
994 isInjectiveTyCon tc = not (isSynTyCon tc)
995         -- Ultimately we may have injective associated types
996         -- in which case this test will become more interesting
997         --
998         -- It'd be unusual to call isInjectiveTyCon on a regular H98
999         -- type synonym, because you should probably have expanded it first
1000         -- But regardless, it's not injective!
1001
1002 -- | Are we able to extract informationa 'TyVar' to class argument list
1003 -- mappping from a given 'TyCon'?
1004 isTyConAssoc :: TyCon -> Bool
1005 isTyConAssoc tc = case tyConParent tc of
1006                      AssocFamilyTyCon {} -> True
1007                      _                   -> False
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 = DataFamilyTyCon {}}) = 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 \end{code}
1256
1257 \begin{code}
1258 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ type with one
1259 -- alternative, a tuple type or a @newtype@ then that constructor is returned. If the 'TyCon'
1260 -- has more than one constructor, or represents a primitive or function type constructor then
1261 -- @Nothing@ is returned. In any other case, the function panics
1262 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1263 tyConSingleDataCon_maybe (TupleTyCon {dataCon = c})                            = Just c
1264 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = [c] }}) = Just c
1265 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})     = Just c
1266 tyConSingleDataCon_maybe _                                                     = Nothing
1267 \end{code}
1268
1269 \begin{code}
1270 -- | Is this 'TyCon' that for a class instance?
1271 isClassTyCon :: TyCon -> Bool
1272 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
1273 isClassTyCon _                                       = False
1274
1275 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1276 -- Otherwise returns @Nothing@
1277 tyConClass_maybe :: TyCon -> Maybe Class
1278 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
1279 tyConClass_maybe _                                          = Nothing
1280
1281 ----------------------------------------------------------------------------
1282 tyConParent :: TyCon -> TyConParent
1283 tyConParent (AlgTyCon {algTcParent = parent}) = parent
1284 tyConParent (SynTyCon {synTcParent = parent}) = parent
1285 tyConParent _                                 = NoParentTyCon
1286
1287 -- | Is this 'TyCon' that for a family instance, be that for a synonym or an
1288 -- algebraic family instance?
1289 isFamInstTyCon :: TyCon -> Bool
1290 isFamInstTyCon tc = case tyConParent tc of
1291                       FamInstTyCon {} -> True
1292                       _               -> False
1293
1294 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], TyCon)
1295 tyConFamInstSig_maybe tc
1296   = case tyConParent tc of
1297       FamInstTyCon f ts co_tc -> Just (f, ts, co_tc)
1298       _                       -> Nothing
1299
1300 -- | If this 'TyCon' is that of a family instance, return the family in question
1301 -- and the instance types. Otherwise, return @Nothing@
1302 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1303 tyConFamInst_maybe tc
1304   = case tyConParent tc of
1305       FamInstTyCon f ts _ -> Just (f, ts)
1306       _                   -> Nothing
1307
1308 -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which represents 
1309 -- a coercion identifying the representation type with the type instance family.
1310 -- Otherwise, return @Nothing@
1311 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
1312 tyConFamilyCoercion_maybe tc
1313   = case tyConParent tc of
1314       FamInstTyCon _ _ co -> Just co
1315       _                   -> Nothing
1316 \end{code}
1317
1318
1319 %************************************************************************
1320 %*                                                                      *
1321 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1322 %*                                                                      *
1323 %************************************************************************
1324
1325 @TyCon@s are compared by comparing their @Unique@s.
1326
1327 The strictness analyser needs @Ord@. It is a lexicographic order with
1328 the property @(a<=b) || (b<=a)@.
1329
1330 \begin{code}
1331 instance Eq TyCon where
1332     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
1333     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
1334
1335 instance Ord TyCon where
1336     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
1337     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
1338     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
1339     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
1340     compare a b = getUnique a `compare` getUnique b
1341
1342 instance Uniquable TyCon where
1343     getUnique tc = tyConUnique tc
1344
1345 instance Outputable CoTyConDesc where
1346     ppr CoSym    = ptext (sLit "SYM")
1347     ppr CoTrans  = ptext (sLit "TRANS")
1348     ppr CoLeft   = ptext (sLit "LEFT")
1349     ppr CoRight  = ptext (sLit "RIGHT")
1350     ppr CoCsel1  = ptext (sLit "CSEL1")
1351     ppr CoCsel2  = ptext (sLit "CSEL2")
1352     ppr CoCselR  = ptext (sLit "CSELR")
1353     ppr CoInst   = ptext (sLit "INST")
1354     ppr CoUnsafe = ptext (sLit "UNSAFE")
1355     ppr (CoAxiom {}) = ptext (sLit "AXIOM")
1356
1357 instance Outputable TyCon where
1358     ppr tc  = ppr (getName tc) 
1359
1360 instance NamedThing TyCon where
1361     getName = tyConName
1362
1363 instance Data.Typeable TyCon where
1364     typeOf _ = Data.mkTyConApp (Data.mkTyCon "TyCon") []
1365
1366 instance Data.Data TyCon where
1367     -- don't traverse?
1368     toConstr _   = abstractConstr "TyCon"
1369     gunfold _ _  = error "gunfold"
1370     dataTypeOf _ = mkNoRepType "TyCon"
1371 \end{code}