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