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