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