Type checking for type synonym families
[ghc-hetmet.git] / compiler / types / TyCon.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 The @TyCon@ datatype
7
8 \begin{code}
9 module TyCon(
10         TyCon, FieldLabel,
11
12         PrimRep(..),
13         tyConPrimRep,
14         sizeofPrimRep,
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, newTyConRep, newTyConRhs, 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     }           -- INVARAINT: 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,   -- The coercion used to create the newtype
247                                 -- from the representation
248                                 -- optional for non-recursive newtypes
249                                 -- See Note [Newtype coercions]
250
251         nt_etad_rhs :: ([TyVar], Type) ,
252                         -- The same again, but this time eta-reduced
253                         -- hence the [TyVar] which may be shorter than the declared 
254                         -- arity of the TyCon.  See Note [Newtype eta]
255
256         nt_rep :: Type  -- Cached: the *ultimate* representation type
257                         -- By 'ultimate' I mean that the top-level constructor
258                         -- of the rep type is not itself a newtype or type synonym.
259                         -- The rep type isn't entirely simple:
260                         --  for a recursive newtype we pick () as the rep type
261                         --      newtype T = MkT T
262                         -- 
263                         -- This one does not need to be eta reduced; hence its
264                         -- free type variables are conveniently tyConTyVars
265                         -- Thus:
266                         --      newtype T a = MkT [(a,Int)]
267                         -- The rep type is [(a,Int)]
268                         -- NB: the rep type isn't necessarily the original RHS of the
269                         --     newtype decl, because the rep type looks through other
270     }                   --     newtypes.
271
272 visibleDataCons :: AlgTyConRhs -> [DataCon]
273 visibleDataCons AbstractTyCon                 = []
274 visibleDataCons OpenTyCon {}                  = []
275 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
276 visibleDataCons (NewTyCon{ data_con = c })    = [c]
277
278 -- Both type classes as well as family instances imply implicit
279 -- type constructors.  These implicit type constructors refer to their parent
280 -- structure (ie, the class or family from which they derive) using a type of
281 -- the following form.  We use `TyConParent' for both algebraic and synonym 
282 -- types, but the variant `ClassTyCon' will only be used by algebraic tycons.
283
284 data TyConParent 
285   = NoParentTyCon       -- An ordinary type constructor has no parent.
286
287   | ClassTyCon          -- Type constructors representing a class dictionary.
288         Class           -- INVARIANT: the classTyCon of this Class is the current tycon
289
290   | FamilyTyCon         -- Type constructors representing an instance of a type
291         TyCon           --   The type family
292         [Type]          --   Instance types; free variables are the tyConTyVars
293                         --      of the current TyCon (not the family one)
294                         --      INVARIANT: the number of types matches the arity 
295                         --                 of the family tycon
296         TyCon           --   A CoercionTyCon identifying the representation 
297                         --     type with the type instance family.  
298                         --      c.f. Note [Newtype coercions]
299
300         --
301         -- E.g.  data intance T [a] = ...
302         -- gives a representation tycon:
303         --      data :R7T a = ...
304         --      axiom co a :: T [a] ~ :R7T a
305         -- with :R7T's algTcParent = FamilyTyCon T [a] co
306
307 okParent :: Name -> TyConParent -> Bool -- Checks invariants
308 okParent tc_name NoParentTyCon                  = True
309 okParent tc_name (ClassTyCon cls)               = tyConName (classTyCon cls) == tc_name
310 okParent tc_name (FamilyTyCon fam_tc tys co_tc) = tyConArity fam_tc == length tys
311
312 --------------------
313 data SynTyConRhs
314   = OpenSynTyCon Kind           -- Type family: *result* kind given
315                  (Maybe [Int])  -- for associated families: for each tyvars in
316                                 -- the AT decl, gives the position of that
317                                 -- tyvar in the class argument list (starting
318                                 -- from 0). 
319                                 -- NB: Length is less than tyConArity
320                                 --     if higher kind signature.
321
322   | SynonymTyCon Type   -- Mentioning head type vars.  Acts as a template for
323                         --  the expansion when the tycon is applied to some
324                         --  types.
325 \end{code}
326
327 Note [Newtype coercions]
328 ~~~~~~~~~~~~~~~~~~~~~~~~
329
330 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
331 which is used for coercing from the representation type of the
332 newtype, to the newtype itself. For example,
333
334    newtype T a = MkT (a -> a)
335
336 the NewTyCon for T will contain nt_co = CoT where CoT t : T t :=: t ->
337 t.  This TyCon is a CoercionTyCon, so it does not have a kind on its
338 own; it basically has its own typing rule for the fully-applied
339 version.  If the newtype T has k type variables then CoT has arity at
340 most k.  In the case that the right hand side is a type application
341 ending with the same type variables as the left hand side, we
342 "eta-contract" the coercion.  So if we had
343
344    newtype S a = MkT [a]
345
346 then we would generate the arity 0 coercion CoS : S :=: [].  The
347 primary reason we do this is to make newtype deriving cleaner.
348
349 In the paper we'd write
350         axiom CoT : (forall t. T t) :=: (forall t. [t])
351 and then when we used CoT at a particular type, s, we'd say
352         CoT @ s
353 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
354
355 But in GHC we instead make CoT into a new piece of type syntax, CoercionTyCon,
356 (like instCoercionTyCon, symCoercionTyCon etc), which must always
357 be saturated, but which encodes as
358         TyConApp CoT [s]
359 In the vocabulary of the paper it's as if we had axiom declarations
360 like
361         axiom CoT t :  T t :=: [t]
362
363 Note [Newtype eta]
364 ~~~~~~~~~~~~~~~~~~
365 Consider
366         newtype Parser m a = MkParser (Foogle m a)
367 Are these two types equal (to Core)?
368         Monad (Parser m) 
369         Monad (Foogle m)
370 Well, yes.  But to see that easily we eta-reduce the RHS type of
371 Parser, in this case to ([], Froogle), so that even unsaturated applications
372 of Parser will work right.  This eta reduction is done when the type 
373 constructor is built, and cached in NewTyCon.  The cached field is
374 only used in coreExpandTyCon_maybe.
375  
376 Here's an example that I think showed up in practice
377 Source code:
378         newtype T a = MkT [a]
379         newtype Foo m = MkFoo (forall a. m a -> Int)
380
381         w1 :: Foo []
382         w1 = ...
383         
384         w2 :: Foo T
385         w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
386
387 After desugaring, and discading the data constructors for the newtypes,
388 we get:
389         w2 :: Foo T
390         w2 = w1
391 And now Lint complains unless Foo T == Foo [], and that requires T==[]
392
393
394 Note [Indexed data types] (aka data type families)
395 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
396    See also Note [Wrappers for data instance tycons] in MkId.lhs
397
398 Consider
399         data family T a
400
401         data instance T (b,c) where
402           T1 :: b -> c -> T (b,c)
403
404 Then
405   * T is the "family TyCon"
406
407   * We make "representation TyCon" :R1T, thus:
408         data :R1T b c where
409           T1 :: forall b c. b -> c -> :R1T b c
410
411   * It has a top-level coercion connecting it to the family TyCon
412
413         axiom :Co:R1T b c : T (b,c) ~ :R1T b c
414
415   * The data contructor T1 has a wrapper (which is what the source-level
416     "T1" invokes):
417
418         $WT1 :: forall b c. b -> c -> T (b,c)
419         $WT1 b c (x::b) (y::c) = T1 b c x y `cast` sym (:Co:R1T b c)
420
421   * The representation TyCon :R1T has an AlgTyConParent of
422
423         FamilyTyCon T [(b,c)] :Co:R1T
424
425
426
427 %************************************************************************
428 %*                                                                      *
429 \subsection{PrimRep}
430 %*                                                                      *
431 %************************************************************************
432
433 A PrimRep is an abstraction of a type.  It contains information that
434 the code generator needs in order to pass arguments, return results,
435 and store values of this type.
436
437 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
438 MachRep (see cmm/MachOp), although each of these types has a distinct
439 and clearly defined purpose:
440
441   - A PrimRep is a CgRep + information about signedness + information
442     about primitive pointers (AddrRep).  Signedness and primitive
443     pointers are required when passing a primitive type to a foreign
444     function, but aren't needed for call/return conventions of Haskell
445     functions.
446
447   - A MachRep is a basic machine type (non-void, doesn't contain
448     information on pointerhood or signedness, but contains some
449     reps that don't have corresponding Haskell types).
450
451 \begin{code}
452 data PrimRep
453   = VoidRep
454   | PtrRep
455   | IntRep              -- signed, word-sized
456   | WordRep             -- unsinged, word-sized
457   | Int64Rep            -- signed, 64 bit (32-bit words only)
458   | Word64Rep           -- unsigned, 64 bit (32-bit words only)
459   | AddrRep             -- a pointer, but not to a Haskell value
460   | FloatRep
461   | DoubleRep
462
463 -- Size of a PrimRep, in bytes
464 sizeofPrimRep :: PrimRep -> Int
465 sizeofPrimRep IntRep   = wORD_SIZE
466 sizeofPrimRep WordRep  = wORD_SIZE
467 sizeofPrimRep Int64Rep = wORD64_SIZE
468 sizeofPrimRep Word64Rep= wORD64_SIZE
469 sizeofPrimRep FloatRep = 4
470 sizeofPrimRep DoubleRep= 8
471 sizeofPrimRep AddrRep  = wORD_SIZE
472 sizeofPrimRep PtrRep   = wORD_SIZE
473 sizeofPrimRep 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 kind tyvars stupid rhs sel_ids parent is_rec gen_info gadt_syn
502   = AlgTyCon {  
503         tyConName        = name,
504         tyConUnique      = nameUnique name,
505         tyConKind        = kind,
506         tyConArity       = length tyvars,
507         tyConTyVars      = tyvars,
508         algTcStupidTheta = stupid,
509         algTcRhs         = rhs,
510         algTcSelIds      = sel_ids,
511         algTcParent      = ASSERT( okParent name parent ) parent,
512         algTcRec         = is_rec,
513         algTcGadtSyntax  = gadt_syn,
514         hasGenerics = gen_info
515     }
516
517 mkClassTyCon name kind tyvars rhs clas is_rec =
518   mkAlgTyCon name kind tyvars [] rhs [] (ClassTyCon clas) is_rec False False
519
520 mkTupleTyCon name kind arity tyvars con boxed gen_info
521   = TupleTyCon {
522         tyConUnique = nameUnique name,
523         tyConName = name,
524         tyConKind = kind,
525         tyConArity = arity,
526         tyConBoxed = boxed,
527         tyConTyVars = tyvars,
528         dataCon = con,
529         hasGenerics = gen_info
530     }
531
532 -- Foreign-imported (.NET) type constructors are represented
533 -- as primitive, but *lifted*, TyCons for now. They are lifted
534 -- because the Haskell type T representing the (foreign) .NET
535 -- type T is actually implemented (in ILX) as a thunk<T>
536 mkForeignTyCon name ext_name kind arity
537   = PrimTyCon {
538         tyConName    = name,
539         tyConUnique  = nameUnique name,
540         tyConKind    = kind,
541         tyConArity   = arity,
542         primTyConRep = PtrRep, -- they all do
543         isUnLifted   = False,
544         tyConExtName = ext_name
545     }
546
547
548 -- most Prim tycons are lifted
549 mkPrimTyCon name kind arity rep
550   = mkPrimTyCon' name kind arity rep True  
551
552 mkVoidPrimTyCon name kind arity 
553   = mkPrimTyCon' name kind arity VoidRep True  
554
555 -- but RealWorld is lifted
556 mkLiftedPrimTyCon name kind arity rep
557   = mkPrimTyCon' name kind arity rep False
558
559 mkPrimTyCon' name kind arity rep is_unlifted
560   = PrimTyCon {
561         tyConName    = name,
562         tyConUnique  = nameUnique name,
563         tyConKind    = kind,
564         tyConArity   = arity,
565         primTyConRep = rep,
566         isUnLifted   = is_unlifted,
567         tyConExtName = Nothing
568     }
569
570 mkSynTyCon name kind tyvars rhs parent
571   = SynTyCon {  
572         tyConName = name,
573         tyConUnique = nameUnique name,
574         tyConKind = kind,
575         tyConArity = length tyvars,
576         tyConTyVars = tyvars,
577         synTcRhs = rhs,
578         synTcParent = parent
579     }
580
581 mkCoercionTyCon name arity kindRule
582   = CoercionTyCon {
583         tyConName = name,
584         tyConUnique = nameUnique name,
585         tyConArity = arity,
586         coKindFun = kindRule
587     }
588
589 -- Super kinds always have arity zero
590 mkSuperKindTyCon name
591   = SuperKindTyCon {
592         tyConName = name,
593         tyConUnique = nameUnique name
594   }
595 \end{code}
596
597 \begin{code}
598 isFunTyCon :: TyCon -> Bool
599 isFunTyCon (FunTyCon {}) = True
600 isFunTyCon _             = False
601
602 isAbstractTyCon :: TyCon -> Bool
603 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
604 isAbstractTyCon _ = False
605
606 makeTyConAbstract :: TyCon -> TyCon
607 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
608 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
609
610 isPrimTyCon :: TyCon -> Bool
611 isPrimTyCon (PrimTyCon {}) = True
612 isPrimTyCon _              = False
613
614 isUnLiftedTyCon :: TyCon -> Bool
615 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
616 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
617 isUnLiftedTyCon _                                       = False
618
619 -- isAlgTyCon returns True for both @data@ and @newtype@
620 isAlgTyCon :: TyCon -> Bool
621 isAlgTyCon (AlgTyCon {})   = True
622 isAlgTyCon (TupleTyCon {}) = True
623 isAlgTyCon other           = False
624
625 isDataTyCon :: TyCon -> Bool
626 -- isDataTyCon returns True for data types that are definitely
627 -- represented by heap-allocated constructors.
628 -- These are srcutinised by Core-level @case@ expressions, and they
629 -- get info tables allocated for them.
630 --      True for all @data@ types
631 --      False for newtypes
632 --                unboxed tuples
633 --                type families
634 -- 
635 -- NB: for a data type family, T, only the *instance* tycons are
636 --     get an info table etc.  The family tycon does not.
637 --     Hence False for OpenTyCon
638 isDataTyCon tc@(AlgTyCon {algTcRhs = rhs})  
639   = case rhs of
640         OpenTyCon {}  -> False
641         DataTyCon {}  -> True
642         NewTyCon {}   -> False
643         AbstractTyCon -> False   -- We don't know, so return False
644 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
645 isDataTyCon other = False
646
647 isNewTyCon :: TyCon -> Bool
648 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
649 isNewTyCon other                               = False
650
651 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
652 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, 
653                                  algTcRhs = NewTyCon { nt_co = mb_co, 
654                                                        nt_rhs = rhs }})
655                            = Just (tvs, rhs, mb_co)
656 unwrapNewTyCon_maybe other = Nothing
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 isOpenSynTyCon :: TyCon -> Bool
687 isOpenSynTyCon tycon = isSynTyCon tycon && isOpenTyCon tycon
688
689 isGadtSyntaxTyCon :: TyCon -> Bool
690 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
691 isGadtSyntaxTyCon other                                = False
692
693 isEnumerationTyCon :: TyCon -> Bool
694 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
695 isEnumerationTyCon other                                               = False
696
697 isOpenTyCon :: TyCon -> Bool
698 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon _ _}) = True
699 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {}    }) = True
700 isOpenTyCon _                                        = False
701
702 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
703 assocTyConArgPoss_maybe (AlgTyCon { 
704                            algTcRhs = OpenTyCon {otArgPoss = poss}})  = poss
705 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
706 assocTyConArgPoss_maybe _ = Nothing
707
708 isTyConAssoc :: TyCon -> Bool
709 isTyConAssoc = isJust . assocTyConArgPoss_maybe
710
711 setTyConArgPoss :: TyCon -> [Int] -> TyCon
712 setTyConArgPoss tc@(AlgTyCon { algTcRhs = rhs })               poss = 
713   tc { algTcRhs = rhs {otArgPoss = Just poss} }
714 setTyConArgPoss tc@(SynTyCon { synTcRhs = OpenSynTyCon ki _ }) poss = 
715   tc { synTcRhs = OpenSynTyCon ki (Just poss) }
716 setTyConArgPoss tc _ = pprPanic "setTyConArgPoss" (ppr tc)
717
718 isTupleTyCon :: TyCon -> Bool
719 -- The unit tycon didn't used to be classed as a tuple tycon
720 -- but I thought that was silly so I've undone it
721 -- If it can't be for some reason, it should be a AlgTyCon
722 --
723 -- NB: when compiling Data.Tuple, the tycons won't reply True to
724 -- isTupleTyCon, becuase they are built as AlgTyCons.  However they
725 -- get spat into the interface file as tuple tycons, so I don't think
726 -- it matters.
727 isTupleTyCon (TupleTyCon {}) = True
728 isTupleTyCon other           = False
729
730 isUnboxedTupleTyCon :: TyCon -> Bool
731 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
732 isUnboxedTupleTyCon other = False
733
734 isBoxedTupleTyCon :: TyCon -> Bool
735 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
736 isBoxedTupleTyCon other = False
737
738 tupleTyConBoxity tc = tyConBoxed tc
739
740 isRecursiveTyCon :: TyCon -> Bool
741 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
742 isRecursiveTyCon other                                = False
743
744 isHiBootTyCon :: TyCon -> Bool
745 -- Used for knot-tying in hi-boot files
746 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
747 isHiBootTyCon other                                 = False
748
749 isForeignTyCon :: TyCon -> Bool
750 -- isForeignTyCon identifies foreign-imported type constructors
751 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
752 isForeignTyCon other                               = False
753
754 isSuperKindTyCon :: TyCon -> Bool
755 isSuperKindTyCon (SuperKindTyCon {}) = True
756 isSuperKindTyCon other               = False
757
758 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, [Type] -> (Type,Type))
759 isCoercionTyCon_maybe (CoercionTyCon {tyConArity = ar, coKindFun = rule}) 
760   = Just (ar, rule)
761 isCoercionTyCon_maybe other = Nothing
762
763 isCoercionTyCon :: TyCon -> Bool
764 isCoercionTyCon (CoercionTyCon {}) = True
765 isCoercionTyCon other              = False
766
767 -- Identifies implicit tycons that, in particular, do not go into interface
768 -- files (because they are implicitly reconstructed when the interface is
769 -- read).
770 --
771 -- Note that 
772 --
773 -- * associated families are implicit, as they are re-constructed from
774 --   the class declaration in which they reside, and 
775 -- * family instances are *not* implicit as they represent the instance body
776 --   (similar to a dfun does that for a class instance).
777 --
778 isImplicitTyCon :: TyCon -> Bool
779 isImplicitTyCon tycon | isTyConAssoc tycon           = True
780                       | isSynTyCon tycon             = False
781                       | isAlgTyCon tycon             = isClassTyCon tycon ||
782                                                        isTupleTyCon tycon
783 isImplicitTyCon _other                               = True
784         -- catches: FunTyCon, PrimTyCon, 
785         -- CoercionTyCon, SuperKindTyCon
786 \end{code}
787
788
789 -----------------------------------------------
790 --      Expand type-constructor applications
791 -----------------------------------------------
792
793 \begin{code}
794 tcExpandTyCon_maybe, coreExpandTyCon_maybe 
795         :: TyCon 
796         -> [Type]                       -- Args to tycon
797         -> Maybe ([(TyVar,Type)],       -- Substitution
798                   Type,                 -- Body type (not yet substituted)
799                   [Type])               -- Leftover args
800
801 -- For the *typechecker* view, we expand synonyms only
802 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs, 
803                                synTcRhs = SynonymTyCon rhs }) tys
804    = expand tvs rhs tys
805 tcExpandTyCon_maybe other_tycon tys = Nothing
806
807 ---------------
808 -- For the *Core* view, we expand synonyms only as well
809
810 coreExpandTyCon_maybe (AlgTyCon {algTcRec = NonRecursive,       -- Not recursive
811          algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
812    = case etad_rhs of   -- Don't do this in the pattern match, lest we accidentally
813                         -- match the etad_rhs of a *recursive* newtype
814         (tvs,rhs) -> expand tvs rhs tys
815
816 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
817
818
819 ----------------
820 expand  :: [TyVar] -> Type                      -- Template
821         -> [Type]                               -- Args
822         -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
823 expand tvs rhs tys
824   = case n_tvs `compare` length tys of
825         LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
826         EQ -> Just (tvs `zip` tys, rhs, [])
827         GT -> Nothing
828    where
829      n_tvs = length tvs
830 \end{code}
831
832 \begin{code}
833 tyConHasGenerics :: TyCon -> Bool
834 tyConHasGenerics (AlgTyCon {hasGenerics = hg})   = hg
835 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
836 tyConHasGenerics other                           = False        -- Synonyms
837
838 tyConDataCons :: TyCon -> [DataCon]
839 -- It's convenient for tyConDataCons to return the
840 -- empty list for type synonyms etc
841 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
842
843 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
844 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
845 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }})    = Just [con]
846 tyConDataCons_maybe (TupleTyCon {dataCon = con})                           = Just [con]
847 tyConDataCons_maybe other                                                  = Nothing
848
849 tyConFamilySize  :: TyCon -> Int
850 tyConFamilySize (AlgTyCon   {algTcRhs = DataTyCon {data_cons = cons}}) = 
851   length cons
852 tyConFamilySize (AlgTyCon   {algTcRhs = NewTyCon {}})                  = 1
853 tyConFamilySize (AlgTyCon   {algTcRhs = OpenTyCon {}})                 = 0
854 tyConFamilySize (TupleTyCon {})                                        = 1
855 #ifdef DEBUG
856 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
857 #endif
858
859 tyConSelIds :: TyCon -> [Id]
860 tyConSelIds (AlgTyCon {algTcSelIds = fs}) = fs
861 tyConSelIds other_tycon                   = []
862
863 algTyConRhs :: TyCon -> AlgTyConRhs
864 algTyConRhs (AlgTyCon {algTcRhs = rhs})  = rhs
865 algTyConRhs (TupleTyCon {dataCon = con}) = DataTyCon { data_cons = [con], is_enum = False }
866 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
867 \end{code}
868
869 \begin{code}
870 newTyConRhs :: TyCon -> ([TyVar], Type)
871 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
872 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
873
874 newTyConRep :: TyCon -> ([TyVar], Type)
875 newTyConRep (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rep = rep }}) = (tvs, rep)
876 newTyConRep tycon = pprPanic "newTyConRep" (ppr tycon)
877
878 newTyConCo_maybe :: TyCon -> Maybe TyCon
879 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
880 newTyConCo_maybe _                                               = Nothing
881
882 tyConPrimRep :: TyCon -> PrimRep
883 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
884 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
885 \end{code}
886
887 \begin{code}
888 tyConStupidTheta :: TyCon -> [PredType]
889 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
890 tyConStupidTheta (TupleTyCon {})                        = []
891 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
892 \end{code}
893
894 \begin{code}
895 synTyConDefn :: TyCon -> ([TyVar], Type)
896 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty}) 
897   = (tyvars, ty)
898 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
899
900 synTyConRhs :: TyCon -> SynTyConRhs
901 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
902 synTyConRhs tc                          = pprPanic "synTyConRhs" (ppr tc)
903
904 synTyConType :: TyCon -> Type
905 synTyConType tc = case synTcRhs tc of
906                     SynonymTyCon t -> t
907                     _              -> pprPanic "synTyConType" (ppr tc)
908
909 synTyConResKind :: TyCon -> Kind
910 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
911 synTyConResKind tycon  = pprPanic "synTyConResKind" (ppr tycon)
912 \end{code}
913
914 \begin{code}
915 maybeTyConSingleCon :: TyCon -> Maybe DataCon
916 maybeTyConSingleCon (AlgTyCon {algTcRhs = DataTyCon {data_cons = [c] }}) = Just c
917 maybeTyConSingleCon (AlgTyCon {algTcRhs = NewTyCon { data_con = c }})    = Just c
918 maybeTyConSingleCon (AlgTyCon {})                = Nothing
919 maybeTyConSingleCon (TupleTyCon {dataCon = con}) = Just con
920 maybeTyConSingleCon (PrimTyCon {})               = Nothing
921 maybeTyConSingleCon (FunTyCon {})                = Nothing  -- case at funty
922 maybeTyConSingleCon tc = pprPanic "maybeTyConSingleCon: unexpected tycon " $ ppr tc
923 \end{code}
924
925 \begin{code}
926 isClassTyCon :: TyCon -> Bool
927 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
928 isClassTyCon other_tycon                             = False
929
930 tyConClass_maybe :: TyCon -> Maybe Class
931 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
932 tyConClass_maybe other_tycon                                = Nothing
933
934 isFamInstTyCon :: TyCon -> Bool
935 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
936 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
937 isFamInstTyCon other_tycon                                   = False
938
939 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
940 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) = 
941   Just (fam, instTys)
942 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) = 
943   Just (fam, instTys)
944 tyConFamInst_maybe other_tycon                                          = 
945   Nothing
946
947 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
948 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) = 
949   Just coe
950 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) = 
951   Just coe
952 tyConFamilyCoercion_maybe other_tycon                                    = 
953   Nothing
954 \end{code}
955
956
957 %************************************************************************
958 %*                                                                      *
959 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
960 %*                                                                      *
961 %************************************************************************
962
963 @TyCon@s are compared by comparing their @Unique@s.
964
965 The strictness analyser needs @Ord@. It is a lexicographic order with
966 the property @(a<=b) || (b<=a)@.
967
968 \begin{code}
969 instance Eq TyCon where
970     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
971     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
972
973 instance Ord TyCon where
974     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
975     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
976     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
977     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
978     compare a b = getUnique a `compare` getUnique b
979
980 instance Uniquable TyCon where
981     getUnique tc = tyConUnique tc
982
983 instance Outputable TyCon where
984     ppr tc  = ppr (getName tc) 
985
986 instance NamedThing TyCon where
987     getName = tyConName
988 \end{code}