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