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