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