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