root/compiler/types/TyCon.lhs

Revision 0fe0c58ee9758f1606ccd12fd04121a08488fb9a, 58.8 KB (checked in by Simon Peyton Jones <simonpj@…>, 10 days ago)

Applied lunaris's patch to allow promoted types and rich kinds in Template Haskell

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