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