isDataTyCon should be False for all type families, even 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 --                type families
620 -- 
621 -- NB: for a data type family, T, only the *instance* tycons are
622 --     get an info table etc.  The family tycon does not.
623 --     Hence False for OpenTyCon
624 isDataTyCon tc@(AlgTyCon {algTcRhs = rhs})  
625   = case rhs of
626         OpenTyCon {}  -> False
627         DataTyCon {}  -> True
628         NewTyCon {}   -> False
629         AbstractTyCon -> False   -- We don't know, so return False
630 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
631 isDataTyCon other = False
632
633 isNewTyCon :: TyCon -> Bool
634 isNewTyCon (AlgTyCon {algTcRhs = rhs}) = 
635   case rhs of
636     OpenTyCon {} -> otIsNewtype rhs
637     NewTyCon {}  -> True
638     _            -> False
639 isNewTyCon other                       = False
640
641 -- This is an important refinement as typical newtype optimisations do *not*
642 -- hold for newtype families.  Why?  Given a type `T a', if T is a newtype
643 -- family, there is no unique right hand side by which `T a' can be replaced
644 -- by a cast.
645 --
646 isClosedNewTyCon :: TyCon -> Bool
647 isClosedNewTyCon tycon = isNewTyCon tycon && not (isOpenTyCon tycon)
648
649 isProductTyCon :: TyCon -> Bool
650 -- A "product" tycon
651 --      has *one* constructor, 
652 --      is *not* existential
653 -- but
654 --      may be  DataType, NewType
655 --      may be  unboxed or not, 
656 --      may be  recursive or not
657 -- 
658 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
659                                     DataTyCon{ data_cons = [data_con] } 
660                                                 -> isVanillaDataCon data_con
661                                     NewTyCon {} -> True
662                                     other       -> False
663 isProductTyCon (TupleTyCon {})  = True   
664 isProductTyCon other            = False
665
666 isSynTyCon :: TyCon -> Bool
667 isSynTyCon (SynTyCon {}) = True
668 isSynTyCon _             = False
669
670 -- As for newtypes, it is in some contexts important to distinguish between
671 -- closed synonyms and synonym families, as synonym families have no unique
672 -- right hand side to which a synonym family application can expand.
673 --
674 isClosedSynTyCon :: TyCon -> Bool
675 isClosedSynTyCon tycon = isSynTyCon tycon && not (isOpenTyCon tycon)
676
677 isGadtSyntaxTyCon :: TyCon -> Bool
678 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
679 isGadtSyntaxTyCon other                                = False
680
681 isEnumerationTyCon :: TyCon -> Bool
682 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
683 isEnumerationTyCon other                                               = False
684
685 isOpenTyCon :: TyCon -> Bool
686 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon _ _}) = True
687 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {}    }) = True
688 isOpenTyCon _                                        = False
689
690 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
691 assocTyConArgPoss_maybe (AlgTyCon { 
692                            algTcRhs = OpenTyCon {otArgPoss = poss}})  = poss
693 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
694 assocTyConArgPoss_maybe _ = Nothing
695
696 isTyConAssoc :: TyCon -> Bool
697 isTyConAssoc = isJust . assocTyConArgPoss_maybe
698
699 setTyConArgPoss :: TyCon -> [Int] -> TyCon
700 setTyConArgPoss tc@(AlgTyCon { algTcRhs = rhs })               poss = 
701   tc { algTcRhs = rhs {otArgPoss = Just poss} }
702 setTyConArgPoss tc@(SynTyCon { synTcRhs = OpenSynTyCon ki _ }) poss = 
703   tc { synTcRhs = OpenSynTyCon ki (Just poss) }
704 setTyConArgPoss tc _ = pprPanic "setTyConArgPoss" (ppr tc)
705
706 isTupleTyCon :: TyCon -> Bool
707 -- The unit tycon didn't used to be classed as a tuple tycon
708 -- but I thought that was silly so I've undone it
709 -- If it can't be for some reason, it should be a AlgTyCon
710 --
711 -- NB: when compiling Data.Tuple, the tycons won't reply True to
712 -- isTupleTyCon, becuase they are built as AlgTyCons.  However they
713 -- get spat into the interface file as tuple tycons, so I don't think
714 -- it matters.
715 isTupleTyCon (TupleTyCon {}) = True
716 isTupleTyCon other           = False
717
718 isUnboxedTupleTyCon :: TyCon -> Bool
719 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
720 isUnboxedTupleTyCon other = False
721
722 isBoxedTupleTyCon :: TyCon -> Bool
723 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
724 isBoxedTupleTyCon other = False
725
726 tupleTyConBoxity tc = tyConBoxed tc
727
728 isRecursiveTyCon :: TyCon -> Bool
729 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
730 isRecursiveTyCon other                                = False
731
732 isHiBootTyCon :: TyCon -> Bool
733 -- Used for knot-tying in hi-boot files
734 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
735 isHiBootTyCon other                                 = False
736
737 isForeignTyCon :: TyCon -> Bool
738 -- isForeignTyCon identifies foreign-imported type constructors
739 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
740 isForeignTyCon other                               = False
741
742 isSuperKindTyCon :: TyCon -> Bool
743 isSuperKindTyCon (SuperKindTyCon {}) = True
744 isSuperKindTyCon other               = False
745
746 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, [Type] -> (Type,Type))
747 isCoercionTyCon_maybe (CoercionTyCon {tyConArity = ar, coKindFun = rule}) 
748   = Just (ar, rule)
749 isCoercionTyCon_maybe other = Nothing
750
751 isCoercionTyCon :: TyCon -> Bool
752 isCoercionTyCon (CoercionTyCon {}) = True
753 isCoercionTyCon other              = False
754
755 -- Identifies implicit tycons that, in particular, do not go into interface
756 -- files (because they are implicitly reconstructed when the interface is
757 -- read).
758 --
759 -- Note that 
760 --
761 -- * associated families are implicit, as they are re-constructed from
762 --   the class declaration in which they reside, and 
763 -- * family instances are *not* implicit as they represent the instance body
764 --   (similar to a dfun does that for a class instance).
765 --
766 isImplicitTyCon :: TyCon -> Bool
767 isImplicitTyCon tycon | isTyConAssoc tycon           = True
768                       | isSynTyCon tycon             = False
769                       | isAlgTyCon tycon             = isClassTyCon tycon ||
770                                                        isTupleTyCon tycon
771 isImplicitTyCon _other                               = True
772         -- catches: FunTyCon, PrimTyCon, 
773         -- CoercionTyCon, SuperKindTyCon
774 \end{code}
775
776
777 -----------------------------------------------
778 --      Expand type-constructor applications
779 -----------------------------------------------
780
781 \begin{code}
782 tcExpandTyCon_maybe, coreExpandTyCon_maybe 
783         :: TyCon 
784         -> [Type]                       -- Args to tycon
785         -> Maybe ([(TyVar,Type)],       -- Substitution
786                   Type,                 -- Body type (not yet substituted)
787                   [Type])               -- Leftover args
788
789 -- For the *typechecker* view, we expand synonyms only
790 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs, 
791                                synTcRhs = SynonymTyCon rhs }) tys
792    = expand tvs rhs tys
793 tcExpandTyCon_maybe other_tycon tys = Nothing
794
795 ---------------
796 -- For the *Core* view, we expand synonyms only as well
797
798 coreExpandTyCon_maybe (AlgTyCon {algTcRec = NonRecursive,       -- Not recursive
799          algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
800    = case etad_rhs of   -- Don't do this in the pattern match, lest we accidentally
801                         -- match the etad_rhs of a *recursive* newtype
802         (tvs,rhs) -> expand tvs rhs tys
803
804 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
805
806
807 ----------------
808 expand  :: [TyVar] -> Type                      -- Template
809         -> [Type]                               -- Args
810         -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
811 expand tvs rhs tys
812   = case n_tvs `compare` length tys of
813         LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
814         EQ -> Just (tvs `zip` tys, rhs, [])
815         GT -> Nothing
816    where
817      n_tvs = length tvs
818 \end{code}
819
820 \begin{code}
821 tyConHasGenerics :: TyCon -> Bool
822 tyConHasGenerics (AlgTyCon {hasGenerics = hg})   = hg
823 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
824 tyConHasGenerics other                           = False        -- Synonyms
825
826 tyConDataCons :: TyCon -> [DataCon]
827 -- It's convenient for tyConDataCons to return the
828 -- empty list for type synonyms etc
829 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
830
831 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
832 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
833 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }})    = Just [con]
834 tyConDataCons_maybe (TupleTyCon {dataCon = con})                           = Just [con]
835 tyConDataCons_maybe other                                                  = Nothing
836
837 tyConFamilySize  :: TyCon -> Int
838 tyConFamilySize (AlgTyCon   {algTcRhs = DataTyCon {data_cons = cons}}) = 
839   length cons
840 tyConFamilySize (AlgTyCon   {algTcRhs = NewTyCon {}})                  = 1
841 tyConFamilySize (AlgTyCon   {algTcRhs = OpenTyCon {}})                 = 0
842 tyConFamilySize (TupleTyCon {})                                        = 1
843 #ifdef DEBUG
844 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
845 #endif
846
847 tyConSelIds :: TyCon -> [Id]
848 tyConSelIds (AlgTyCon {algTcSelIds = fs}) = fs
849 tyConSelIds other_tycon                   = []
850
851 algTyConRhs :: TyCon -> AlgTyConRhs
852 algTyConRhs (AlgTyCon {algTcRhs = rhs})  = rhs
853 algTyConRhs (TupleTyCon {dataCon = con}) = DataTyCon { data_cons = [con], is_enum = False }
854 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
855 \end{code}
856
857 \begin{code}
858 newTyConRhs :: TyCon -> ([TyVar], Type)
859 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
860 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
861
862 newTyConRep :: TyCon -> ([TyVar], Type)
863 newTyConRep (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rep = rep }}) = (tvs, rep)
864 newTyConRep tycon = pprPanic "newTyConRep" (ppr tycon)
865
866 newTyConCo_maybe :: TyCon -> Maybe TyCon
867 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
868 newTyConCo_maybe _                                               = Nothing
869
870 tyConPrimRep :: TyCon -> PrimRep
871 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
872 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
873 \end{code}
874
875 \begin{code}
876 tyConStupidTheta :: TyCon -> [PredType]
877 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
878 tyConStupidTheta (TupleTyCon {})                        = []
879 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
880 \end{code}
881
882 \begin{code}
883 synTyConDefn :: TyCon -> ([TyVar], Type)
884 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty}) 
885   = (tyvars, ty)
886 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
887
888 synTyConRhs :: TyCon -> SynTyConRhs
889 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
890 synTyConRhs tc                          = pprPanic "synTyConRhs" (ppr tc)
891
892 synTyConType :: TyCon -> Type
893 synTyConType tc = case synTcRhs tc of
894                     SynonymTyCon t -> t
895                     _              -> pprPanic "synTyConType" (ppr tc)
896
897 synTyConResKind :: TyCon -> Kind
898 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
899 synTyConResKind tycon  = pprPanic "synTyConResKind" (ppr tycon)
900 \end{code}
901
902 \begin{code}
903 maybeTyConSingleCon :: TyCon -> Maybe DataCon
904 maybeTyConSingleCon (AlgTyCon {algTcRhs = DataTyCon {data_cons = [c] }}) = Just c
905 maybeTyConSingleCon (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})    = Just c
906 maybeTyConSingleCon (AlgTyCon {})                = Nothing
907 maybeTyConSingleCon (TupleTyCon {dataCon = con}) = Just con
908 maybeTyConSingleCon (PrimTyCon {})               = Nothing
909 maybeTyConSingleCon (FunTyCon {})                = Nothing  -- case at funty
910 maybeTyConSingleCon tc = pprPanic "maybeTyConSingleCon: unexpected tycon " $ ppr tc
911 \end{code}
912
913 \begin{code}
914 isClassTyCon :: TyCon -> Bool
915 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
916 isClassTyCon other_tycon                             = False
917
918 tyConClass_maybe :: TyCon -> Maybe Class
919 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
920 tyConClass_maybe other_tycon                                = Nothing
921
922 isFamInstTyCon :: TyCon -> Bool
923 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
924 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
925 isFamInstTyCon other_tycon                                   = False
926
927 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
928 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) = 
929   Just (fam, instTys)
930 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) = 
931   Just (fam, instTys)
932 tyConFamInst_maybe other_tycon                                          = 
933   Nothing
934
935 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
936 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) = 
937   Just coe
938 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) = 
939   Just coe
940 tyConFamilyCoercion_maybe other_tycon                                    = 
941   Nothing
942 \end{code}
943
944
945 %************************************************************************
946 %*                                                                      *
947 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
948 %*                                                                      *
949 %************************************************************************
950
951 @TyCon@s are compared by comparing their @Unique@s.
952
953 The strictness analyser needs @Ord@. It is a lexicographic order with
954 the property @(a<=b) || (b<=a)@.
955
956 \begin{code}
957 instance Eq TyCon where
958     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
959     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
960
961 instance Ord TyCon where
962     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
963     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
964     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
965     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
966     compare a b = getUnique a `compare` getUnique b
967
968 instance Uniquable TyCon where
969     getUnique tc = tyConUnique tc
970
971 instance Outputable TyCon where
972     ppr tc  = ppr (getName tc) 
973
974 instance NamedThing TyCon where
975     getName = tyConName
976 \end{code}