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