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