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