Rewrite the unsafe code dealing with unboxed primitives in RtClosureInspect
[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 \end{code}
471
472 %************************************************************************
473 %*                                                                      *
474 \subsection{TyCon Construction}
475 %*                                                                      *
476 %************************************************************************
477
478 Note: the TyCon constructors all take a Kind as one argument, even though
479 they could, in principle, work out their Kind from their other arguments.
480 But to do so they need functions from Types, and that makes a nasty
481 module mutual-recursion.  And they aren't called from many places.
482 So we compromise, and move their Kind calculation to the call site.
483
484 \begin{code}
485 mkFunTyCon :: Name -> Kind -> TyCon
486 mkFunTyCon name kind 
487   = FunTyCon { 
488         tyConUnique = nameUnique name,
489         tyConName   = name,
490         tyConKind   = kind,
491         tyConArity  = 2
492     }
493
494 -- This is the making of a TyCon. Just the same as the old mkAlgTyCon,
495 -- but now you also have to pass in the generic information about the type
496 -- constructor - you can get hold of it easily (see Generics module)
497 mkAlgTyCon name kind tyvars stupid rhs sel_ids parent is_rec gen_info gadt_syn
498   = AlgTyCon {  
499         tyConName        = name,
500         tyConUnique      = nameUnique name,
501         tyConKind        = kind,
502         tyConArity       = length tyvars,
503         tyConTyVars      = tyvars,
504         algTcStupidTheta = stupid,
505         algTcRhs         = rhs,
506         algTcSelIds      = sel_ids,
507         algTcParent      = ASSERT( okParent name parent ) parent,
508         algTcRec         = is_rec,
509         algTcGadtSyntax  = gadt_syn,
510         hasGenerics = gen_info
511     }
512
513 mkClassTyCon name kind tyvars rhs clas is_rec =
514   mkAlgTyCon name kind tyvars [] rhs [] (ClassTyCon clas) is_rec False False
515
516 mkTupleTyCon name kind arity tyvars con boxed gen_info
517   = TupleTyCon {
518         tyConUnique = nameUnique name,
519         tyConName = name,
520         tyConKind = kind,
521         tyConArity = arity,
522         tyConBoxed = boxed,
523         tyConTyVars = tyvars,
524         dataCon = con,
525         hasGenerics = gen_info
526     }
527
528 -- Foreign-imported (.NET) type constructors are represented
529 -- as primitive, but *lifted*, TyCons for now. They are lifted
530 -- because the Haskell type T representing the (foreign) .NET
531 -- type T is actually implemented (in ILX) as a thunk<T>
532 mkForeignTyCon name ext_name kind arity
533   = PrimTyCon {
534         tyConName    = name,
535         tyConUnique  = nameUnique name,
536         tyConKind    = kind,
537         tyConArity   = arity,
538         primTyConRep = PtrRep, -- they all do
539         isUnLifted   = False,
540         tyConExtName = ext_name
541     }
542
543
544 -- most Prim tycons are lifted
545 mkPrimTyCon name kind arity rep
546   = mkPrimTyCon' name kind arity rep True  
547
548 mkVoidPrimTyCon name kind arity 
549   = mkPrimTyCon' name kind arity VoidRep True  
550
551 -- but RealWorld is lifted
552 mkLiftedPrimTyCon name kind arity rep
553   = mkPrimTyCon' name kind arity rep False
554
555 mkPrimTyCon' name kind arity rep is_unlifted
556   = PrimTyCon {
557         tyConName    = name,
558         tyConUnique  = nameUnique name,
559         tyConKind    = kind,
560         tyConArity   = arity,
561         primTyConRep = rep,
562         isUnLifted   = is_unlifted,
563         tyConExtName = Nothing
564     }
565
566 mkSynTyCon name kind tyvars rhs parent
567   = SynTyCon {  
568         tyConName = name,
569         tyConUnique = nameUnique name,
570         tyConKind = kind,
571         tyConArity = length tyvars,
572         tyConTyVars = tyvars,
573         synTcRhs = rhs,
574         synTcParent = parent
575     }
576
577 mkCoercionTyCon name arity kindRule
578   = CoercionTyCon {
579         tyConName = name,
580         tyConUnique = nameUnique name,
581         tyConArity = arity,
582         coKindFun = kindRule
583     }
584
585 -- Super kinds always have arity zero
586 mkSuperKindTyCon name
587   = SuperKindTyCon {
588         tyConName = name,
589         tyConUnique = nameUnique name
590   }
591 \end{code}
592
593 \begin{code}
594 isFunTyCon :: TyCon -> Bool
595 isFunTyCon (FunTyCon {}) = True
596 isFunTyCon _             = False
597
598 isAbstractTyCon :: TyCon -> Bool
599 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
600 isAbstractTyCon _ = False
601
602 makeTyConAbstract :: TyCon -> TyCon
603 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
604 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
605
606 isPrimTyCon :: TyCon -> Bool
607 isPrimTyCon (PrimTyCon {}) = True
608 isPrimTyCon _              = False
609
610 isUnLiftedTyCon :: TyCon -> Bool
611 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
612 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
613 isUnLiftedTyCon _                                       = False
614
615 -- isAlgTyCon returns True for both @data@ and @newtype@
616 isAlgTyCon :: TyCon -> Bool
617 isAlgTyCon (AlgTyCon {})   = True
618 isAlgTyCon (TupleTyCon {}) = True
619 isAlgTyCon other           = False
620
621 isDataTyCon :: TyCon -> Bool
622 -- isDataTyCon returns True for data types that are definitely
623 -- represented by heap-allocated constructors.
624 -- These are srcutinised by Core-level @case@ expressions, and they
625 -- get info tables allocated for them.
626 --      True for all @data@ types
627 --      False for newtypes
628 --                unboxed tuples
629 --                type families
630 -- 
631 -- NB: for a data type family, T, only the *instance* tycons are
632 --     get an info table etc.  The family tycon does not.
633 --     Hence False for OpenTyCon
634 isDataTyCon tc@(AlgTyCon {algTcRhs = rhs})  
635   = case rhs of
636         OpenTyCon {}  -> False
637         DataTyCon {}  -> True
638         NewTyCon {}   -> False
639         AbstractTyCon -> False   -- We don't know, so return False
640 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
641 isDataTyCon other = False
642
643 isNewTyCon :: TyCon -> Bool
644 isNewTyCon (AlgTyCon {algTcRhs = rhs}) = 
645   case rhs of
646     NewTyCon {}  -> True
647     _            -> False
648 isNewTyCon other                       = False
649
650 -- This is an important refinement as typical newtype optimisations do *not*
651 -- hold for newtype families.  Why?  Given a type `T a', if T is a newtype
652 -- family, there is no unique right hand side by which `T a' can be replaced
653 -- by a cast.
654 --
655 isClosedNewTyCon :: TyCon -> Bool
656 isClosedNewTyCon tycon = isNewTyCon tycon && not (isOpenTyCon tycon)
657
658 isProductTyCon :: TyCon -> Bool
659 -- A "product" tycon
660 --      has *one* constructor, 
661 --      is *not* existential
662 -- but
663 --      may be  DataType, NewType
664 --      may be  unboxed or not, 
665 --      may be  recursive or not
666 -- 
667 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
668                                     DataTyCon{ data_cons = [data_con] } 
669                                                 -> isVanillaDataCon data_con
670                                     NewTyCon {} -> True
671                                     other       -> False
672 isProductTyCon (TupleTyCon {})  = True   
673 isProductTyCon other            = False
674
675 isSynTyCon :: TyCon -> Bool
676 isSynTyCon (SynTyCon {}) = True
677 isSynTyCon _             = False
678
679 -- As for newtypes, it is in some contexts important to distinguish between
680 -- closed synonyms and synonym families, as synonym families have no unique
681 -- right hand side to which a synonym family application can expand.
682 --
683 isClosedSynTyCon :: TyCon -> Bool
684 isClosedSynTyCon tycon = isSynTyCon tycon && not (isOpenTyCon tycon)
685
686 isGadtSyntaxTyCon :: TyCon -> Bool
687 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
688 isGadtSyntaxTyCon other                                = False
689
690 isEnumerationTyCon :: TyCon -> Bool
691 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
692 isEnumerationTyCon other                                               = False
693
694 isOpenTyCon :: TyCon -> Bool
695 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon _ _}) = True
696 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {}    }) = True
697 isOpenTyCon _                                        = False
698
699 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
700 assocTyConArgPoss_maybe (AlgTyCon { 
701                            algTcRhs = OpenTyCon {otArgPoss = poss}})  = poss
702 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
703 assocTyConArgPoss_maybe _ = Nothing
704
705 isTyConAssoc :: TyCon -> Bool
706 isTyConAssoc = isJust . assocTyConArgPoss_maybe
707
708 setTyConArgPoss :: TyCon -> [Int] -> TyCon
709 setTyConArgPoss tc@(AlgTyCon { algTcRhs = rhs })               poss = 
710   tc { algTcRhs = rhs {otArgPoss = Just poss} }
711 setTyConArgPoss tc@(SynTyCon { synTcRhs = OpenSynTyCon ki _ }) poss = 
712   tc { synTcRhs = OpenSynTyCon ki (Just poss) }
713 setTyConArgPoss tc _ = pprPanic "setTyConArgPoss" (ppr tc)
714
715 isTupleTyCon :: TyCon -> Bool
716 -- The unit tycon didn't used to be classed as a tuple tycon
717 -- but I thought that was silly so I've undone it
718 -- If it can't be for some reason, it should be a AlgTyCon
719 --
720 -- NB: when compiling Data.Tuple, the tycons won't reply True to
721 -- isTupleTyCon, becuase they are built as AlgTyCons.  However they
722 -- get spat into the interface file as tuple tycons, so I don't think
723 -- it matters.
724 isTupleTyCon (TupleTyCon {}) = True
725 isTupleTyCon other           = False
726
727 isUnboxedTupleTyCon :: TyCon -> Bool
728 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
729 isUnboxedTupleTyCon other = False
730
731 isBoxedTupleTyCon :: TyCon -> Bool
732 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
733 isBoxedTupleTyCon other = False
734
735 tupleTyConBoxity tc = tyConBoxed tc
736
737 isRecursiveTyCon :: TyCon -> Bool
738 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
739 isRecursiveTyCon other                                = False
740
741 isHiBootTyCon :: TyCon -> Bool
742 -- Used for knot-tying in hi-boot files
743 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
744 isHiBootTyCon other                                 = False
745
746 isForeignTyCon :: TyCon -> Bool
747 -- isForeignTyCon identifies foreign-imported type constructors
748 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
749 isForeignTyCon other                               = False
750
751 isSuperKindTyCon :: TyCon -> Bool
752 isSuperKindTyCon (SuperKindTyCon {}) = True
753 isSuperKindTyCon other               = False
754
755 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, [Type] -> (Type,Type))
756 isCoercionTyCon_maybe (CoercionTyCon {tyConArity = ar, coKindFun = rule}) 
757   = Just (ar, rule)
758 isCoercionTyCon_maybe other = Nothing
759
760 isCoercionTyCon :: TyCon -> Bool
761 isCoercionTyCon (CoercionTyCon {}) = True
762 isCoercionTyCon other              = False
763
764 -- Identifies implicit tycons that, in particular, do not go into interface
765 -- files (because they are implicitly reconstructed when the interface is
766 -- read).
767 --
768 -- Note that 
769 --
770 -- * associated families are implicit, as they are re-constructed from
771 --   the class declaration in which they reside, and 
772 -- * family instances are *not* implicit as they represent the instance body
773 --   (similar to a dfun does that for a class instance).
774 --
775 isImplicitTyCon :: TyCon -> Bool
776 isImplicitTyCon tycon | isTyConAssoc tycon           = True
777                       | isSynTyCon tycon             = False
778                       | isAlgTyCon tycon             = isClassTyCon tycon ||
779                                                        isTupleTyCon tycon
780 isImplicitTyCon _other                               = True
781         -- catches: FunTyCon, PrimTyCon, 
782         -- CoercionTyCon, SuperKindTyCon
783 \end{code}
784
785
786 -----------------------------------------------
787 --      Expand type-constructor applications
788 -----------------------------------------------
789
790 \begin{code}
791 tcExpandTyCon_maybe, coreExpandTyCon_maybe 
792         :: TyCon 
793         -> [Type]                       -- Args to tycon
794         -> Maybe ([(TyVar,Type)],       -- Substitution
795                   Type,                 -- Body type (not yet substituted)
796                   [Type])               -- Leftover args
797
798 -- For the *typechecker* view, we expand synonyms only
799 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs, 
800                                synTcRhs = SynonymTyCon rhs }) tys
801    = expand tvs rhs tys
802 tcExpandTyCon_maybe other_tycon tys = Nothing
803
804 ---------------
805 -- For the *Core* view, we expand synonyms only as well
806
807 coreExpandTyCon_maybe (AlgTyCon {algTcRec = NonRecursive,       -- Not recursive
808          algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
809    = case etad_rhs of   -- Don't do this in the pattern match, lest we accidentally
810                         -- match the etad_rhs of a *recursive* newtype
811         (tvs,rhs) -> expand tvs rhs tys
812
813 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
814
815
816 ----------------
817 expand  :: [TyVar] -> Type                      -- Template
818         -> [Type]                               -- Args
819         -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
820 expand tvs rhs tys
821   = case n_tvs `compare` length tys of
822         LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
823         EQ -> Just (tvs `zip` tys, rhs, [])
824         GT -> Nothing
825    where
826      n_tvs = length tvs
827 \end{code}
828
829 \begin{code}
830 tyConHasGenerics :: TyCon -> Bool
831 tyConHasGenerics (AlgTyCon {hasGenerics = hg})   = hg
832 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
833 tyConHasGenerics other                           = False        -- Synonyms
834
835 tyConDataCons :: TyCon -> [DataCon]
836 -- It's convenient for tyConDataCons to return the
837 -- empty list for type synonyms etc
838 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
839
840 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
841 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
842 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }})    = Just [con]
843 tyConDataCons_maybe (TupleTyCon {dataCon = con})                           = Just [con]
844 tyConDataCons_maybe other                                                  = Nothing
845
846 tyConFamilySize  :: TyCon -> Int
847 tyConFamilySize (AlgTyCon   {algTcRhs = DataTyCon {data_cons = cons}}) = 
848   length cons
849 tyConFamilySize (AlgTyCon   {algTcRhs = NewTyCon {}})                  = 1
850 tyConFamilySize (AlgTyCon   {algTcRhs = OpenTyCon {}})                 = 0
851 tyConFamilySize (TupleTyCon {})                                        = 1
852 #ifdef DEBUG
853 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
854 #endif
855
856 tyConSelIds :: TyCon -> [Id]
857 tyConSelIds (AlgTyCon {algTcSelIds = fs}) = fs
858 tyConSelIds other_tycon                   = []
859
860 algTyConRhs :: TyCon -> AlgTyConRhs
861 algTyConRhs (AlgTyCon {algTcRhs = rhs})  = rhs
862 algTyConRhs (TupleTyCon {dataCon = con}) = DataTyCon { data_cons = [con], is_enum = False }
863 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
864 \end{code}
865
866 \begin{code}
867 newTyConRhs :: TyCon -> ([TyVar], Type)
868 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
869 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
870
871 newTyConRep :: TyCon -> ([TyVar], Type)
872 newTyConRep (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rep = rep }}) = (tvs, rep)
873 newTyConRep tycon = pprPanic "newTyConRep" (ppr tycon)
874
875 newTyConCo_maybe :: TyCon -> Maybe TyCon
876 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
877 newTyConCo_maybe _                                               = Nothing
878
879 tyConPrimRep :: TyCon -> PrimRep
880 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
881 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
882 \end{code}
883
884 \begin{code}
885 tyConStupidTheta :: TyCon -> [PredType]
886 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
887 tyConStupidTheta (TupleTyCon {})                        = []
888 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
889 \end{code}
890
891 \begin{code}
892 synTyConDefn :: TyCon -> ([TyVar], Type)
893 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty}) 
894   = (tyvars, ty)
895 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
896
897 synTyConRhs :: TyCon -> SynTyConRhs
898 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
899 synTyConRhs tc                          = pprPanic "synTyConRhs" (ppr tc)
900
901 synTyConType :: TyCon -> Type
902 synTyConType tc = case synTcRhs tc of
903                     SynonymTyCon t -> t
904                     _              -> pprPanic "synTyConType" (ppr tc)
905
906 synTyConResKind :: TyCon -> Kind
907 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
908 synTyConResKind tycon  = pprPanic "synTyConResKind" (ppr tycon)
909 \end{code}
910
911 \begin{code}
912 maybeTyConSingleCon :: TyCon -> Maybe DataCon
913 maybeTyConSingleCon (AlgTyCon {algTcRhs = DataTyCon {data_cons = [c] }}) = Just c
914 maybeTyConSingleCon (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})    = Just c
915 maybeTyConSingleCon (AlgTyCon {})                = Nothing
916 maybeTyConSingleCon (TupleTyCon {dataCon = con}) = Just con
917 maybeTyConSingleCon (PrimTyCon {})               = Nothing
918 maybeTyConSingleCon (FunTyCon {})                = Nothing  -- case at funty
919 maybeTyConSingleCon tc = pprPanic "maybeTyConSingleCon: unexpected tycon " $ ppr tc
920 \end{code}
921
922 \begin{code}
923 isClassTyCon :: TyCon -> Bool
924 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
925 isClassTyCon other_tycon                             = False
926
927 tyConClass_maybe :: TyCon -> Maybe Class
928 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
929 tyConClass_maybe other_tycon                                = Nothing
930
931 isFamInstTyCon :: TyCon -> Bool
932 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
933 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
934 isFamInstTyCon other_tycon                                   = False
935
936 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
937 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) = 
938   Just (fam, instTys)
939 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) = 
940   Just (fam, instTys)
941 tyConFamInst_maybe other_tycon                                          = 
942   Nothing
943
944 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
945 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) = 
946   Just coe
947 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) = 
948   Just coe
949 tyConFamilyCoercion_maybe other_tycon                                    = 
950   Nothing
951 \end{code}
952
953
954 %************************************************************************
955 %*                                                                      *
956 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
957 %*                                                                      *
958 %************************************************************************
959
960 @TyCon@s are compared by comparing their @Unique@s.
961
962 The strictness analyser needs @Ord@. It is a lexicographic order with
963 the property @(a<=b) || (b<=a)@.
964
965 \begin{code}
966 instance Eq TyCon where
967     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
968     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
969
970 instance Ord TyCon where
971     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
972     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
973     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
974     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
975     compare a b = getUnique a `compare` getUnique b
976
977 instance Uniquable TyCon where
978     getUnique tc = tyConUnique tc
979
980 instance Outputable TyCon where
981     ppr tc  = ppr (getName tc) 
982
983 instance NamedThing TyCon where
984     getName = tyConName
985 \end{code}