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