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