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