[project @ 2001-06-13 15:50:57 by rrt]
[ghc-hetmet.git] / ghc / compiler / types / TyCon.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TyCon]{The @TyCon@ datatype}
5
6 \begin{code}
7 module TyCon(
8         TyCon, KindCon, SuperKindCon, ArgVrcs, AlgTyConFlavour(..),
9
10         isFunTyCon, isUnLiftedTyCon, isBoxedTyCon, isProductTyCon,
11         isAlgTyCon, isDataTyCon, isSynTyCon, isNewTyCon, isPrimTyCon,
12         isEnumerationTyCon, 
13         isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, tupleTyConBoxity,
14         isRecursiveTyCon, newTyConRep,
15
16         mkForeignTyCon, isForeignTyCon,
17
18         mkAlgTyCon, --mkAlgTyCon, 
19         mkClassTyCon,
20         mkFunTyCon,
21         mkPrimTyCon,
22         mkTupleTyCon,
23         mkSynTyCon,
24         mkKindCon,
25         mkSuperKindCon,
26
27         setTyConName,
28
29         tyConName,
30         tyConKind,
31         tyConUnique,
32         tyConTyVars,
33         tyConArgVrcs_maybe,
34         tyConDataCons, tyConDataConsIfAvailable, tyConFamilySize,
35         tyConSelIds,
36         tyConTheta,
37         tyConPrimRep,
38         tyConArity,
39         isClassTyCon, tyConClass_maybe,
40         getSynTyConDefn,
41
42         maybeTyConSingleCon,
43
44         matchesTyCon,
45
46         -- Generics
47         tyConGenIds, tyConGenInfo
48 ) where
49
50 #include "HsVersions.h"
51
52 import {-# SOURCE #-} TypeRep ( Type, PredType, Kind, SuperKind )
53  -- Should just be Type(Type), but this fails due to bug present up to
54  -- and including 4.02 involving slurping of hi-boot files.  Bug is now fixed.
55
56 import {-# SOURCE #-} DataCon ( DataCon, isExistentialDataCon )
57
58
59 import Var              ( TyVar, Id )
60 import Class            ( Class )
61 import BasicTypes       ( Arity, RecFlag(..), Boxity(..), 
62                           isBoxed, EP(..) )
63 import Name             ( Name, nameUnique, NamedThing(getName) )
64 import PrelNames        ( Unique, Uniquable(..), anyBoxConKey )
65 import PrimRep          ( PrimRep(..), isFollowableRep )
66 import Outputable
67 import FastString
68 \end{code}
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{The data type}
73 %*                                                                      *
74 %************************************************************************
75
76 \begin{code}
77 type KindCon      = TyCon
78 type SuperKindCon = TyCon
79
80 data TyCon
81   = FunTyCon {
82         tyConUnique :: Unique,
83         tyConName   :: Name,
84         tyConKind   :: Kind,
85         tyConArity  :: Arity
86     }
87
88
89   | AlgTyCon {          -- Tuples, data type, and newtype decls.
90                         -- All lifted, all boxed
91         tyConUnique :: Unique,
92         tyConName   :: Name,
93         tyConKind   :: Kind,
94         tyConArity  :: Arity,
95         
96         tyConTyVars   :: [TyVar],
97         tyConArgVrcs  :: ArgVrcs,
98         algTyConTheta :: [PredType],
99
100         dataCons :: [DataCon],
101                 -- Its data constructors, with fully polymorphic types
102                 --      This list can be empty, when we import a data type abstractly,
103                 --      either (a) the interface is hand-written and doesn't give
104                 --                 the constructors, or
105                 --             (b) in a quest for fast compilation we don't import 
106                 --                 the constructors
107
108         selIds :: [Id], -- Its record selectors (if any)
109
110         noOfDataCons :: Int,    -- Number of data constructors
111                                 -- Usually this is the same as the length of the
112                                 -- dataCons field, but the latter may be empty if
113                                 -- we imported the type abstractly.  But even if we import
114                                 -- abstractly we still need to know the number of constructors
115                                 -- so we can get the return convention right.  Tiresome!
116                                 
117         algTyConFlavour :: AlgTyConFlavour,
118         algTyConRec     :: RecFlag,             -- Tells whether the data type is part of 
119                                                 -- a mutually-recursive group or not
120
121         genInfo :: Maybe (EP Id),       -- Convert T <-> Tring
122                                         -- Some TyCons don't have it; 
123                                         -- e.g. the TyCon for a Class dictionary,
124                                         -- and TyCons with unboxed arguments
125
126         algTyConClass :: Maybe Class    -- Just cl if this tycon came from a class declaration
127     }
128
129   | PrimTyCon {                 -- Primitive types; cannot be defined in Haskell
130                                 -- Now includes foreign-imported types
131         tyConUnique  :: Unique,
132         tyConName    :: Name,
133         tyConKind    :: Kind,
134         tyConArity   :: Arity,
135         tyConArgVrcs :: ArgVrcs,
136         primTyConRep :: PrimRep,        -- Many primitive tycons are unboxed, but some are
137                                         -- boxed (represented by pointers). The PrimRep tells.
138
139         isUnLifted   :: Bool,   -- Most primitive tycons are unlifted, 
140                                 -- but foreign-imported ones may not be
141         tyConExtName :: Maybe FastString
142     }
143
144   | TupleTyCon {
145
146         tyConUnique :: Unique,
147         tyConName   :: Name,
148         tyConKind   :: Kind,
149         tyConArity  :: Arity,
150         tyConBoxed  :: Boxity,
151         tyConTyVars :: [TyVar],
152         dataCon     :: DataCon,
153         genInfo     :: Maybe (EP Id)            -- Generic type and conv funs 
154     }
155
156   | SynTyCon {
157         tyConUnique :: Unique,
158         tyConName   :: Name,
159         tyConKind   :: Kind,
160         tyConArity  :: Arity,
161
162         tyConTyVars     :: [TyVar],     -- Bound tyvars
163         synTyConDefn    :: Type,        -- Right-hand side, mentioning these type vars.
164                                         -- Acts as a template for the expansion when
165                                         -- the tycon is applied to some types.
166         tyConArgVrcs :: ArgVrcs
167     }
168
169   | KindCon {           -- Type constructor at the kind level
170         tyConUnique :: Unique,
171         tyConName   :: Name,
172         tyConKind   :: SuperKind,
173         tyConArity  :: Arity
174     }
175
176   | SuperKindCon        {               -- The type of kind variables or boxity variables,
177         tyConUnique :: Unique,
178         tyConName   :: Name
179     }
180
181 type ArgVrcs = [(Bool,Bool)]  -- Tyvar variance info: [(occPos,occNeg)]
182
183 data AlgTyConFlavour
184   = DataTyCon           -- Data type
185   | EnumTyCon           -- Special sort of enumeration type
186   | NewTyCon Type       -- Newtype, with its *ultimate* representation type
187                         -- By 'ultimate' I mean that the rep type is not itself
188                         -- a newtype or type synonym.
189
190                         -- The rep type has explicit for-alls for the tyvars of
191                         -- the TyCon.  Thus:
192                         --      newtype T a = MkT [(a,Int)]
193                         -- The rep type is forall a. [(a,Int)]
194                         --
195                         -- The rep type isn't entirely simple:
196                         --  for a recursive newtype we pick () as the rep type
197                         --      newtype T = MkT T
198 \end{code}
199
200 %************************************************************************
201 %*                                                                      *
202 \subsection{TyCon Construction}
203 %*                                                                      *
204 %************************************************************************
205
206 Note: the TyCon constructors all take a Kind as one argument, even though
207 they could, in principle, work out their Kind from their other arguments.
208 But to do so they need functions from Types, and that makes a nasty
209 module mutual-recursion.  And they aren't called from many places.
210 So we compromise, and move their Kind calculation to the call site.
211
212 \begin{code}
213 mkSuperKindCon :: Name -> SuperKindCon
214 mkSuperKindCon name = SuperKindCon {
215                         tyConUnique = nameUnique name,
216                         tyConName = name
217                       }
218
219 mkKindCon :: Name -> SuperKind -> KindCon
220 mkKindCon name kind
221   = KindCon { 
222         tyConUnique = nameUnique name,
223         tyConName = name,
224         tyConArity = 0,
225         tyConKind = kind
226      }
227
228 mkFunTyCon :: Name -> Kind -> TyCon
229 mkFunTyCon name kind 
230   = FunTyCon { 
231         tyConUnique = nameUnique name,
232         tyConName   = name,
233         tyConKind   = kind,
234         tyConArity  = 2
235     }
236
237 tyConGenInfo :: TyCon -> Maybe (EP Id)
238 tyConGenInfo (AlgTyCon   { genInfo = info }) = info
239 tyConGenInfo (TupleTyCon { genInfo = info }) = info
240 tyConGenInfo other                           = Nothing
241
242 tyConGenIds :: TyCon -> [Id]
243 -- Returns the generic-programming Ids; these Ids need bindings
244 tyConGenIds tycon = case tyConGenInfo tycon of
245                         Nothing           -> []
246                         Just (EP from to) -> [from,to]
247
248 -- This is the making of a TyCon. Just the same as the old mkAlgTyCon,
249 -- but now you also have to pass in the generic information about the type
250 -- constructor - you can get hold of it easily (see Generics module)
251 mkAlgTyCon name kind tyvars theta argvrcs cons ncons sels flavour rec 
252               gen_info
253   = AlgTyCon {  
254         tyConName               = name,
255         tyConUnique             = nameUnique name,
256         tyConKind               = kind,
257         tyConArity              = length tyvars,
258         tyConTyVars             = tyvars,
259         tyConArgVrcs            = argvrcs,
260         algTyConTheta           = theta,
261         dataCons                = cons, 
262         selIds                  = sels,
263         noOfDataCons            = ncons,
264         algTyConClass           = Nothing,
265         algTyConFlavour         = flavour,
266         algTyConRec             = rec,
267         genInfo                 = gen_info
268     }
269
270 mkClassTyCon name kind tyvars argvrcs con clas flavour
271   = AlgTyCon {  
272         tyConName               = name,
273         tyConUnique             = nameUnique name,
274         tyConKind               = kind,
275         tyConArity              = length tyvars,
276         tyConTyVars             = tyvars,
277         tyConArgVrcs            = argvrcs,
278         algTyConTheta           = [],
279         dataCons                = [con],
280         selIds                  = [],
281         noOfDataCons            = 1,
282         algTyConClass           = Just clas,
283         algTyConFlavour         = flavour,
284         algTyConRec             = NonRecursive,
285         genInfo                 = Nothing
286     }
287
288
289 mkTupleTyCon name kind arity tyvars con boxed gen_info
290   = TupleTyCon {
291         tyConUnique = nameUnique name,
292         tyConName = name,
293         tyConKind = kind,
294         tyConArity = arity,
295         tyConBoxed = boxed,
296         tyConTyVars = tyvars,
297         dataCon = con,
298         genInfo = gen_info
299     }
300
301 -- Foreign-imported (.NET) type constructors are represented
302 -- as primitive, but *lifted*, TyCons for now. They are lifted
303 -- because the Haskell type T representing the (foreign) .NET
304 -- type T is actually implemented (in ILX) as a thunk<T>
305 -- They have PtrRep
306 mkForeignTyCon name ext_name kind arity arg_vrcs
307   = PrimTyCon {
308         tyConName    = name,
309         tyConUnique  = nameUnique name,
310         tyConKind    = kind,
311         tyConArity   = arity,
312         tyConArgVrcs = arg_vrcs,
313         primTyConRep = PtrRep,
314         isUnLifted   = False,
315         tyConExtName = ext_name
316     }
317
318
319 mkPrimTyCon name kind arity arg_vrcs rep
320   = PrimTyCon {
321         tyConName    = name,
322         tyConUnique  = nameUnique name,
323         tyConKind    = kind,
324         tyConArity   = arity,
325         tyConArgVrcs = arg_vrcs,
326         primTyConRep = rep,
327         isUnLifted   = True,
328         tyConExtName = Nothing
329     }
330
331 mkSynTyCon name kind arity tyvars rhs argvrcs
332   = SynTyCon {  
333         tyConName = name,
334         tyConUnique = nameUnique name,
335         tyConKind = kind,
336         tyConArity = arity,
337         tyConTyVars = tyvars,
338         synTyConDefn = rhs,
339         tyConArgVrcs = argvrcs
340     }
341
342 setTyConName tc name = tc {tyConName = name, tyConUnique = nameUnique name}
343
344 \end{code}
345
346 \begin{code}
347 isFunTyCon (FunTyCon {}) = True
348 isFunTyCon _             = False
349
350 isPrimTyCon (PrimTyCon {}) = True
351 isPrimTyCon _              = False
352
353 isUnLiftedTyCon (PrimTyCon  {isUnLifted = is_unlifted}) = is_unlifted
354 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity})      = not (isBoxed boxity)
355 isUnLiftedTyCon _                                       = False
356
357 -- isBoxedTyCon should not be applied to SynTyCon, nor KindCon
358 isBoxedTyCon (AlgTyCon {}) = True
359 isBoxedTyCon (FunTyCon {}) = True
360 isBoxedTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
361 isBoxedTyCon (PrimTyCon {primTyConRep = rep}) = isFollowableRep rep
362
363 -- isAlgTyCon returns True for both @data@ and @newtype@
364 isAlgTyCon (AlgTyCon {})   = True
365 isAlgTyCon (TupleTyCon {}) = True
366 isAlgTyCon other           = False
367
368 -- isDataTyCon returns False for @newtype@ and for unboxed tuples
369 isDataTyCon (AlgTyCon {algTyConFlavour = new_or_data})  = case new_or_data of
370                                                                 NewTyCon _ -> False
371                                                                 other   -> True
372 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
373 isDataTyCon other = False
374
375 isNewTyCon (AlgTyCon {algTyConFlavour = NewTyCon _}) = True 
376 isNewTyCon other                                     = False
377
378 newTyConRep (AlgTyCon {algTyConFlavour = NewTyCon rep}) = Just rep
379 newTyConRep other                                       = Nothing
380
381 -- A "product" tycon
382 --      has *one* constructor, 
383 --      is *not* existential
384 -- but
385 --      may be  DataType or NewType, 
386 --      may be  unboxed or not, 
387 --      may be  recursive or not
388 isProductTyCon (AlgTyCon {dataCons = [data_con]}) = not (isExistentialDataCon data_con)
389 isProductTyCon (TupleTyCon {})                    = True
390 isProductTyCon other                              = False
391
392 isSynTyCon (SynTyCon {}) = True
393 isSynTyCon _             = False
394
395 isEnumerationTyCon (AlgTyCon {algTyConFlavour = EnumTyCon}) = True
396 isEnumerationTyCon other                                    = False
397
398 -- The unit tycon didn't used to be classed as a tuple tycon
399 -- but I thought that was silly so I've undone it
400 -- If it can't be for some reason, it should be a AlgTyCon
401 isTupleTyCon (TupleTyCon {}) = True
402 isTupleTyCon other           = False
403
404 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
405 isUnboxedTupleTyCon other = False
406
407 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
408 isBoxedTupleTyCon other = False
409
410 tupleTyConBoxity tc = tyConBoxed tc
411
412 isRecursiveTyCon (AlgTyCon {algTyConRec = Recursive}) = True
413 isRecursiveTyCon other                                = False
414
415 -- isForeignTyCon identifies foreign-imported type constructors
416 -- For the moment, they are primitive but lifted, but that may change
417 isForeignTyCon (PrimTyCon {isUnLifted = is_unlifted}) = not is_unlifted
418 isForeignTyCon other                                  = False
419 \end{code}
420
421 \begin{code}
422 tyConDataCons :: TyCon -> [DataCon]
423 tyConDataCons tycon = ASSERT2( length cons == tyConFamilySize tycon, ppr tycon )
424                       cons
425                     where
426                       cons = tyConDataConsIfAvailable tycon
427
428 tyConDataConsIfAvailable (AlgTyCon {dataCons = cons}) = cons    -- Empty for abstract types
429 tyConDataConsIfAvailable (TupleTyCon {dataCon = con}) = [con]
430 tyConDataConsIfAvailable other                        = []
431         -- You may think this last equation should fail,
432         -- but it's quite convenient to return no constructors for
433         -- a synonym; see for example the call in TcTyClsDecls.
434
435 tyConFamilySize  :: TyCon -> Int
436 tyConFamilySize (AlgTyCon {noOfDataCons = n}) = n
437 tyConFamilySize (TupleTyCon {})               = 1
438 #ifdef DEBUG
439 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
440 #endif
441
442 tyConSelIds :: TyCon -> [Id]
443 tyConSelIds (AlgTyCon {selIds = sels}) = sels
444 tyConSelIds other_tycon                = []
445 \end{code}
446
447 \begin{code}
448 tyConPrimRep :: TyCon -> PrimRep
449 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
450 tyConPrimRep _                                = PtrRep
451 \end{code}
452
453 \begin{code}
454 tyConTheta :: TyCon -> [PredType]
455 tyConTheta (AlgTyCon {algTyConTheta = theta}) = theta
456 -- should ask about anything else
457 \end{code}
458
459 @tyConArgVrcs_maybe@ gives a list of (occPos,occNeg) flags, one for
460 each tyvar, if available.  See @calcAlgTyConArgVrcs@ for how this is
461 actually computed (in another file).
462
463 \begin{code}
464 tyConArgVrcs_maybe :: TyCon -> Maybe ArgVrcs
465
466 tyConArgVrcs_maybe (FunTyCon   {}                     ) = Just [(False,True),(True,False)]
467 tyConArgVrcs_maybe (AlgTyCon   {tyConArgVrcs = oi})     = Just oi
468 tyConArgVrcs_maybe (PrimTyCon  {tyConArgVrcs = oi})     = Just oi
469 tyConArgVrcs_maybe (TupleTyCon {tyConArity = arity   }) = Just (replicate arity (True,False))
470 tyConArgVrcs_maybe (SynTyCon   {tyConArgVrcs = oi })    = Just oi
471 tyConArgVrcs_maybe _                                    = Nothing
472 \end{code}
473
474 \begin{code}
475 getSynTyConDefn :: TyCon -> ([TyVar], Type)
476 getSynTyConDefn (SynTyCon {tyConTyVars = tyvars, synTyConDefn = ty}) = (tyvars,ty)
477 \end{code}
478
479 \begin{code}
480 maybeTyConSingleCon :: TyCon -> Maybe DataCon
481 maybeTyConSingleCon (AlgTyCon {dataCons = [c]})  = Just c
482 maybeTyConSingleCon (AlgTyCon {})                = Nothing
483 maybeTyConSingleCon (TupleTyCon {dataCon = con}) = Just con
484 maybeTyConSingleCon (PrimTyCon {})               = Nothing
485 maybeTyConSingleCon (FunTyCon {})                = Nothing  -- case at funty
486 maybeTyConSingleCon tc = pprPanic "maybeTyConSingleCon: unexpected tycon " $
487                          ppr tc
488 \end{code}
489
490 \begin{code}
491 isClassTyCon :: TyCon -> Bool
492 isClassTyCon (AlgTyCon {algTyConClass = Just _}) = True
493 isClassTyCon other_tycon                         = False
494
495 tyConClass_maybe :: TyCon -> Maybe Class
496 tyConClass_maybe (AlgTyCon {algTyConClass = maybe_clas}) = maybe_clas
497 tyConClass_maybe ther_tycon                              = Nothing
498 \end{code}
499
500
501 %************************************************************************
502 %*                                                                      *
503 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
504 %*                                                                      *
505 %************************************************************************
506
507 @TyCon@s are compared by comparing their @Unique@s.
508
509 The strictness analyser needs @Ord@. It is a lexicographic order with
510 the property @(a<=b) || (b<=a)@.
511
512 \begin{code}
513 instance Eq TyCon where
514     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
515     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
516
517 instance Ord TyCon where
518     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
519     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
520     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
521     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
522     compare a b = getUnique a `compare` getUnique b
523
524 instance Uniquable TyCon where
525     getUnique tc = tyConUnique tc
526
527 instance Outputable TyCon where
528     ppr tc  = ppr (getName tc) 
529
530 instance NamedThing TyCon where
531     getName = tyConName
532 \end{code}
533
534
535 %************************************************************************
536 %*                                                                      *
537 \subsection{Kind constructors}
538 %*                                                                      *
539 %************************************************************************
540
541 @matchesTyCon tc1 tc2@ checks whether an appliation
542 (tc1 t1..tn) matches (tc2 t1..tn).  By "matches" we basically mean "equals",
543 except that at the kind level tc2 might have more boxity info than tc1.
544
545 \begin{code}
546 matchesTyCon :: TyCon   -- Expected (e.g. arg type of function)
547              -> TyCon   -- Inferred (e.g. type of actual arg to function)
548              -> Bool
549
550 matchesTyCon tc1 tc2 =  uniq1 == uniq2 || uniq1 == anyBoxConKey
551                      where
552                         uniq1 = tyConUnique tc1
553                         uniq2 = tyConUnique tc2
554 \end{code}
555
556
557