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