Eliminate over-zealous warning in CoreToStg
[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/Commentary/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, newTyConEtadRhs, 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,   -- A CoercionTyCon used to create the newtype
254                                 -- from the representation
255                                 -- Optional for non-recursive newtypes
256                                 -- See Note [Newtype coercions]
257                                 -- Invariant: arity = #tvs in nt_etad_rhs;
258                                 --      See Note [Newtype eta]
259
260         nt_etad_rhs :: ([TyVar], Type) ,
261                         -- The same again, but this time eta-reduced
262                         -- hence the [TyVar] which may be shorter than the declared 
263                         -- arity of the TyCon.  See Note [Newtype eta]
264
265         nt_rep :: Type  -- Cached: the *ultimate* representation type
266                         -- By 'ultimate' I mean that the top-level constructor
267                         -- of the rep type is not itself a newtype or type synonym.
268                         -- The rep type isn't entirely simple:
269                         --  for a recursive newtype we pick () as the rep type
270                         --      newtype T = MkT T
271                         -- 
272                         -- This one does not need to be eta reduced; hence its
273                         -- free type variables are conveniently tyConTyVars
274                         -- Thus:
275                         --      newtype T a = MkT [(a,Int)]
276                         -- The rep type is [(a,Int)]
277                         -- NB: the rep type isn't necessarily the original RHS of the
278                         --     newtype decl, because the rep type looks through other
279     }                   --     newtypes.
280
281 visibleDataCons :: AlgTyConRhs -> [DataCon]
282 visibleDataCons AbstractTyCon                 = []
283 visibleDataCons OpenTyCon {}                  = []
284 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
285 visibleDataCons (NewTyCon{ data_con = c })    = [c]
286
287 -- Both type classes as well as family instances imply implicit
288 -- type constructors.  These implicit type constructors refer to their parent
289 -- structure (ie, the class or family from which they derive) using a type of
290 -- the following form.  We use `TyConParent' for both algebraic and synonym 
291 -- types, but the variant `ClassTyCon' will only be used by algebraic tycons.
292
293 data TyConParent 
294   = NoParentTyCon       -- An ordinary type constructor has no parent.
295
296   | ClassTyCon          -- Type constructors representing a class dictionary.
297         Class           -- INVARIANT: the classTyCon of this Class is the current tycon
298
299   | FamilyTyCon         -- Type constructors representing an instance of a type
300         TyCon           --   The type family
301         [Type]          --   Instance types; free variables are the tyConTyVars
302                         --      of the current TyCon (not the family one)
303                         --      INVARIANT: the number of types matches the arity 
304                         --                 of the family tycon
305         TyCon           --   A CoercionTyCon identifying the representation 
306                         --     type with the type instance family.  
307                         --      c.f. Note [Newtype coercions]
308
309         --
310         -- E.g.  data intance T [a] = ...
311         -- gives a representation tycon:
312         --      data :R7T a = ...
313         --      axiom co a :: T [a] ~ :R7T a
314         -- with :R7T's algTcParent = FamilyTyCon T [a] co
315
316 okParent :: Name -> TyConParent -> Bool -- Checks invariants
317 okParent tc_name NoParentTyCon                  = True
318 okParent tc_name (ClassTyCon cls)               = tyConName (classTyCon cls) == tc_name
319 okParent tc_name (FamilyTyCon fam_tc tys co_tc) = tyConArity fam_tc == length tys
320
321 --------------------
322 data SynTyConRhs
323   = OpenSynTyCon Kind           -- Type family: *result* kind given
324                  (Maybe [Int])  -- for associated families: for each tyvars in
325                                 -- the AT decl, gives the position of that
326                                 -- tyvar in the class argument list (starting
327                                 -- from 0). 
328                                 -- NB: Length is less than tyConArity
329                                 --     if higher kind signature.
330
331   | SynonymTyCon Type   -- Mentioning head type vars.  Acts as a template for
332                         --  the expansion when the tycon is applied to some
333                         --  types.
334 \end{code}
335
336 Note [Newtype coercions]
337 ~~~~~~~~~~~~~~~~~~~~~~~~
338 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
339 which is used for coercing from the representation type of the
340 newtype, to the newtype itself. For example,
341
342    newtype T a = MkT (a -> a)
343
344 the NewTyCon for T will contain nt_co = CoT where CoT t : T t :=: t ->
345 t.  This TyCon is a CoercionTyCon, so it does not have a kind on its
346 own; it basically has its own typing rule for the fully-applied
347 version.  If the newtype T has k type variables then CoT has arity at
348 most k.  In the case that the right hand side is a type application
349 ending with the same type variables as the left hand side, we
350 "eta-contract" the coercion.  So if we had
351
352    newtype S a = MkT [a]
353
354 then we would generate the arity 0 coercion CoS : S :=: [].  The
355 primary reason we do this is to make newtype deriving cleaner.
356
357 In the paper we'd write
358         axiom CoT : (forall t. T t) :=: (forall t. [t])
359 and then when we used CoT at a particular type, s, we'd say
360         CoT @ s
361 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
362
363 But in GHC we instead make CoT into a new piece of type syntax, CoercionTyCon,
364 (like instCoercionTyCon, symCoercionTyCon etc), which must always
365 be saturated, but which encodes as
366         TyConApp CoT [s]
367 In the vocabulary of the paper it's as if we had axiom declarations
368 like
369         axiom CoT t :  T t :=: [t]
370
371 Note [Newtype eta]
372 ~~~~~~~~~~~~~~~~~~
373 Consider
374         newtype Parser m a = MkParser (Foogle m a)
375 Are these two types equal (to Core)?
376         Monad (Parser m) 
377         Monad (Foogle m)
378 Well, yes.  But to see that easily we eta-reduce the RHS type of
379 Parser, in this case to ([], Froogle), so that even unsaturated applications
380 of Parser will work right.  This eta reduction is done when the type 
381 constructor is built, and cached in NewTyCon.  The cached field is
382 only used in coreExpandTyCon_maybe.
383  
384 Here's an example that I think showed up in practice
385 Source code:
386         newtype T a = MkT [a]
387         newtype Foo m = MkFoo (forall a. m a -> Int)
388
389         w1 :: Foo []
390         w1 = ...
391         
392         w2 :: Foo T
393         w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
394
395 After desugaring, and discading the data constructors for the newtypes,
396 we get:
397         w2 :: Foo T
398         w2 = w1
399 And now Lint complains unless Foo T == Foo [], and that requires T==[]
400
401 This point carries over to the newtype coercion, because we need to
402 say 
403         w2 = w1 `cast` Foo CoT
404
405 so the coercion tycon CoT must have 
406         kind:    T ~ []
407  and    arity:   0
408
409
410 Note [Indexed data types] (aka data type families)
411 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
412    See also Note [Wrappers for data instance tycons] in MkId.lhs
413
414 Consider
415         data family T a
416
417         data instance T (b,c) where
418           T1 :: b -> c -> T (b,c)
419
420 Then
421   * T is the "family TyCon"
422
423   * We make "representation TyCon" :R1T, thus:
424         data :R1T b c where
425           T1 :: forall b c. b -> c -> :R1T b c
426
427   * It has a top-level coercion connecting it to the family TyCon
428
429         axiom :Co:R1T b c : T (b,c) ~ :R1T b c
430
431   * The data contructor T1 has a wrapper (which is what the source-level
432     "T1" invokes):
433
434         $WT1 :: forall b c. b -> c -> T (b,c)
435         $WT1 b c (x::b) (y::c) = T1 b c x y `cast` sym (:Co:R1T b c)
436
437   * The representation TyCon :R1T has an AlgTyConParent of
438
439         FamilyTyCon T [(b,c)] :Co:R1T
440
441
442
443 %************************************************************************
444 %*                                                                      *
445 \subsection{PrimRep}
446 %*                                                                      *
447 %************************************************************************
448
449 A PrimRep is an abstraction of a type.  It contains information that
450 the code generator needs in order to pass arguments, return results,
451 and store values of this type.
452
453 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
454 MachRep (see cmm/MachOp), although each of these types has a distinct
455 and clearly defined purpose:
456
457   - A PrimRep is a CgRep + information about signedness + information
458     about primitive pointers (AddrRep).  Signedness and primitive
459     pointers are required when passing a primitive type to a foreign
460     function, but aren't needed for call/return conventions of Haskell
461     functions.
462
463   - A MachRep is a basic machine type (non-void, doesn't contain
464     information on pointerhood or signedness, but contains some
465     reps that don't have corresponding Haskell types).
466
467 \begin{code}
468 data PrimRep
469   = VoidRep
470   | PtrRep
471   | IntRep              -- signed, word-sized
472   | WordRep             -- unsinged, word-sized
473   | Int64Rep            -- signed, 64 bit (32-bit words only)
474   | Word64Rep           -- unsigned, 64 bit (32-bit words only)
475   | AddrRep             -- a pointer, but not to a Haskell value
476   | FloatRep
477   | DoubleRep
478   deriving( Eq )
479
480 -- Size of a PrimRep, in bytes
481 sizeofPrimRep :: PrimRep -> Int
482 sizeofPrimRep IntRep   = wORD_SIZE
483 sizeofPrimRep WordRep  = wORD_SIZE
484 sizeofPrimRep Int64Rep = wORD64_SIZE
485 sizeofPrimRep Word64Rep= wORD64_SIZE
486 sizeofPrimRep FloatRep = 4
487 sizeofPrimRep DoubleRep= 8
488 sizeofPrimRep AddrRep  = wORD_SIZE
489 sizeofPrimRep PtrRep   = wORD_SIZE
490 sizeofPrimRep VoidRep  = 0
491 \end{code}
492
493 %************************************************************************
494 %*                                                                      *
495 \subsection{TyCon Construction}
496 %*                                                                      *
497 %************************************************************************
498
499 Note: the TyCon constructors all take a Kind as one argument, even though
500 they could, in principle, work out their Kind from their other arguments.
501 But to do so they need functions from Types, and that makes a nasty
502 module mutual-recursion.  And they aren't called from many places.
503 So we compromise, and move their Kind calculation to the call site.
504
505 \begin{code}
506 mkFunTyCon :: Name -> Kind -> TyCon
507 mkFunTyCon name kind 
508   = FunTyCon { 
509         tyConUnique = nameUnique name,
510         tyConName   = name,
511         tyConKind   = kind,
512         tyConArity  = 2
513     }
514
515 -- This is the making of a TyCon. Just the same as the old mkAlgTyCon,
516 -- but now you also have to pass in the generic information about the type
517 -- constructor - you can get hold of it easily (see Generics module)
518 mkAlgTyCon name kind tyvars stupid rhs sel_ids parent is_rec gen_info gadt_syn
519   = AlgTyCon {  
520         tyConName        = name,
521         tyConUnique      = nameUnique name,
522         tyConKind        = kind,
523         tyConArity       = length tyvars,
524         tyConTyVars      = tyvars,
525         algTcStupidTheta = stupid,
526         algTcRhs         = rhs,
527         algTcSelIds      = sel_ids,
528         algTcParent      = ASSERT( okParent name parent ) parent,
529         algTcRec         = is_rec,
530         algTcGadtSyntax  = gadt_syn,
531         hasGenerics = gen_info
532     }
533
534 mkClassTyCon name kind tyvars rhs clas is_rec =
535   mkAlgTyCon name kind tyvars [] rhs [] (ClassTyCon clas) is_rec False False
536
537 mkTupleTyCon name kind arity tyvars con boxed gen_info
538   = TupleTyCon {
539         tyConUnique = nameUnique name,
540         tyConName = name,
541         tyConKind = kind,
542         tyConArity = arity,
543         tyConBoxed = boxed,
544         tyConTyVars = tyvars,
545         dataCon = con,
546         hasGenerics = gen_info
547     }
548
549 -- Foreign-imported (.NET) type constructors are represented
550 -- as primitive, but *lifted*, TyCons for now. They are lifted
551 -- because the Haskell type T representing the (foreign) .NET
552 -- type T is actually implemented (in ILX) as a thunk<T>
553 mkForeignTyCon name ext_name kind arity
554   = PrimTyCon {
555         tyConName    = name,
556         tyConUnique  = nameUnique name,
557         tyConKind    = kind,
558         tyConArity   = arity,
559         primTyConRep = PtrRep, -- they all do
560         isUnLifted   = False,
561         tyConExtName = ext_name
562     }
563
564
565 -- most Prim tycons are lifted
566 mkPrimTyCon name kind arity rep
567   = mkPrimTyCon' name kind arity rep True  
568
569 mkVoidPrimTyCon name kind arity 
570   = mkPrimTyCon' name kind arity VoidRep True  
571
572 -- but RealWorld is lifted
573 mkLiftedPrimTyCon name kind arity rep
574   = mkPrimTyCon' name kind arity rep False
575
576 mkPrimTyCon' name kind arity rep is_unlifted
577   = PrimTyCon {
578         tyConName    = name,
579         tyConUnique  = nameUnique name,
580         tyConKind    = kind,
581         tyConArity   = arity,
582         primTyConRep = rep,
583         isUnLifted   = is_unlifted,
584         tyConExtName = Nothing
585     }
586
587 mkSynTyCon name kind tyvars rhs parent
588   = SynTyCon {  
589         tyConName = name,
590         tyConUnique = nameUnique name,
591         tyConKind = kind,
592         tyConArity = length tyvars,
593         tyConTyVars = tyvars,
594         synTcRhs = rhs,
595         synTcParent = parent
596     }
597
598 mkCoercionTyCon name arity kindRule
599   = CoercionTyCon {
600         tyConName = name,
601         tyConUnique = nameUnique name,
602         tyConArity = arity,
603         coKindFun = kindRule
604     }
605
606 -- Super kinds always have arity zero
607 mkSuperKindTyCon name
608   = SuperKindTyCon {
609         tyConName = name,
610         tyConUnique = nameUnique name
611   }
612 \end{code}
613
614 \begin{code}
615 isFunTyCon :: TyCon -> Bool
616 isFunTyCon (FunTyCon {}) = True
617 isFunTyCon _             = False
618
619 isAbstractTyCon :: TyCon -> Bool
620 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
621 isAbstractTyCon _ = False
622
623 makeTyConAbstract :: TyCon -> TyCon
624 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
625 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
626
627 isPrimTyCon :: TyCon -> Bool
628 isPrimTyCon (PrimTyCon {}) = True
629 isPrimTyCon _              = False
630
631 isUnLiftedTyCon :: TyCon -> Bool
632 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
633 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
634 isUnLiftedTyCon _                                       = False
635
636 -- isAlgTyCon returns True for both @data@ and @newtype@
637 isAlgTyCon :: TyCon -> Bool
638 isAlgTyCon (AlgTyCon {})   = True
639 isAlgTyCon (TupleTyCon {}) = True
640 isAlgTyCon other           = False
641
642 isDataTyCon :: TyCon -> Bool
643 -- isDataTyCon returns True for data types that are definitely
644 -- represented by heap-allocated constructors.
645 -- These are srcutinised by Core-level @case@ expressions, and they
646 -- get info tables allocated for them.
647 --      True for all @data@ types
648 --      False for newtypes
649 --                unboxed tuples
650 --                type families
651 -- 
652 -- NB: for a data type family, T, only the *instance* tycons are
653 --     get an info table etc.  The family tycon does not.
654 --     Hence False for OpenTyCon
655 isDataTyCon tc@(AlgTyCon {algTcRhs = rhs})  
656   = case rhs of
657         OpenTyCon {}  -> False
658         DataTyCon {}  -> True
659         NewTyCon {}   -> False
660         AbstractTyCon -> False   -- We don't know, so return False
661 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
662 isDataTyCon other = False
663
664 isNewTyCon :: TyCon -> Bool
665 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
666 isNewTyCon other                               = False
667
668 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
669 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, 
670                                  algTcRhs = NewTyCon { nt_co = mb_co, 
671                                                        nt_rhs = rhs }})
672                            = Just (tvs, rhs, mb_co)
673 unwrapNewTyCon_maybe other = Nothing
674
675 isProductTyCon :: TyCon -> Bool
676 -- A "product" tycon
677 --      has *one* constructor, 
678 --      is *not* existential
679 -- but
680 --      may be  DataType, NewType
681 --      may be  unboxed or not, 
682 --      may be  recursive or not
683 -- 
684 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
685                                     DataTyCon{ data_cons = [data_con] } 
686                                                 -> isVanillaDataCon data_con
687                                     NewTyCon {} -> True
688                                     other       -> False
689 isProductTyCon (TupleTyCon {})  = True   
690 isProductTyCon other            = False
691
692 isSynTyCon :: TyCon -> Bool
693 isSynTyCon (SynTyCon {}) = True
694 isSynTyCon _             = False
695
696 -- As for newtypes, it is in some contexts important to distinguish between
697 -- closed synonyms and synonym families, as synonym families have no unique
698 -- right hand side to which a synonym family application can expand.
699 --
700 isClosedSynTyCon :: TyCon -> Bool
701 isClosedSynTyCon tycon = isSynTyCon tycon && not (isOpenTyCon tycon)
702
703 isOpenSynTyCon :: TyCon -> Bool
704 isOpenSynTyCon tycon = isSynTyCon tycon && isOpenTyCon tycon
705
706 isGadtSyntaxTyCon :: TyCon -> Bool
707 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
708 isGadtSyntaxTyCon other                                = False
709
710 isEnumerationTyCon :: TyCon -> Bool
711 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
712 isEnumerationTyCon other                                               = False
713
714 isOpenTyCon :: TyCon -> Bool
715 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon _ _}) = True
716 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {}    }) = True
717 isOpenTyCon _                                        = False
718
719 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
720 assocTyConArgPoss_maybe (AlgTyCon { 
721                            algTcRhs = OpenTyCon {otArgPoss = poss}})  = poss
722 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
723 assocTyConArgPoss_maybe _ = Nothing
724
725 isTyConAssoc :: TyCon -> Bool
726 isTyConAssoc = isJust . assocTyConArgPoss_maybe
727
728 setTyConArgPoss :: TyCon -> [Int] -> TyCon
729 setTyConArgPoss tc@(AlgTyCon { algTcRhs = rhs })               poss = 
730   tc { algTcRhs = rhs {otArgPoss = Just poss} }
731 setTyConArgPoss tc@(SynTyCon { synTcRhs = OpenSynTyCon ki _ }) poss = 
732   tc { synTcRhs = OpenSynTyCon ki (Just poss) }
733 setTyConArgPoss tc _ = pprPanic "setTyConArgPoss" (ppr tc)
734
735 isTupleTyCon :: TyCon -> Bool
736 -- The unit tycon didn't used to be classed as a tuple tycon
737 -- but I thought that was silly so I've undone it
738 -- If it can't be for some reason, it should be a AlgTyCon
739 --
740 -- NB: when compiling Data.Tuple, the tycons won't reply True to
741 -- isTupleTyCon, becuase they are built as AlgTyCons.  However they
742 -- get spat into the interface file as tuple tycons, so I don't think
743 -- it matters.
744 isTupleTyCon (TupleTyCon {}) = True
745 isTupleTyCon other           = False
746
747 isUnboxedTupleTyCon :: TyCon -> Bool
748 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
749 isUnboxedTupleTyCon other = False
750
751 isBoxedTupleTyCon :: TyCon -> Bool
752 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
753 isBoxedTupleTyCon other = False
754
755 tupleTyConBoxity tc = tyConBoxed tc
756
757 isRecursiveTyCon :: TyCon -> Bool
758 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
759 isRecursiveTyCon other                                = False
760
761 isHiBootTyCon :: TyCon -> Bool
762 -- Used for knot-tying in hi-boot files
763 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
764 isHiBootTyCon other                                 = False
765
766 isForeignTyCon :: TyCon -> Bool
767 -- isForeignTyCon identifies foreign-imported type constructors
768 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
769 isForeignTyCon other                               = False
770
771 isSuperKindTyCon :: TyCon -> Bool
772 isSuperKindTyCon (SuperKindTyCon {}) = True
773 isSuperKindTyCon other               = False
774
775 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, [Type] -> (Type,Type))
776 isCoercionTyCon_maybe (CoercionTyCon {tyConArity = ar, coKindFun = rule}) 
777   = Just (ar, rule)
778 isCoercionTyCon_maybe other = Nothing
779
780 isCoercionTyCon :: TyCon -> Bool
781 isCoercionTyCon (CoercionTyCon {}) = True
782 isCoercionTyCon other              = False
783
784 -- Identifies implicit tycons that, in particular, do not go into interface
785 -- files (because they are implicitly reconstructed when the interface is
786 -- read).
787 --
788 -- Note that 
789 --
790 -- * associated families are implicit, as they are re-constructed from
791 --   the class declaration in which they reside, and 
792 -- * family instances are *not* implicit as they represent the instance body
793 --   (similar to a dfun does that for a class instance).
794 --
795 isImplicitTyCon :: TyCon -> Bool
796 isImplicitTyCon tycon | isTyConAssoc tycon           = True
797                       | isSynTyCon tycon             = False
798                       | isAlgTyCon tycon             = isClassTyCon tycon ||
799                                                        isTupleTyCon tycon
800 isImplicitTyCon _other                               = True
801         -- catches: FunTyCon, PrimTyCon, 
802         -- CoercionTyCon, SuperKindTyCon
803 \end{code}
804
805
806 -----------------------------------------------
807 --      Expand type-constructor applications
808 -----------------------------------------------
809
810 \begin{code}
811 tcExpandTyCon_maybe, coreExpandTyCon_maybe 
812         :: TyCon 
813         -> [Type]                       -- Args to tycon
814         -> Maybe ([(TyVar,Type)],       -- Substitution
815                   Type,                 -- Body type (not yet substituted)
816                   [Type])               -- Leftover args
817
818 -- For the *typechecker* view, we expand (closed) synonyms only
819 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs, 
820                                synTcRhs = SynonymTyCon rhs }) tys
821    = expand tvs rhs tys
822 tcExpandTyCon_maybe other_tycon tys = Nothing
823
824 ---------------
825 -- For the *Core* view, we expand synonyms only as well
826
827 coreExpandTyCon_maybe (AlgTyCon {algTcRec = NonRecursive,       -- Not recursive
828          algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
829    = case etad_rhs of   -- Don't do this in the pattern match, lest we accidentally
830                         -- match the etad_rhs of a *recursive* newtype
831         (tvs,rhs) -> expand tvs rhs tys
832
833 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
834
835
836 ----------------
837 expand  :: [TyVar] -> Type                      -- Template
838         -> [Type]                               -- Args
839         -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
840 expand tvs rhs tys
841   = case n_tvs `compare` length tys of
842         LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
843         EQ -> Just (tvs `zip` tys, rhs, [])
844         GT -> Nothing
845    where
846      n_tvs = length tvs
847 \end{code}
848
849 \begin{code}
850 tyConHasGenerics :: TyCon -> Bool
851 tyConHasGenerics (AlgTyCon {hasGenerics = hg})   = hg
852 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
853 tyConHasGenerics other                           = False        -- Synonyms
854
855 tyConDataCons :: TyCon -> [DataCon]
856 -- It's convenient for tyConDataCons to return the
857 -- empty list for type synonyms etc
858 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
859
860 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
861 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
862 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }})    = Just [con]
863 tyConDataCons_maybe (TupleTyCon {dataCon = con})                           = Just [con]
864 tyConDataCons_maybe other                                                  = Nothing
865
866 tyConFamilySize  :: TyCon -> Int
867 tyConFamilySize (AlgTyCon   {algTcRhs = DataTyCon {data_cons = cons}}) = 
868   length cons
869 tyConFamilySize (AlgTyCon   {algTcRhs = NewTyCon {}})                  = 1
870 tyConFamilySize (AlgTyCon   {algTcRhs = OpenTyCon {}})                 = 0
871 tyConFamilySize (TupleTyCon {})                                        = 1
872 #ifdef DEBUG
873 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
874 #endif
875
876 tyConSelIds :: TyCon -> [Id]
877 tyConSelIds (AlgTyCon {algTcSelIds = fs}) = fs
878 tyConSelIds other_tycon                   = []
879
880 algTyConRhs :: TyCon -> AlgTyConRhs
881 algTyConRhs (AlgTyCon {algTcRhs = rhs})  = rhs
882 algTyConRhs (TupleTyCon {dataCon = con}) = DataTyCon { data_cons = [con], is_enum = False }
883 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
884 \end{code}
885
886 \begin{code}
887 newTyConRhs :: TyCon -> ([TyVar], Type)
888 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
889 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
890
891 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
892 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
893 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
894
895 newTyConRep :: TyCon -> ([TyVar], Type)
896 newTyConRep (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rep = rep }}) = (tvs, rep)
897 newTyConRep tycon = pprPanic "newTyConRep" (ppr tycon)
898
899 newTyConCo_maybe :: TyCon -> Maybe TyCon
900 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
901 newTyConCo_maybe _                                               = Nothing
902
903 tyConPrimRep :: TyCon -> PrimRep
904 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
905 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
906 \end{code}
907
908 \begin{code}
909 tyConStupidTheta :: TyCon -> [PredType]
910 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
911 tyConStupidTheta (TupleTyCon {})                        = []
912 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
913 \end{code}
914
915 \begin{code}
916 synTyConDefn :: TyCon -> ([TyVar], Type)
917 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty}) 
918   = (tyvars, ty)
919 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
920
921 synTyConRhs :: TyCon -> SynTyConRhs
922 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
923 synTyConRhs tc                          = pprPanic "synTyConRhs" (ppr tc)
924
925 synTyConType :: TyCon -> Type
926 synTyConType tc = case synTcRhs tc of
927                     SynonymTyCon t -> t
928                     _              -> pprPanic "synTyConType" (ppr tc)
929
930 synTyConResKind :: TyCon -> Kind
931 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
932 synTyConResKind tycon  = pprPanic "synTyConResKind" (ppr tycon)
933 \end{code}
934
935 \begin{code}
936 maybeTyConSingleCon :: TyCon -> Maybe DataCon
937 maybeTyConSingleCon (AlgTyCon {algTcRhs = DataTyCon {data_cons = [c] }}) = Just c
938 maybeTyConSingleCon (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})    = Just c
939 maybeTyConSingleCon (AlgTyCon {})                = Nothing
940 maybeTyConSingleCon (TupleTyCon {dataCon = con}) = Just con
941 maybeTyConSingleCon (PrimTyCon {})               = Nothing
942 maybeTyConSingleCon (FunTyCon {})                = Nothing  -- case at funty
943 maybeTyConSingleCon tc = pprPanic "maybeTyConSingleCon: unexpected tycon " $ ppr tc
944 \end{code}
945
946 \begin{code}
947 isClassTyCon :: TyCon -> Bool
948 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
949 isClassTyCon other_tycon                             = False
950
951 tyConClass_maybe :: TyCon -> Maybe Class
952 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
953 tyConClass_maybe other_tycon                                = Nothing
954
955 isFamInstTyCon :: TyCon -> Bool
956 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
957 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
958 isFamInstTyCon other_tycon                                   = False
959
960 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
961 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) = 
962   Just (fam, instTys)
963 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) = 
964   Just (fam, instTys)
965 tyConFamInst_maybe other_tycon                                          = 
966   Nothing
967
968 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
969 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) = 
970   Just coe
971 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) = 
972   Just coe
973 tyConFamilyCoercion_maybe other_tycon                                    = 
974   Nothing
975 \end{code}
976
977
978 %************************************************************************
979 %*                                                                      *
980 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
981 %*                                                                      *
982 %************************************************************************
983
984 @TyCon@s are compared by comparing their @Unique@s.
985
986 The strictness analyser needs @Ord@. It is a lexicographic order with
987 the property @(a<=b) || (b<=a)@.
988
989 \begin{code}
990 instance Eq TyCon where
991     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
992     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
993
994 instance Ord TyCon where
995     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
996     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
997     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
998     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
999     compare a b = getUnique a `compare` getUnique b
1000
1001 instance Uniquable TyCon where
1002     getUnique tc = tyConUnique tc
1003
1004 instance Outputable TyCon where
1005     ppr tc  = ppr (getName tc) 
1006
1007 instance NamedThing TyCon where
1008     getName = tyConName
1009 \end{code}