Haddock fixes
[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                         -- The 'tyConTyVars' of this 'TyCon' may mention some
505                         -- of the same type variables as the classTyVars of the
506                         -- parent 'Class'.  E.g.
507                         --
508                         -- @
509                         --    class C a b where
510                         --      data T c a
511                         -- @
512                         --
513                         -- Here the 'a' is shared with the 'Class', and that is
514                         -- important. In an instance declaration we expect the
515                         -- two to be instantiated the same way.  Eg.
516                         --
517                         -- @
518                         --    instanc C [x] (Tree y) where
519                         --      data T c [x] = T1 x | T2 c
520                         -- @
521
522   -- | Type constructors representing an instance of a type family. Parameters:
523   --
524   --  1) The type family in question
525   --
526   --  2) Instance types; free variables are the 'tyConTyVars'
527   --  of the current 'TyCon' (not the family one). INVARIANT: 
528   --  the number of types matches the arity of the family 'TyCon'
529   --
530   --  3) A 'CoTyCon' identifying the representation
531   --  type with the type instance family
532   | FamInstTyCon          -- See Note [Data type families]
533                           -- and Note [Type synonym families]
534         TyCon   -- The family TyCon
535         [Type]  -- Argument types (mentions the tyConTyVars of this TyCon)
536         TyCon   -- The coercion constructor
537
538         -- E.g.  data intance T [a] = ...
539         -- gives a representation tycon:
540         --      data R:TList a = ...
541         --      axiom co a :: T [a] ~ R:TList a
542         -- with R:TList's algTcParent = FamInstTyCon T [a] co
543
544 -- | Checks the invariants of a 'TyConParent' given the appropriate type class name, if any
545 okParent :: Name -> TyConParent -> Bool
546 okParent _       NoParentTyCon                    = True
547 okParent tc_name (AssocFamilyTyCon cls)           = tc_name `elem` map tyConName (classATs cls)
548 okParent tc_name (ClassTyCon cls)                 = tc_name == tyConName (classTyCon cls)
549 okParent _       (FamInstTyCon fam_tc tys _co_tc) = tyConArity fam_tc == length tys
550
551 isNoParent :: TyConParent -> Bool
552 isNoParent NoParentTyCon = True
553 isNoParent _             = False
554
555 --------------------
556
557 -- | Information pertaining to the expansion of a type synonym (@type@)
558 data SynTyConRhs
559   = -- | An ordinary type synonyn.
560     SynonymTyCon      
561        Type           -- This 'Type' is the rhs, and may mention from 'tyConTyVars'. 
562                       -- It acts as a template for the expansion when the 'TyCon' 
563                       -- is applied to some types.
564
565    -- | A type synonym family  e.g. @type family F x y :: * -> *@
566    | SynFamilyTyCon
567
568 --------------------
569 data CoTyConDesc
570   = CoSym   | CoTrans
571   | CoLeft  | CoRight
572   | CoCsel1 | CoCsel2 | CoCselR
573   | CoInst
574
575   | CoAxiom     -- C tvs : F lhs-tys ~ rhs-ty
576       { co_ax_tvs :: [TyVar]
577       , co_ax_lhs :: Type
578       , co_ax_rhs :: Type }
579
580   | CoUnsafe 
581 \end{code}
582
583 Note [Newtype coercions]
584 ~~~~~~~~~~~~~~~~~~~~~~~~
585 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
586 which is used for coercing from the representation type of the
587 newtype, to the newtype itself. For example,
588
589    newtype T a = MkT (a -> a)
590
591 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t ->
592 t.  This TyCon is a CoTyCon, so it does not have a kind on its
593 own; it basically has its own typing rule for the fully-applied
594 version.  If the newtype T has k type variables then CoT has arity at
595 most k.  In the case that the right hand side is a type application
596 ending with the same type variables as the left hand side, we
597 "eta-contract" the coercion.  So if we had
598
599    newtype S a = MkT [a]
600
601 then we would generate the arity 0 coercion CoS : S ~ [].  The
602 primary reason we do this is to make newtype deriving cleaner.
603
604 In the paper we'd write
605         axiom CoT : (forall t. T t) ~ (forall t. [t])
606 and then when we used CoT at a particular type, s, we'd say
607         CoT @ s
608 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
609
610 But in GHC we instead make CoT into a new piece of type syntax, CoTyCon,
611 (like instCoercionTyCon, symCoercionTyCon etc), which must always
612 be saturated, but which encodes as
613         TyConApp CoT [s]
614 In the vocabulary of the paper it's as if we had axiom declarations
615 like
616         axiom CoT t :  T t ~ [t]
617
618 Note [Newtype eta]
619 ~~~~~~~~~~~~~~~~~~
620 Consider
621         newtype Parser m a = MkParser (Foogle m a)
622 Are these two types equal (to Core)?
623         Monad (Parser m) 
624         Monad (Foogle m)
625 Well, yes.  But to see that easily we eta-reduce the RHS type of
626 Parser, in this case to ([], Froogle), so that even unsaturated applications
627 of Parser will work right.  This eta reduction is done when the type 
628 constructor is built, and cached in NewTyCon.  The cached field is
629 only used in coreExpandTyCon_maybe.
630  
631 Here's an example that I think showed up in practice
632 Source code:
633         newtype T a = MkT [a]
634         newtype Foo m = MkFoo (forall a. m a -> Int)
635
636         w1 :: Foo []
637         w1 = ...
638         
639         w2 :: Foo T
640         w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
641
642 After desugaring, and discarding the data constructors for the newtypes,
643 we get:
644         w2 :: Foo T
645         w2 = w1
646 And now Lint complains unless Foo T == Foo [], and that requires T==[]
647
648 This point carries over to the newtype coercion, because we need to
649 say 
650         w2 = w1 `cast` Foo CoT
651
652 so the coercion tycon CoT must have 
653         kind:    T ~ []
654  and    arity:   0
655
656
657 %************************************************************************
658 %*                                                                      *
659 \subsection{PrimRep}
660 %*                                                                      *
661 %************************************************************************
662
663 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
664 MachRep (see cmm/CmmExpr), although each of these types has a distinct
665 and clearly defined purpose:
666
667   - A PrimRep is a CgRep + information about signedness + information
668     about primitive pointers (AddrRep).  Signedness and primitive
669     pointers are required when passing a primitive type to a foreign
670     function, but aren't needed for call/return conventions of Haskell
671     functions.
672
673   - A MachRep is a basic machine type (non-void, doesn't contain
674     information on pointerhood or signedness, but contains some
675     reps that don't have corresponding Haskell types).
676
677 \begin{code}
678 -- | A 'PrimRep' is an abstraction of a type.  It contains information that
679 -- the code generator needs in order to pass arguments, return results,
680 -- and store values of this type.
681 data PrimRep
682   = VoidRep
683   | PtrRep
684   | IntRep              -- ^ Signed, word-sized value
685   | WordRep             -- ^ Unsigned, word-sized value
686   | Int64Rep            -- ^ Signed, 64 bit value (with 32-bit words only)
687   | Word64Rep           -- ^ Unsigned, 64 bit value (with 32-bit words only)
688   | AddrRep             -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
689   | FloatRep
690   | DoubleRep
691   deriving( Eq, Show )
692
693 instance Outputable PrimRep where
694   ppr r = text (show r)
695
696 -- | Find the size of a 'PrimRep', in words
697 primRepSizeW :: PrimRep -> Int
698 primRepSizeW IntRep   = 1
699 primRepSizeW WordRep  = 1
700 primRepSizeW Int64Rep = wORD64_SIZE `quot` wORD_SIZE
701 primRepSizeW Word64Rep= wORD64_SIZE `quot` wORD_SIZE
702 primRepSizeW FloatRep = 1    -- NB. might not take a full word
703 primRepSizeW DoubleRep= dOUBLE_SIZE `quot` wORD_SIZE
704 primRepSizeW AddrRep  = 1
705 primRepSizeW PtrRep   = 1
706 primRepSizeW VoidRep  = 0
707 \end{code}
708
709 %************************************************************************
710 %*                                                                      *
711 \subsection{TyCon Construction}
712 %*                                                                      *
713 %************************************************************************
714
715 Note: the TyCon constructors all take a Kind as one argument, even though
716 they could, in principle, work out their Kind from their other arguments.
717 But to do so they need functions from Types, and that makes a nasty
718 module mutual-recursion.  And they aren't called from many places.
719 So we compromise, and move their Kind calculation to the call site.
720
721 \begin{code}
722 -- | Given the name of the function type constructor and it's kind, create the
723 -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want 
724 -- this functionality
725 mkFunTyCon :: Name -> Kind -> TyCon
726 mkFunTyCon name kind 
727   = FunTyCon { 
728         tyConUnique = nameUnique name,
729         tyConName   = name,
730         tc_kind   = kind,
731         tyConArity  = 2
732     }
733
734 -- | This is the making of an algebraic 'TyCon'. Notably, you have to
735 -- pass in the generic (in the -XGenerics sense) information about the
736 -- type constructor - you can get hold of it easily (see Generics
737 -- module)
738 mkAlgTyCon :: Name
739            -> Kind              -- ^ Kind of the resulting 'TyCon'
740            -> [TyVar]           -- ^ 'TyVar's scoped over: see 'tyConTyVars'. 
741                                 --   Arity is inferred from the length of this list
742            -> [PredType]        -- ^ Stupid theta: see 'algTcStupidTheta'
743            -> AlgTyConRhs       -- ^ Information about dat aconstructors
744            -> TyConParent
745            -> RecFlag           -- ^ Is the 'TyCon' recursive?
746            -> Bool              -- ^ Does it have generic functions? See 'hasGenerics'
747            -> Bool              -- ^ Was the 'TyCon' declared with GADT syntax?
748            -> TyCon
749 mkAlgTyCon name kind tyvars stupid rhs parent is_rec gen_info gadt_syn
750   = AlgTyCon {  
751         tyConName        = name,
752         tyConUnique      = nameUnique name,
753         tc_kind          = kind,
754         tyConArity       = length tyvars,
755         tyConTyVars      = tyvars,
756         algTcStupidTheta = stupid,
757         algTcRhs         = rhs,
758         algTcParent      = ASSERT( okParent name parent ) parent,
759         algTcRec         = is_rec,
760         algTcGadtSyntax  = gadt_syn,
761         hasGenerics      = gen_info
762     }
763
764 -- | Simpler specialization of 'mkAlgTyCon' for classes
765 mkClassTyCon :: Name -> Kind -> [TyVar] -> AlgTyConRhs -> Class -> RecFlag -> TyCon
766 mkClassTyCon name kind tyvars rhs clas is_rec =
767   mkAlgTyCon name kind tyvars [] rhs (ClassTyCon clas) is_rec False False
768
769 mkTupleTyCon :: Name 
770              -> Kind    -- ^ Kind of the resulting 'TyCon'
771              -> Arity   -- ^ Arity of the tuple
772              -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
773              -> DataCon 
774              -> Boxity  -- ^ Whether the tuple is boxed or unboxed
775              -> Bool    -- ^ Does it have generic functions? See 'hasGenerics'
776              -> TyCon
777 mkTupleTyCon name kind arity tyvars con boxed gen_info
778   = TupleTyCon {
779         tyConUnique = nameUnique name,
780         tyConName = name,
781         tc_kind = kind,
782         tyConArity = arity,
783         tyConBoxed = boxed,
784         tyConTyVars = tyvars,
785         dataCon = con,
786         hasGenerics = gen_info
787     }
788
789 -- ^ Foreign-imported (.NET) type constructors are represented
790 -- as primitive, but /lifted/, 'TyCons' for now. They are lifted
791 -- because the Haskell type @T@ representing the (foreign) .NET
792 -- type @T@ is actually implemented (in ILX) as a @thunk<T>@
793 mkForeignTyCon :: Name 
794                -> Maybe FastString -- ^ Name of the foreign imported thing, maybe
795                -> Kind 
796                -> Arity 
797                -> TyCon
798 mkForeignTyCon name ext_name kind arity
799   = PrimTyCon {
800         tyConName    = name,
801         tyConUnique  = nameUnique name,
802         tc_kind    = kind,
803         tyConArity   = arity,
804         primTyConRep = PtrRep, -- they all do
805         isUnLifted   = False,
806         tyConExtName = ext_name
807     }
808
809
810 -- | Create an unlifted primitive 'TyCon', such as @Int#@
811 mkPrimTyCon :: Name  -> Kind -> Arity -> PrimRep -> TyCon
812 mkPrimTyCon name kind arity rep
813   = mkPrimTyCon' name kind arity rep True  
814
815 -- | Kind constructors
816 mkKindTyCon :: Name -> Kind -> TyCon
817 mkKindTyCon name kind
818   = mkPrimTyCon' name kind 0 VoidRep True  
819
820 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
821 mkLiftedPrimTyCon :: Name  -> Kind -> Arity -> PrimRep -> TyCon
822 mkLiftedPrimTyCon name kind arity rep
823   = mkPrimTyCon' name kind arity rep False
824
825 mkPrimTyCon' :: Name  -> Kind -> Arity -> PrimRep -> Bool -> TyCon
826 mkPrimTyCon' name kind arity rep is_unlifted
827   = PrimTyCon {
828         tyConName    = name,
829         tyConUnique  = nameUnique name,
830         tc_kind    = kind,
831         tyConArity   = arity,
832         primTyConRep = rep,
833         isUnLifted   = is_unlifted,
834         tyConExtName = Nothing
835     }
836
837 -- | Create a type synonym 'TyCon'
838 mkSynTyCon :: Name -> Kind -> [TyVar] -> SynTyConRhs -> TyConParent -> TyCon
839 mkSynTyCon name kind tyvars rhs parent
840   = SynTyCon {  
841         tyConName = name,
842         tyConUnique = nameUnique name,
843         tc_kind = kind,
844         tyConArity = length tyvars,
845         tyConTyVars = tyvars,
846         synTcRhs = rhs,
847         synTcParent = parent
848     }
849
850 -- | Create a coercion 'TyCon'
851 mkCoercionTyCon :: Name -> Arity 
852                 -> CoTyConDesc
853                 -> TyCon
854 mkCoercionTyCon name arity desc
855   = CoTyCon {
856         tyConName   = name,
857         tyConUnique = nameUnique name,
858         tyConArity  = arity,
859         coTcDesc    = desc }
860
861 mkAnyTyCon :: Name -> Kind -> TyCon
862 mkAnyTyCon name kind 
863   = AnyTyCon {  tyConName = name,
864                 tc_kind = kind,
865                 tyConUnique = nameUnique name }
866
867 -- | Create a super-kind 'TyCon'
868 mkSuperKindTyCon :: Name -> TyCon -- Super kinds always have arity zero
869 mkSuperKindTyCon name
870   = SuperKindTyCon {
871         tyConName = name,
872         tyConUnique = nameUnique name
873   }
874 \end{code}
875
876 \begin{code}
877 isFunTyCon :: TyCon -> Bool
878 isFunTyCon (FunTyCon {}) = True
879 isFunTyCon _             = False
880
881 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
882 isAbstractTyCon :: TyCon -> Bool
883 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
884 isAbstractTyCon _ = False
885
886 -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not algebraic
887 makeTyConAbstract :: TyCon -> TyCon
888 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
889 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
890
891 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
892 isPrimTyCon :: TyCon -> Bool
893 isPrimTyCon (PrimTyCon {}) = True
894 isPrimTyCon _              = False
895
896 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can only
897 -- be true for primitive and unboxed-tuple 'TyCon's
898 isUnLiftedTyCon :: TyCon -> Bool
899 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
900 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
901 isUnLiftedTyCon _                                       = False
902
903 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
904 -- @data@ or @newtype@ declaration
905 isAlgTyCon :: TyCon -> Bool
906 isAlgTyCon (AlgTyCon {})   = True
907 isAlgTyCon (TupleTyCon {}) = True
908 isAlgTyCon _               = False
909
910 isDataTyCon :: TyCon -> Bool
911 -- ^ Returns @True@ for data types that are /definitely/ represented by 
912 -- heap-allocated constructors.  These are scrutinised by Core-level 
913 -- @case@ expressions, and they get info tables allocated for them.
914 -- 
915 -- Generally, the function will be true for all @data@ types and false
916 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
917 -- not guarenteed to return @True@ in all cases that it could.
918 -- 
919 -- NB: for a data type family, only the /instance/ 'TyCon's
920 --     get an info table.  The family declaration 'TyCon' does not
921 isDataTyCon (AlgTyCon {algTcRhs = rhs})
922   = case rhs of
923         DataFamilyTyCon {}  -> False
924         DataTyCon {}  -> True
925         NewTyCon {}   -> False
926         AbstractTyCon -> False   -- We don't know, so return False
927 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
928 isDataTyCon _ = False
929
930 -- | Is this 'TyCon' that for a @newtype@
931 isNewTyCon :: TyCon -> Bool
932 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
933 isNewTyCon _                                   = False
934
935 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
936 -- into, and (possibly) a coercion from the representation type to the @newtype@.
937 -- Returns @Nothing@ if this is not possible.
938 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
939 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, 
940                                  algTcRhs = NewTyCon { nt_co = mb_co, 
941                                                        nt_rhs = rhs }})
942                            = Just (tvs, rhs, mb_co)
943 unwrapNewTyCon_maybe _     = Nothing
944
945 isProductTyCon :: TyCon -> Bool
946 -- | A /product/ 'TyCon' must both:
947 --
948 -- 1. Have /one/ constructor
949 -- 
950 -- 2. /Not/ be existential
951 -- 
952 -- However other than this there are few restrictions: they may be @data@ or @newtype@ 
953 -- 'TyCon's of any boxity and may even be recursive.
954 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
955                                     DataTyCon{ data_cons = [data_con] } 
956                                                 -> isVanillaDataCon data_con
957                                     NewTyCon {} -> True
958                                     _           -> False
959 isProductTyCon (TupleTyCon {})  = True   
960 isProductTyCon _                = False
961
962 -- | Is this a 'TyCon' representing a type synonym (@type@)?
963 isSynTyCon :: TyCon -> Bool
964 isSynTyCon (SynTyCon {}) = True
965 isSynTyCon _             = False
966
967 -- As for newtypes, it is in some contexts important to distinguish between
968 -- closed synonyms and synonym families, as synonym families have no unique
969 -- right hand side to which a synonym family application can expand.
970 --
971
972 isDecomposableTyCon :: TyCon -> Bool
973 -- True iff we can decompose (T a b c) into ((T a b) c)
974 -- Specifically NOT true of synonyms (open and otherwise) and coercions
975 isDecomposableTyCon (SynTyCon {}) = False
976 isDecomposableTyCon (CoTyCon {})  = False
977 isDecomposableTyCon _other        = True
978
979 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
980 isGadtSyntaxTyCon :: TyCon -> Bool
981 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
982 isGadtSyntaxTyCon _                                    = False
983
984 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
985 isEnumerationTyCon :: TyCon -> Bool
986 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
987 isEnumerationTyCon (TupleTyCon {tyConArity = arity}) = arity == 0
988 isEnumerationTyCon _                                                   = False
989
990 -- | Is this a 'TyCon', synonym or otherwise, that may have further instances appear?
991 isFamilyTyCon :: TyCon -> Bool
992 isFamilyTyCon (SynTyCon {synTcRhs = SynFamilyTyCon {}})  = True
993 isFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
994 isFamilyTyCon _ = False
995
996 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
997 isSynFamilyTyCon :: TyCon -> Bool
998 isSynFamilyTyCon (SynTyCon {synTcRhs = SynFamilyTyCon {}}) = True
999 isSynFamilyTyCon _ = False
1000
1001 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1002 isDataFamilyTyCon :: TyCon -> Bool
1003 isDataFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
1004 isDataFamilyTyCon _ = False
1005
1006 -- | Is this a synonym 'TyCon' that can have no further instances appear?
1007 isClosedSynTyCon :: TyCon -> Bool
1008 isClosedSynTyCon tycon = isSynTyCon tycon && not (isFamilyTyCon tycon)
1009
1010 -- | Injective 'TyCon's can be decomposed, so that
1011 --     T ty1 ~ T ty2  =>  ty1 ~ ty2
1012 isInjectiveTyCon :: TyCon -> Bool
1013 isInjectiveTyCon tc = not (isSynTyCon tc)
1014         -- Ultimately we may have injective associated types
1015         -- in which case this test will become more interesting
1016         --
1017         -- It'd be unusual to call isInjectiveTyCon on a regular H98
1018         -- type synonym, because you should probably have expanded it first
1019         -- But regardless, it's not injective!
1020
1021 -- | Are we able to extract informationa 'TyVar' to class argument list
1022 -- mappping from a given 'TyCon'?
1023 isTyConAssoc :: TyCon -> Bool
1024 isTyConAssoc tc = case tyConParent tc of
1025                      AssocFamilyTyCon {} -> True
1026                      _                   -> False
1027
1028 -- The unit tycon didn't used to be classed as a tuple tycon
1029 -- but I thought that was silly so I've undone it
1030 -- If it can't be for some reason, it should be a AlgTyCon
1031 isTupleTyCon :: TyCon -> Bool
1032 -- ^ Does this 'TyCon' represent a tuple?
1033 --
1034 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
1035 -- 'isTupleTyCon', becuase they are built as 'AlgTyCons'.  However they
1036 -- get spat into the interface file as tuple tycons, so I don't think
1037 -- it matters.
1038 isTupleTyCon (TupleTyCon {}) = True
1039 isTupleTyCon _               = False
1040
1041 -- | Is this the 'TyCon' for an unboxed tuple?
1042 isUnboxedTupleTyCon :: TyCon -> Bool
1043 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
1044 isUnboxedTupleTyCon _                                  = False
1045
1046 -- | Is this the 'TyCon' for a boxed tuple?
1047 isBoxedTupleTyCon :: TyCon -> Bool
1048 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
1049 isBoxedTupleTyCon _                                  = False
1050
1051 -- | Extract the boxity of the given 'TyCon', if it is a 'TupleTyCon'.
1052 -- Panics otherwise
1053 tupleTyConBoxity :: TyCon -> Boxity
1054 tupleTyConBoxity tc = tyConBoxed tc
1055
1056 -- | Is this a recursive 'TyCon'?
1057 isRecursiveTyCon :: TyCon -> Bool
1058 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
1059 isRecursiveTyCon _                                 = False
1060
1061 -- | Did this 'TyCon' originate from type-checking a .h*-boot file?
1062 isHiBootTyCon :: TyCon -> Bool
1063 -- Used for knot-tying in hi-boot files
1064 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
1065 isHiBootTyCon _                                     = False
1066
1067 -- | Is this the 'TyCon' of a foreign-imported type constructor?
1068 isForeignTyCon :: TyCon -> Bool
1069 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
1070 isForeignTyCon _                                   = False
1071
1072 -- | Is this a super-kind 'TyCon'?
1073 isSuperKindTyCon :: TyCon -> Bool
1074 isSuperKindTyCon (SuperKindTyCon {}) = True
1075 isSuperKindTyCon _                   = False
1076
1077 -- | Is this an AnyTyCon?
1078 isAnyTyCon :: TyCon -> Bool
1079 isAnyTyCon (AnyTyCon {}) = True
1080 isAnyTyCon _              = False
1081
1082 -- | Attempt to pull a 'TyCon' apart into the arity and 'coKindFun' of
1083 -- a coercion 'TyCon'. Returns @Nothing@ if the 'TyCon' is not of the
1084 -- appropriate kind
1085 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, CoTyConDesc)
1086 isCoercionTyCon_maybe (CoTyCon {tyConArity = ar, coTcDesc = desc}) 
1087   = Just (ar, desc)
1088 isCoercionTyCon_maybe _ = Nothing
1089
1090 -- | Is this a 'TyCon' that represents a coercion?
1091 isCoercionTyCon :: TyCon -> Bool
1092 isCoercionTyCon (CoTyCon {}) = True
1093 isCoercionTyCon _            = False
1094
1095 -- | Identifies implicit tycons that, in particular, do not go into interface
1096 -- files (because they are implicitly reconstructed when the interface is
1097 -- read).
1098 --
1099 -- Note that:
1100 --
1101 -- * Associated families are implicit, as they are re-constructed from
1102 --   the class declaration in which they reside, and 
1103 --
1104 -- * Family instances are /not/ implicit as they represent the instance body
1105 --   (similar to a @dfun@ does that for a class instance).
1106 isImplicitTyCon :: TyCon -> Bool
1107 isImplicitTyCon tycon | isTyConAssoc tycon           = True
1108                       | isSynTyCon tycon             = False
1109                       | isAlgTyCon tycon             = isClassTyCon tycon ||
1110                                                        isTupleTyCon tycon
1111 isImplicitTyCon _other                               = True
1112         -- catches: FunTyCon, PrimTyCon, 
1113         -- CoTyCon, SuperKindTyCon
1114 \end{code}
1115
1116
1117 -----------------------------------------------
1118 --      Expand type-constructor applications
1119 -----------------------------------------------
1120
1121 \begin{code}
1122 tcExpandTyCon_maybe, coreExpandTyCon_maybe 
1123         :: TyCon 
1124         -> [Type]                       -- ^ Arguments to 'TyCon'
1125         -> Maybe ([(TyVar,Type)],       
1126                   Type,                 
1127                   [Type])               -- ^ Returns a 'TyVar' substitution, the body type
1128                                         -- of the synonym (not yet substituted) and any arguments
1129                                         -- remaining from the application
1130
1131 -- ^ Used to create the view the /typechecker/ has on 'TyCon's. We expand (closed) synonyms only, cf. 'coreExpandTyCon_maybe'
1132 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs, 
1133                                synTcRhs = SynonymTyCon rhs }) tys
1134    = expand tvs rhs tys
1135 tcExpandTyCon_maybe _ _ = Nothing
1136
1137 ---------------
1138
1139 -- ^ Used to create the view /Core/ has on 'TyCon's. We expand not only closed synonyms like 'tcExpandTyCon_maybe',
1140 -- but also non-recursive @newtype@s
1141 coreExpandTyCon_maybe (AlgTyCon {
1142          algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
1143    = case etad_rhs of   -- Don't do this in the pattern match, lest we accidentally
1144                         -- match the etad_rhs of a *recursive* newtype
1145         (tvs,rhs) -> expand tvs rhs tys
1146
1147 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
1148
1149
1150 ----------------
1151 expand  :: [TyVar] -> Type                      -- Template
1152         -> [Type]                               -- Args
1153         -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
1154 expand tvs rhs tys
1155   = case n_tvs `compare` length tys of
1156         LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
1157         EQ -> Just (tvs `zip` tys, rhs, [])
1158         GT -> Nothing
1159    where
1160      n_tvs = length tvs
1161 \end{code}
1162
1163 \begin{code}
1164 -- | Does this 'TyCon' have any generic to\/from functions available? See also 'hasGenerics'
1165 tyConHasGenerics :: TyCon -> Bool
1166 tyConHasGenerics (AlgTyCon {hasGenerics = hg})   = hg
1167 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
1168 tyConHasGenerics _                               = False        -- Synonyms
1169
1170 tyConKind :: TyCon -> Kind
1171 tyConKind (FunTyCon   { tc_kind = k }) = k
1172 tyConKind (AlgTyCon   { tc_kind = k }) = k
1173 tyConKind (TupleTyCon { tc_kind = k }) = k
1174 tyConKind (SynTyCon   { tc_kind = k }) = k
1175 tyConKind (PrimTyCon  { tc_kind = k }) = k
1176 tyConKind (AnyTyCon   { tc_kind = k }) = k
1177 tyConKind tc = pprPanic "tyConKind" (ppr tc)    -- SuperKindTyCon and CoTyCon
1178
1179 tyConHasKind :: TyCon -> Bool
1180 tyConHasKind (SuperKindTyCon {}) = False
1181 tyConHasKind (CoTyCon {})        = False
1182 tyConHasKind _                   = True
1183
1184 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no constructors
1185 -- could be found
1186 tyConDataCons :: TyCon -> [DataCon]
1187 -- It's convenient for tyConDataCons to return the
1188 -- empty list for type synonyms etc
1189 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1190
1191 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' is the
1192 -- sort that can have any constructors (note: this does not include abstract algebraic types)
1193 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1194 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
1195 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }})    = Just [con]
1196 tyConDataCons_maybe (TupleTyCon {dataCon = con})                           = Just [con]
1197 tyConDataCons_maybe _                                                      = Nothing
1198
1199 -- | Determine the number of value constructors a 'TyCon' has. Panics if the 'TyCon'
1200 -- is not algebraic or a tuple
1201 tyConFamilySize  :: TyCon -> Int
1202 tyConFamilySize (AlgTyCon   {algTcRhs = DataTyCon {data_cons = cons}}) = 
1203   length cons
1204 tyConFamilySize (AlgTyCon   {algTcRhs = NewTyCon {}})        = 1
1205 tyConFamilySize (AlgTyCon   {algTcRhs = DataFamilyTyCon {}}) = 0
1206 tyConFamilySize (TupleTyCon {})                              = 1
1207 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
1208
1209 -- | Extract an 'AlgTyConRhs' with information about data constructors from an algebraic or tuple
1210 -- 'TyCon'. Panics for any other sort of 'TyCon'
1211 algTyConRhs :: TyCon -> AlgTyConRhs
1212 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1213 algTyConRhs (TupleTyCon {dataCon = con, tyConArity = arity})
1214     = DataTyCon { data_cons = [con], is_enum = arity == 0 }
1215 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1216 \end{code}
1217
1218 \begin{code}
1219 -- | Extract the bound type variables and type expansion of a type synonym 'TyCon'. Panics if the
1220 -- 'TyCon' is not a synonym
1221 newTyConRhs :: TyCon -> ([TyVar], Type)
1222 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
1223 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
1224
1225 -- | Extract the bound type variables and type expansion of an eta-contracted type synonym 'TyCon'.
1226 -- Panics if the 'TyCon' is not a synonym
1227 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
1228 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
1229 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
1230
1231 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to construct something
1232 -- with the @newtype@s type from its representation type (right hand side). If the supplied 'TyCon'
1233 -- is not a @newtype@, returns @Nothing@
1234 newTyConCo_maybe :: TyCon -> Maybe TyCon
1235 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
1236 newTyConCo_maybe _                                               = Nothing
1237
1238 -- | Find the primitive representation of a 'TyCon'
1239 tyConPrimRep :: TyCon -> PrimRep
1240 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
1241 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
1242 \end{code}
1243
1244 \begin{code}
1245 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context to the left of
1246 -- an algebraic type declaration, e.g. @Eq a@ in the declaration @data Eq a => T a ...@
1247 tyConStupidTheta :: TyCon -> [PredType]
1248 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
1249 tyConStupidTheta (TupleTyCon {})                        = []
1250 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
1251 \end{code}
1252
1253 \begin{code}
1254 -- | Extract the 'TyVar's bound by a type synonym and the corresponding (unsubstituted) right hand side.
1255 -- If the given 'TyCon' is not a type synonym, panics
1256 synTyConDefn :: TyCon -> ([TyVar], Type)
1257 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty}) 
1258   = (tyvars, ty)
1259 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
1260
1261 -- | Extract the information pertaining to the right hand side of a type synonym (@type@) declaration. Panics
1262 -- if the given 'TyCon' is not a type synonym
1263 synTyConRhs :: TyCon -> SynTyConRhs
1264 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
1265 synTyConRhs tc                          = pprPanic "synTyConRhs" (ppr tc)
1266
1267 -- | Find the expansion of the type synonym represented by the given 'TyCon'. The free variables of this
1268 -- type will typically include those 'TyVar's bound by the 'TyCon'. Panics if the 'TyCon' is not that of
1269 -- a type synonym
1270 synTyConType :: TyCon -> Type
1271 synTyConType tc = case synTcRhs tc of
1272                     SynonymTyCon t -> t
1273                     _              -> pprPanic "synTyConType" (ppr tc)
1274 \end{code}
1275
1276 \begin{code}
1277 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ type with one
1278 -- alternative, a tuple type or a @newtype@ then that constructor is returned. If the 'TyCon'
1279 -- has more than one constructor, or represents a primitive or function type constructor then
1280 -- @Nothing@ is returned. In any other case, the function panics
1281 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1282 tyConSingleDataCon_maybe (TupleTyCon {dataCon = c})                            = Just c
1283 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = [c] }}) = Just c
1284 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})     = Just c
1285 tyConSingleDataCon_maybe _                                                     = Nothing
1286 \end{code}
1287
1288 \begin{code}
1289 -- | Is this 'TyCon' that for a class instance?
1290 isClassTyCon :: TyCon -> Bool
1291 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
1292 isClassTyCon _                                       = False
1293
1294 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1295 -- Otherwise returns @Nothing@
1296 tyConClass_maybe :: TyCon -> Maybe Class
1297 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
1298 tyConClass_maybe _                                          = Nothing
1299
1300 ----------------------------------------------------------------------------
1301 tyConParent :: TyCon -> TyConParent
1302 tyConParent (AlgTyCon {algTcParent = parent}) = parent
1303 tyConParent (SynTyCon {synTcParent = parent}) = parent
1304 tyConParent _                                 = NoParentTyCon
1305
1306 -- | Is this 'TyCon' that for a family instance, be that for a synonym or an
1307 -- algebraic family instance?
1308 isFamInstTyCon :: TyCon -> Bool
1309 isFamInstTyCon tc = case tyConParent tc of
1310                       FamInstTyCon {} -> True
1311                       _               -> False
1312
1313 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], TyCon)
1314 tyConFamInstSig_maybe tc
1315   = case tyConParent tc of
1316       FamInstTyCon f ts co_tc -> Just (f, ts, co_tc)
1317       _                       -> Nothing
1318
1319 -- | If this 'TyCon' is that of a family instance, return the family in question
1320 -- and the instance types. Otherwise, return @Nothing@
1321 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1322 tyConFamInst_maybe tc
1323   = case tyConParent tc of
1324       FamInstTyCon f ts _ -> Just (f, ts)
1325       _                   -> Nothing
1326
1327 -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which represents 
1328 -- a coercion identifying the representation type with the type instance family.
1329 -- Otherwise, return @Nothing@
1330 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
1331 tyConFamilyCoercion_maybe tc
1332   = case tyConParent tc of
1333       FamInstTyCon _ _ co -> Just co
1334       _                   -> Nothing
1335 \end{code}
1336
1337
1338 %************************************************************************
1339 %*                                                                      *
1340 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1341 %*                                                                      *
1342 %************************************************************************
1343
1344 @TyCon@s are compared by comparing their @Unique@s.
1345
1346 The strictness analyser needs @Ord@. It is a lexicographic order with
1347 the property @(a<=b) || (b<=a)@.
1348
1349 \begin{code}
1350 instance Eq TyCon where
1351     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
1352     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
1353
1354 instance Ord TyCon where
1355     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
1356     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
1357     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
1358     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
1359     compare a b = getUnique a `compare` getUnique b
1360
1361 instance Uniquable TyCon where
1362     getUnique tc = tyConUnique tc
1363
1364 instance Outputable CoTyConDesc where
1365     ppr CoSym    = ptext (sLit "SYM")
1366     ppr CoTrans  = ptext (sLit "TRANS")
1367     ppr CoLeft   = ptext (sLit "LEFT")
1368     ppr CoRight  = ptext (sLit "RIGHT")
1369     ppr CoCsel1  = ptext (sLit "CSEL1")
1370     ppr CoCsel2  = ptext (sLit "CSEL2")
1371     ppr CoCselR  = ptext (sLit "CSELR")
1372     ppr CoInst   = ptext (sLit "INST")
1373     ppr CoUnsafe = ptext (sLit "UNSAFE")
1374     ppr (CoAxiom {}) = ptext (sLit "AXIOM")
1375
1376 instance Outputable TyCon where
1377     ppr tc  = ppr (getName tc) 
1378
1379 instance NamedThing TyCon where
1380     getName = tyConName
1381
1382 instance Data.Typeable TyCon where
1383     typeOf _ = Data.mkTyConApp (Data.mkTyCon "TyCon") []
1384
1385 instance Data.Data TyCon where
1386     -- don't traverse?
1387     toConstr _   = abstractConstr "TyCon"
1388     gunfold _ _  = error "gunfold"
1389     dataTypeOf _ = mkNoRepType "TyCon"
1390 \end{code}