Use OPTIONS rather than OPTIONS_GHC for pragmas
[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 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/CodingStyle#Warnings
14 -- for details
15
16 module TyCon(
17         TyCon, FieldLabel,
18
19         PrimRep(..),
20         tyConPrimRep,
21         sizeofPrimRep,
22
23         AlgTyConRhs(..), visibleDataCons, 
24         TyConParent(..), 
25         SynTyConRhs(..),
26
27         isFunTyCon, isUnLiftedTyCon, isProductTyCon, 
28         isAlgTyCon, isDataTyCon, 
29         isNewTyCon, unwrapNewTyCon_maybe, 
30         isSynTyCon, isClosedSynTyCon, isOpenSynTyCon,
31         isPrimTyCon, 
32
33         isEnumerationTyCon, isGadtSyntaxTyCon, isOpenTyCon,
34         assocTyConArgPoss_maybe, isTyConAssoc, setTyConArgPoss,
35         isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, tupleTyConBoxity,
36         isRecursiveTyCon, newTyConRep, newTyConRhs, newTyConCo_maybe,
37         isHiBootTyCon, isSuperKindTyCon,
38         isCoercionTyCon_maybe, isCoercionTyCon,
39         isImplicitTyCon,
40
41         tcExpandTyCon_maybe, coreExpandTyCon_maybe,
42
43         makeTyConAbstract, isAbstractTyCon,
44
45         mkForeignTyCon, isForeignTyCon,
46
47         mkAlgTyCon,
48         mkClassTyCon,
49         mkFunTyCon,
50         mkPrimTyCon,
51         mkVoidPrimTyCon,
52         mkLiftedPrimTyCon,
53         mkTupleTyCon,
54         mkSynTyCon,
55         mkSuperKindTyCon,
56         mkCoercionTyCon,
57
58         tyConName,
59         tyConKind,
60         tyConUnique,
61         tyConTyVars,
62         algTyConRhs, tyConDataCons, tyConDataCons_maybe, tyConFamilySize,
63         tyConSelIds,
64         tyConStupidTheta,
65         tyConArity,
66         isClassTyCon, tyConClass_maybe,
67         isFamInstTyCon, tyConFamInst_maybe, tyConFamilyCoercion_maybe,
68         synTyConDefn, synTyConRhs, synTyConType, synTyConResKind,
69         tyConExtName,           -- External name for foreign types
70
71         maybeTyConSingleCon,
72
73         -- Generics
74         tyConHasGenerics
75 ) where
76
77 #include "HsVersions.h"
78
79 import {-# SOURCE #-} TypeRep ( Kind, Type, PredType )
80 import {-# SOURCE #-} DataCon ( DataCon, isVanillaDataCon )
81
82 import Var
83 import Class
84 import BasicTypes
85 import Name
86 import PrelNames
87 import Maybes
88 import Outputable
89 import FastString
90 import Constants
91 \end{code}
92
93 %************************************************************************
94 %*                                                                      *
95 \subsection{The data type}
96 %*                                                                      *
97 %************************************************************************
98
99 \begin{code}
100 data TyCon
101   = FunTyCon {
102         tyConUnique :: Unique,
103         tyConName   :: Name,
104         tyConKind   :: Kind,
105         tyConArity  :: Arity
106     }
107
108
109   | AlgTyCon {          -- Data type, and newtype decls.
110                         -- All lifted, all boxed
111         tyConUnique :: Unique,
112         tyConName   :: Name,
113         tyConKind   :: Kind,
114         tyConArity  :: Arity,
115
116         tyConTyVars :: [TyVar],         -- Scopes over (a) the algTcStupidTheta
117                                         --             (b) the cached types in
118                                         --                 algTyConRhs.NewTyCon
119                                         --             (c) the family instance
120                                         --                 types if present
121                                         -- But not over the data constructors
122
123         algTcSelIds :: [Id],            -- Its record selectors (empty if none)
124
125         algTcGadtSyntax  :: Bool,       -- True <=> the data type was declared using GADT syntax
126                                         -- That doesn't mean it's a true GADT; only that the "where"
127                                         --      form was used. This field is used only to guide
128                                         --      pretty-printinng
129         algTcStupidTheta :: [PredType], -- The "stupid theta" for the data type
130                                         -- (always empty for GADTs)
131
132         algTcRhs :: AlgTyConRhs,        -- Data constructors in here
133
134         algTcRec :: RecFlag,            -- Tells whether the data type is part
135                                         -- of a mutually-recursive group or not
136
137         hasGenerics :: Bool,            -- True <=> generic to/from functions are available
138                                         -- (in the exports of the data type's source module)
139
140         algTcParent :: TyConParent      -- Gives the class or family tycon for
141                                         -- derived tycons representing classes
142                                         -- or family instances, respectively.
143     }
144
145   | TupleTyCon {
146         tyConUnique :: Unique,
147         tyConName   :: Name,
148         tyConKind   :: Kind,
149         tyConArity  :: Arity,
150         tyConBoxed  :: Boxity,
151         tyConTyVars :: [TyVar],
152         dataCon     :: DataCon,
153         hasGenerics :: Bool
154     }
155
156   | SynTyCon {
157         tyConUnique  :: Unique,
158         tyConName    :: Name,
159         tyConKind    :: Kind,
160         tyConArity   :: Arity,
161
162         tyConTyVars  :: [TyVar],        -- Bound tyvars
163
164         synTcRhs     :: SynTyConRhs,    -- Expanded type in here
165
166         synTcParent  :: TyConParent     -- Gives the family tycon of
167                                         -- representation tycons of family
168                                         -- instances
169
170     }
171
172   | PrimTyCon {                 -- Primitive types; cannot be defined in Haskell
173                                 -- Now includes foreign-imported types
174                                 -- Also includes Kinds
175         tyConUnique   :: Unique,
176         tyConName     :: Name,
177         tyConKind     :: Kind,
178         tyConArity    :: Arity,         -- SLPJ Oct06: I'm not sure what the significance
179                                         --             of the arity of a primtycon is!
180
181         primTyConRep  :: PrimRep,
182                         -- Many primitive tycons are unboxed, but some are
183                         -- boxed (represented by pointers). The CgRep tells.
184
185         isUnLifted   :: Bool,           -- Most primitive tycons are unlifted, 
186                                         -- but foreign-imported ones may not be
187         tyConExtName :: Maybe FastString        -- Just xx for foreign-imported types
188     }
189
190   | CoercionTyCon {     -- E.g. (:=:), sym, trans, left, right
191                         -- INVARIANT: coercions are always fully applied
192         tyConUnique :: Unique,
193         tyConName   :: Name,
194         tyConArity  :: Arity,
195         coKindFun   :: [Type] -> (Type,Type)
196     }           -- INVARAINT: coKindFun is always applied to exactly 'arity' args
197                 -- E.g. for trans (c1 :: ta=tb) (c2 :: tb=tc), the coKindFun returns 
198                 --      the kind as a pair of types: (ta,tc)
199         
200   | SuperKindTyCon {    -- Super Kinds, TY (box) and CO (diamond).
201                         -- They have no kind; and arity zero
202         tyConUnique :: Unique,
203         tyConName   :: Name
204     }
205
206 type FieldLabel = Name
207
208 -- Right hand sides of type constructors for algebraic types
209 --
210 data AlgTyConRhs
211
212   -- We know nothing about this data type, except that it's represented by a
213   -- pointer.  Used when we export a data type abstractly into an hi file.
214   --
215   = AbstractTyCon
216
217   -- The constructor represents an open family without a fixed right hand
218   -- side.  Additional instances can appear at any time.
219   -- 
220   -- These are introduced by either a top level decl:
221   --    data T a :: *
222   -- or an assoicated data type decl, in a class decl:
223   --    class C a b where
224   --      data T b :: *
225
226   | OpenTyCon {
227
228       otArgPoss   :: Maybe [Int]
229         -- Nothing <=> top-level indexed type family
230         -- Just ns <=> associated (not toplevel) family
231         --   In the latter case, for each tyvar in the AT decl, 'ns' gives the
232         --   position of that tyvar in the class argument list (starting from 0).
233         --   NB: Length is less than tyConArity iff higher kind signature.
234         
235     }
236
237   | DataTyCon {
238         data_cons :: [DataCon],
239                         -- The constructors; can be empty if the user declares
240                         --   the type to have no constructors
241                         -- INVARIANT: Kept in order of increasing tag
242                         --        (see the tag assignment in DataCon.mkDataCon)
243         is_enum :: Bool         -- Cached: True <=> an enumeration type
244     }                   --         Includes data types with no constructors.
245
246   | NewTyCon {
247         data_con :: DataCon,    -- The unique constructor; it has no existentials
248
249         nt_rhs :: Type,         -- Cached: the argument type of the constructor
250                                 --  = the representation type of the tycon
251                                 -- The free tyvars of this type are the tyConTyVars
252       
253         nt_co :: Maybe TyCon,   -- The coercion used to create the newtype
254                                 -- from the representation
255                                 -- optional for non-recursive newtypes
256                                 -- See Note [Newtype coercions]
257
258         nt_etad_rhs :: ([TyVar], Type) ,
259                         -- The same again, but this time eta-reduced
260                         -- hence the [TyVar] which may be shorter than the declared 
261                         -- arity of the TyCon.  See Note [Newtype eta]
262
263         nt_rep :: Type  -- Cached: the *ultimate* representation type
264                         -- By 'ultimate' I mean that the top-level constructor
265                         -- of the rep type is not itself a newtype or type synonym.
266                         -- The rep type isn't entirely simple:
267                         --  for a recursive newtype we pick () as the rep type
268                         --      newtype T = MkT T
269                         -- 
270                         -- This one does not need to be eta reduced; hence its
271                         -- free type variables are conveniently tyConTyVars
272                         -- Thus:
273                         --      newtype T a = MkT [(a,Int)]
274                         -- The rep type is [(a,Int)]
275                         -- NB: the rep type isn't necessarily the original RHS of the
276                         --     newtype decl, because the rep type looks through other
277     }                   --     newtypes.
278
279 visibleDataCons :: AlgTyConRhs -> [DataCon]
280 visibleDataCons AbstractTyCon                 = []
281 visibleDataCons OpenTyCon {}                  = []
282 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
283 visibleDataCons (NewTyCon{ data_con = c })    = [c]
284
285 -- Both type classes as well as family instances imply implicit
286 -- type constructors.  These implicit type constructors refer to their parent
287 -- structure (ie, the class or family from which they derive) using a type of
288 -- the following form.  We use `TyConParent' for both algebraic and synonym 
289 -- types, but the variant `ClassTyCon' will only be used by algebraic tycons.
290
291 data TyConParent 
292   = NoParentTyCon       -- An ordinary type constructor has no parent.
293
294   | ClassTyCon          -- Type constructors representing a class dictionary.
295         Class           -- INVARIANT: the classTyCon of this Class is the current tycon
296
297   | FamilyTyCon         -- Type constructors representing an instance of a type
298         TyCon           --   The type family
299         [Type]          --   Instance types; free variables are the tyConTyVars
300                         --      of the current TyCon (not the family one)
301                         --      INVARIANT: the number of types matches the arity 
302                         --                 of the family tycon
303         TyCon           --   A CoercionTyCon identifying the representation 
304                         --     type with the type instance family.  
305                         --      c.f. Note [Newtype coercions]
306
307         --
308         -- E.g.  data intance T [a] = ...
309         -- gives a representation tycon:
310         --      data :R7T a = ...
311         --      axiom co a :: T [a] ~ :R7T a
312         -- with :R7T's algTcParent = FamilyTyCon T [a] co
313
314 okParent :: Name -> TyConParent -> Bool -- Checks invariants
315 okParent tc_name NoParentTyCon                  = True
316 okParent tc_name (ClassTyCon cls)               = tyConName (classTyCon cls) == tc_name
317 okParent tc_name (FamilyTyCon fam_tc tys co_tc) = tyConArity fam_tc == length tys
318
319 --------------------
320 data SynTyConRhs
321   = OpenSynTyCon Kind           -- Type family: *result* kind given
322                  (Maybe [Int])  -- for associated families: for each tyvars in
323                                 -- the AT decl, gives the position of that
324                                 -- tyvar in the class argument list (starting
325                                 -- from 0). 
326                                 -- NB: Length is less than tyConArity
327                                 --     if higher kind signature.
328
329   | SynonymTyCon Type   -- Mentioning head type vars.  Acts as a template for
330                         --  the expansion when the tycon is applied to some
331                         --  types.
332 \end{code}
333
334 Note [Newtype coercions]
335 ~~~~~~~~~~~~~~~~~~~~~~~~
336
337 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
338 which is used for coercing from the representation type of the
339 newtype, to the newtype itself. For example,
340
341    newtype T a = MkT (a -> a)
342
343 the NewTyCon for T will contain nt_co = CoT where CoT t : T t :=: t ->
344 t.  This TyCon is a CoercionTyCon, so it does not have a kind on its
345 own; it basically has its own typing rule for the fully-applied
346 version.  If the newtype T has k type variables then CoT has arity at
347 most k.  In the case that the right hand side is a type application
348 ending with the same type variables as the left hand side, we
349 "eta-contract" the coercion.  So if we had
350
351    newtype S a = MkT [a]
352
353 then we would generate the arity 0 coercion CoS : S :=: [].  The
354 primary reason we do this is to make newtype deriving cleaner.
355
356 In the paper we'd write
357         axiom CoT : (forall t. T t) :=: (forall t. [t])
358 and then when we used CoT at a particular type, s, we'd say
359         CoT @ s
360 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
361
362 But in GHC we instead make CoT into a new piece of type syntax, CoercionTyCon,
363 (like instCoercionTyCon, symCoercionTyCon etc), which must always
364 be saturated, but which encodes as
365         TyConApp CoT [s]
366 In the vocabulary of the paper it's as if we had axiom declarations
367 like
368         axiom CoT t :  T t :=: [t]
369
370 Note [Newtype eta]
371 ~~~~~~~~~~~~~~~~~~
372 Consider
373         newtype Parser m a = MkParser (Foogle m a)
374 Are these two types equal (to Core)?
375         Monad (Parser m) 
376         Monad (Foogle m)
377 Well, yes.  But to see that easily we eta-reduce the RHS type of
378 Parser, in this case to ([], Froogle), so that even unsaturated applications
379 of Parser will work right.  This eta reduction is done when the type 
380 constructor is built, and cached in NewTyCon.  The cached field is
381 only used in coreExpandTyCon_maybe.
382  
383 Here's an example that I think showed up in practice
384 Source code:
385         newtype T a = MkT [a]
386         newtype Foo m = MkFoo (forall a. m a -> Int)
387
388         w1 :: Foo []
389         w1 = ...
390         
391         w2 :: Foo T
392         w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
393
394 After desugaring, and discading the data constructors for the newtypes,
395 we get:
396         w2 :: Foo T
397         w2 = w1
398 And now Lint complains unless Foo T == Foo [], and that requires T==[]
399
400
401 Note [Indexed data types] (aka data type families)
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
403    See also Note [Wrappers for data instance tycons] in MkId.lhs
404
405 Consider
406         data family T a
407
408         data instance T (b,c) where
409           T1 :: b -> c -> T (b,c)
410
411 Then
412   * T is the "family TyCon"
413
414   * We make "representation TyCon" :R1T, thus:
415         data :R1T b c where
416           T1 :: forall b c. b -> c -> :R1T b c
417
418   * It has a top-level coercion connecting it to the family TyCon
419
420         axiom :Co:R1T b c : T (b,c) ~ :R1T b c
421
422   * The data contructor T1 has a wrapper (which is what the source-level
423     "T1" invokes):
424
425         $WT1 :: forall b c. b -> c -> T (b,c)
426         $WT1 b c (x::b) (y::c) = T1 b c x y `cast` sym (:Co:R1T b c)
427
428   * The representation TyCon :R1T has an AlgTyConParent of
429
430         FamilyTyCon T [(b,c)] :Co:R1T
431
432
433
434 %************************************************************************
435 %*                                                                      *
436 \subsection{PrimRep}
437 %*                                                                      *
438 %************************************************************************
439
440 A PrimRep is an abstraction of a type.  It contains information that
441 the code generator needs in order to pass arguments, return results,
442 and store values of this type.
443
444 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
445 MachRep (see cmm/MachOp), although each of these types has a distinct
446 and clearly defined purpose:
447
448   - A PrimRep is a CgRep + information about signedness + information
449     about primitive pointers (AddrRep).  Signedness and primitive
450     pointers are required when passing a primitive type to a foreign
451     function, but aren't needed for call/return conventions of Haskell
452     functions.
453
454   - A MachRep is a basic machine type (non-void, doesn't contain
455     information on pointerhood or signedness, but contains some
456     reps that don't have corresponding Haskell types).
457
458 \begin{code}
459 data PrimRep
460   = VoidRep
461   | PtrRep
462   | IntRep              -- signed, word-sized
463   | WordRep             -- unsinged, word-sized
464   | Int64Rep            -- signed, 64 bit (32-bit words only)
465   | Word64Rep           -- unsigned, 64 bit (32-bit words only)
466   | AddrRep             -- a pointer, but not to a Haskell value
467   | FloatRep
468   | DoubleRep
469
470 -- Size of a PrimRep, in bytes
471 sizeofPrimRep :: PrimRep -> Int
472 sizeofPrimRep IntRep   = wORD_SIZE
473 sizeofPrimRep WordRep  = wORD_SIZE
474 sizeofPrimRep Int64Rep = wORD64_SIZE
475 sizeofPrimRep Word64Rep= wORD64_SIZE
476 sizeofPrimRep FloatRep = 4
477 sizeofPrimRep DoubleRep= 8
478 sizeofPrimRep AddrRep  = wORD_SIZE
479 sizeofPrimRep PtrRep   = wORD_SIZE
480 sizeofPrimRep VoidRep  = 0
481 \end{code}
482
483 %************************************************************************
484 %*                                                                      *
485 \subsection{TyCon Construction}
486 %*                                                                      *
487 %************************************************************************
488
489 Note: the TyCon constructors all take a Kind as one argument, even though
490 they could, in principle, work out their Kind from their other arguments.
491 But to do so they need functions from Types, and that makes a nasty
492 module mutual-recursion.  And they aren't called from many places.
493 So we compromise, and move their Kind calculation to the call site.
494
495 \begin{code}
496 mkFunTyCon :: Name -> Kind -> TyCon
497 mkFunTyCon name kind 
498   = FunTyCon { 
499         tyConUnique = nameUnique name,
500         tyConName   = name,
501         tyConKind   = kind,
502         tyConArity  = 2
503     }
504
505 -- This is the making of a TyCon. Just the same as the old mkAlgTyCon,
506 -- but now you also have to pass in the generic information about the type
507 -- constructor - you can get hold of it easily (see Generics module)
508 mkAlgTyCon name kind tyvars stupid rhs sel_ids parent is_rec gen_info gadt_syn
509   = AlgTyCon {  
510         tyConName        = name,
511         tyConUnique      = nameUnique name,
512         tyConKind        = kind,
513         tyConArity       = length tyvars,
514         tyConTyVars      = tyvars,
515         algTcStupidTheta = stupid,
516         algTcRhs         = rhs,
517         algTcSelIds      = sel_ids,
518         algTcParent      = ASSERT( okParent name parent ) parent,
519         algTcRec         = is_rec,
520         algTcGadtSyntax  = gadt_syn,
521         hasGenerics = gen_info
522     }
523
524 mkClassTyCon name kind tyvars rhs clas is_rec =
525   mkAlgTyCon name kind tyvars [] rhs [] (ClassTyCon clas) is_rec False False
526
527 mkTupleTyCon name kind arity tyvars con boxed gen_info
528   = TupleTyCon {
529         tyConUnique = nameUnique name,
530         tyConName = name,
531         tyConKind = kind,
532         tyConArity = arity,
533         tyConBoxed = boxed,
534         tyConTyVars = tyvars,
535         dataCon = con,
536         hasGenerics = gen_info
537     }
538
539 -- Foreign-imported (.NET) type constructors are represented
540 -- as primitive, but *lifted*, TyCons for now. They are lifted
541 -- because the Haskell type T representing the (foreign) .NET
542 -- type T is actually implemented (in ILX) as a thunk<T>
543 mkForeignTyCon name ext_name kind arity
544   = PrimTyCon {
545         tyConName    = name,
546         tyConUnique  = nameUnique name,
547         tyConKind    = kind,
548         tyConArity   = arity,
549         primTyConRep = PtrRep, -- they all do
550         isUnLifted   = False,
551         tyConExtName = ext_name
552     }
553
554
555 -- most Prim tycons are lifted
556 mkPrimTyCon name kind arity rep
557   = mkPrimTyCon' name kind arity rep True  
558
559 mkVoidPrimTyCon name kind arity 
560   = mkPrimTyCon' name kind arity VoidRep True  
561
562 -- but RealWorld is lifted
563 mkLiftedPrimTyCon name kind arity rep
564   = mkPrimTyCon' name kind arity rep False
565
566 mkPrimTyCon' name kind arity rep is_unlifted
567   = PrimTyCon {
568         tyConName    = name,
569         tyConUnique  = nameUnique name,
570         tyConKind    = kind,
571         tyConArity   = arity,
572         primTyConRep = rep,
573         isUnLifted   = is_unlifted,
574         tyConExtName = Nothing
575     }
576
577 mkSynTyCon name kind tyvars rhs parent
578   = SynTyCon {  
579         tyConName = name,
580         tyConUnique = nameUnique name,
581         tyConKind = kind,
582         tyConArity = length tyvars,
583         tyConTyVars = tyvars,
584         synTcRhs = rhs,
585         synTcParent = parent
586     }
587
588 mkCoercionTyCon name arity kindRule
589   = CoercionTyCon {
590         tyConName = name,
591         tyConUnique = nameUnique name,
592         tyConArity = arity,
593         coKindFun = kindRule
594     }
595
596 -- Super kinds always have arity zero
597 mkSuperKindTyCon name
598   = SuperKindTyCon {
599         tyConName = name,
600         tyConUnique = nameUnique name
601   }
602 \end{code}
603
604 \begin{code}
605 isFunTyCon :: TyCon -> Bool
606 isFunTyCon (FunTyCon {}) = True
607 isFunTyCon _             = False
608
609 isAbstractTyCon :: TyCon -> Bool
610 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
611 isAbstractTyCon _ = False
612
613 makeTyConAbstract :: TyCon -> TyCon
614 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
615 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
616
617 isPrimTyCon :: TyCon -> Bool
618 isPrimTyCon (PrimTyCon {}) = True
619 isPrimTyCon _              = False
620
621 isUnLiftedTyCon :: TyCon -> Bool
622 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
623 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
624 isUnLiftedTyCon _                                       = False
625
626 -- isAlgTyCon returns True for both @data@ and @newtype@
627 isAlgTyCon :: TyCon -> Bool
628 isAlgTyCon (AlgTyCon {})   = True
629 isAlgTyCon (TupleTyCon {}) = True
630 isAlgTyCon other           = False
631
632 isDataTyCon :: TyCon -> Bool
633 -- isDataTyCon returns True for data types that are definitely
634 -- represented by heap-allocated constructors.
635 -- These are srcutinised by Core-level @case@ expressions, and they
636 -- get info tables allocated for them.
637 --      True for all @data@ types
638 --      False for newtypes
639 --                unboxed tuples
640 --                type families
641 -- 
642 -- NB: for a data type family, T, only the *instance* tycons are
643 --     get an info table etc.  The family tycon does not.
644 --     Hence False for OpenTyCon
645 isDataTyCon tc@(AlgTyCon {algTcRhs = rhs})  
646   = case rhs of
647         OpenTyCon {}  -> False
648         DataTyCon {}  -> True
649         NewTyCon {}   -> False
650         AbstractTyCon -> False   -- We don't know, so return False
651 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
652 isDataTyCon other = False
653
654 isNewTyCon :: TyCon -> Bool
655 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
656 isNewTyCon other                               = False
657
658 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
659 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, 
660                                  algTcRhs = NewTyCon { nt_co = mb_co, 
661                                                        nt_rhs = rhs }})
662                            = Just (tvs, rhs, mb_co)
663 unwrapNewTyCon_maybe other = Nothing
664
665 isProductTyCon :: TyCon -> Bool
666 -- A "product" tycon
667 --      has *one* constructor, 
668 --      is *not* existential
669 -- but
670 --      may be  DataType, NewType
671 --      may be  unboxed or not, 
672 --      may be  recursive or not
673 -- 
674 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
675                                     DataTyCon{ data_cons = [data_con] } 
676                                                 -> isVanillaDataCon data_con
677                                     NewTyCon {} -> True
678                                     other       -> False
679 isProductTyCon (TupleTyCon {})  = True   
680 isProductTyCon other            = False
681
682 isSynTyCon :: TyCon -> Bool
683 isSynTyCon (SynTyCon {}) = True
684 isSynTyCon _             = False
685
686 -- As for newtypes, it is in some contexts important to distinguish between
687 -- closed synonyms and synonym families, as synonym families have no unique
688 -- right hand side to which a synonym family application can expand.
689 --
690 isClosedSynTyCon :: TyCon -> Bool
691 isClosedSynTyCon tycon = isSynTyCon tycon && not (isOpenTyCon tycon)
692
693 isOpenSynTyCon :: TyCon -> Bool
694 isOpenSynTyCon tycon = isSynTyCon tycon && isOpenTyCon tycon
695
696 isGadtSyntaxTyCon :: TyCon -> Bool
697 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
698 isGadtSyntaxTyCon other                                = False
699
700 isEnumerationTyCon :: TyCon -> Bool
701 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
702 isEnumerationTyCon other                                               = False
703
704 isOpenTyCon :: TyCon -> Bool
705 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon _ _}) = True
706 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {}    }) = True
707 isOpenTyCon _                                        = False
708
709 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
710 assocTyConArgPoss_maybe (AlgTyCon { 
711                            algTcRhs = OpenTyCon {otArgPoss = poss}})  = poss
712 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
713 assocTyConArgPoss_maybe _ = Nothing
714
715 isTyConAssoc :: TyCon -> Bool
716 isTyConAssoc = isJust . assocTyConArgPoss_maybe
717
718 setTyConArgPoss :: TyCon -> [Int] -> TyCon
719 setTyConArgPoss tc@(AlgTyCon { algTcRhs = rhs })               poss = 
720   tc { algTcRhs = rhs {otArgPoss = Just poss} }
721 setTyConArgPoss tc@(SynTyCon { synTcRhs = OpenSynTyCon ki _ }) poss = 
722   tc { synTcRhs = OpenSynTyCon ki (Just poss) }
723 setTyConArgPoss tc _ = pprPanic "setTyConArgPoss" (ppr tc)
724
725 isTupleTyCon :: TyCon -> Bool
726 -- The unit tycon didn't used to be classed as a tuple tycon
727 -- but I thought that was silly so I've undone it
728 -- If it can't be for some reason, it should be a AlgTyCon
729 --
730 -- NB: when compiling Data.Tuple, the tycons won't reply True to
731 -- isTupleTyCon, becuase they are built as AlgTyCons.  However they
732 -- get spat into the interface file as tuple tycons, so I don't think
733 -- it matters.
734 isTupleTyCon (TupleTyCon {}) = True
735 isTupleTyCon other           = False
736
737 isUnboxedTupleTyCon :: TyCon -> Bool
738 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
739 isUnboxedTupleTyCon other = False
740
741 isBoxedTupleTyCon :: TyCon -> Bool
742 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
743 isBoxedTupleTyCon other = False
744
745 tupleTyConBoxity tc = tyConBoxed tc
746
747 isRecursiveTyCon :: TyCon -> Bool
748 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
749 isRecursiveTyCon other                                = False
750
751 isHiBootTyCon :: TyCon -> Bool
752 -- Used for knot-tying in hi-boot files
753 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
754 isHiBootTyCon other                                 = False
755
756 isForeignTyCon :: TyCon -> Bool
757 -- isForeignTyCon identifies foreign-imported type constructors
758 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
759 isForeignTyCon other                               = False
760
761 isSuperKindTyCon :: TyCon -> Bool
762 isSuperKindTyCon (SuperKindTyCon {}) = True
763 isSuperKindTyCon other               = False
764
765 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, [Type] -> (Type,Type))
766 isCoercionTyCon_maybe (CoercionTyCon {tyConArity = ar, coKindFun = rule}) 
767   = Just (ar, rule)
768 isCoercionTyCon_maybe other = Nothing
769
770 isCoercionTyCon :: TyCon -> Bool
771 isCoercionTyCon (CoercionTyCon {}) = True
772 isCoercionTyCon other              = False
773
774 -- Identifies implicit tycons that, in particular, do not go into interface
775 -- files (because they are implicitly reconstructed when the interface is
776 -- read).
777 --
778 -- Note that 
779 --
780 -- * associated families are implicit, as they are re-constructed from
781 --   the class declaration in which they reside, and 
782 -- * family instances are *not* implicit as they represent the instance body
783 --   (similar to a dfun does that for a class instance).
784 --
785 isImplicitTyCon :: TyCon -> Bool
786 isImplicitTyCon tycon | isTyConAssoc tycon           = True
787                       | isSynTyCon tycon             = False
788                       | isAlgTyCon tycon             = isClassTyCon tycon ||
789                                                        isTupleTyCon tycon
790 isImplicitTyCon _other                               = True
791         -- catches: FunTyCon, PrimTyCon, 
792         -- CoercionTyCon, SuperKindTyCon
793 \end{code}
794
795
796 -----------------------------------------------
797 --      Expand type-constructor applications
798 -----------------------------------------------
799
800 \begin{code}
801 tcExpandTyCon_maybe, coreExpandTyCon_maybe 
802         :: TyCon 
803         -> [Type]                       -- Args to tycon
804         -> Maybe ([(TyVar,Type)],       -- Substitution
805                   Type,                 -- Body type (not yet substituted)
806                   [Type])               -- Leftover args
807
808 -- For the *typechecker* view, we expand synonyms only
809 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs, 
810                                synTcRhs = SynonymTyCon rhs }) tys
811    = expand tvs rhs tys
812 tcExpandTyCon_maybe other_tycon tys = Nothing
813
814 ---------------
815 -- For the *Core* view, we expand synonyms only as well
816
817 coreExpandTyCon_maybe (AlgTyCon {algTcRec = NonRecursive,       -- Not recursive
818          algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
819    = case etad_rhs of   -- Don't do this in the pattern match, lest we accidentally
820                         -- match the etad_rhs of a *recursive* newtype
821         (tvs,rhs) -> expand tvs rhs tys
822
823 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
824
825
826 ----------------
827 expand  :: [TyVar] -> Type                      -- Template
828         -> [Type]                               -- Args
829         -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
830 expand tvs rhs tys
831   = case n_tvs `compare` length tys of
832         LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
833         EQ -> Just (tvs `zip` tys, rhs, [])
834         GT -> Nothing
835    where
836      n_tvs = length tvs
837 \end{code}
838
839 \begin{code}
840 tyConHasGenerics :: TyCon -> Bool
841 tyConHasGenerics (AlgTyCon {hasGenerics = hg})   = hg
842 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
843 tyConHasGenerics other                           = False        -- Synonyms
844
845 tyConDataCons :: TyCon -> [DataCon]
846 -- It's convenient for tyConDataCons to return the
847 -- empty list for type synonyms etc
848 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
849
850 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
851 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
852 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }})    = Just [con]
853 tyConDataCons_maybe (TupleTyCon {dataCon = con})                           = Just [con]
854 tyConDataCons_maybe other                                                  = Nothing
855
856 tyConFamilySize  :: TyCon -> Int
857 tyConFamilySize (AlgTyCon   {algTcRhs = DataTyCon {data_cons = cons}}) = 
858   length cons
859 tyConFamilySize (AlgTyCon   {algTcRhs = NewTyCon {}})                  = 1
860 tyConFamilySize (AlgTyCon   {algTcRhs = OpenTyCon {}})                 = 0
861 tyConFamilySize (TupleTyCon {})                                        = 1
862 #ifdef DEBUG
863 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
864 #endif
865
866 tyConSelIds :: TyCon -> [Id]
867 tyConSelIds (AlgTyCon {algTcSelIds = fs}) = fs
868 tyConSelIds other_tycon                   = []
869
870 algTyConRhs :: TyCon -> AlgTyConRhs
871 algTyConRhs (AlgTyCon {algTcRhs = rhs})  = rhs
872 algTyConRhs (TupleTyCon {dataCon = con}) = DataTyCon { data_cons = [con], is_enum = False }
873 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
874 \end{code}
875
876 \begin{code}
877 newTyConRhs :: TyCon -> ([TyVar], Type)
878 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
879 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
880
881 newTyConRep :: TyCon -> ([TyVar], Type)
882 newTyConRep (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rep = rep }}) = (tvs, rep)
883 newTyConRep tycon = pprPanic "newTyConRep" (ppr tycon)
884
885 newTyConCo_maybe :: TyCon -> Maybe TyCon
886 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
887 newTyConCo_maybe _                                               = Nothing
888
889 tyConPrimRep :: TyCon -> PrimRep
890 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
891 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
892 \end{code}
893
894 \begin{code}
895 tyConStupidTheta :: TyCon -> [PredType]
896 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
897 tyConStupidTheta (TupleTyCon {})                        = []
898 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
899 \end{code}
900
901 \begin{code}
902 synTyConDefn :: TyCon -> ([TyVar], Type)
903 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty}) 
904   = (tyvars, ty)
905 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
906
907 synTyConRhs :: TyCon -> SynTyConRhs
908 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
909 synTyConRhs tc                          = pprPanic "synTyConRhs" (ppr tc)
910
911 synTyConType :: TyCon -> Type
912 synTyConType tc = case synTcRhs tc of
913                     SynonymTyCon t -> t
914                     _              -> pprPanic "synTyConType" (ppr tc)
915
916 synTyConResKind :: TyCon -> Kind
917 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
918 synTyConResKind tycon  = pprPanic "synTyConResKind" (ppr tycon)
919 \end{code}
920
921 \begin{code}
922 maybeTyConSingleCon :: TyCon -> Maybe DataCon
923 maybeTyConSingleCon (AlgTyCon {algTcRhs = DataTyCon {data_cons = [c] }}) = Just c
924 maybeTyConSingleCon (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})    = Just c
925 maybeTyConSingleCon (AlgTyCon {})                = Nothing
926 maybeTyConSingleCon (TupleTyCon {dataCon = con}) = Just con
927 maybeTyConSingleCon (PrimTyCon {})               = Nothing
928 maybeTyConSingleCon (FunTyCon {})                = Nothing  -- case at funty
929 maybeTyConSingleCon tc = pprPanic "maybeTyConSingleCon: unexpected tycon " $ ppr tc
930 \end{code}
931
932 \begin{code}
933 isClassTyCon :: TyCon -> Bool
934 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
935 isClassTyCon other_tycon                             = False
936
937 tyConClass_maybe :: TyCon -> Maybe Class
938 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
939 tyConClass_maybe other_tycon                                = Nothing
940
941 isFamInstTyCon :: TyCon -> Bool
942 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
943 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
944 isFamInstTyCon other_tycon                                   = False
945
946 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
947 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) = 
948   Just (fam, instTys)
949 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) = 
950   Just (fam, instTys)
951 tyConFamInst_maybe other_tycon                                          = 
952   Nothing
953
954 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
955 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) = 
956   Just coe
957 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) = 
958   Just coe
959 tyConFamilyCoercion_maybe other_tycon                                    = 
960   Nothing
961 \end{code}
962
963
964 %************************************************************************
965 %*                                                                      *
966 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
967 %*                                                                      *
968 %************************************************************************
969
970 @TyCon@s are compared by comparing their @Unique@s.
971
972 The strictness analyser needs @Ord@. It is a lexicographic order with
973 the property @(a<=b) || (b<=a)@.
974
975 \begin{code}
976 instance Eq TyCon where
977     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
978     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
979
980 instance Ord TyCon where
981     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
982     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
983     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
984     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
985     compare a b = getUnique a `compare` getUnique b
986
987 instance Uniquable TyCon where
988     getUnique tc = tyConUnique tc
989
990 instance Outputable TyCon where
991     ppr tc  = ppr (getName tc) 
992
993 instance NamedThing TyCon where
994     getName = tyConName
995 \end{code}