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