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