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