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