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