remove some outdated comments
[ghc-base.git] / Data / Typeable.hs
1 {-# OPTIONS_GHC -fno-implicit-prelude -fallow-overlapping-instances #-}
2
3 -- The -fallow-overlapping-instances flag allows the user to over-ride
4 -- the instances for Typeable given here.  In particular, we provide an instance
5 --      instance ... => Typeable (s a) 
6 -- But a user might want to say
7 --      instance ... => Typeable (MyType a b)
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module      :  Data.Typeable
12 -- Copyright   :  (c) The University of Glasgow, CWI 2001--2004
13 -- License     :  BSD-style (see the file libraries/base/LICENSE)
14 -- 
15 -- Maintainer  :  libraries@haskell.org
16 -- Stability   :  experimental
17 -- Portability :  portable
18 --
19 -- The 'Typeable' class reifies types to some extent by associating type
20 -- representations to types. These type representations can be compared,
21 -- and one can in turn define a type-safe cast operation. To this end,
22 -- an unsafe cast is guarded by a test for type (representation)
23 -- equivalence. The module "Data.Dynamic" uses Typeable for an
24 -- implementation of dynamics. The module "Data.Generics" uses Typeable
25 -- and type-safe cast (but not dynamics) to support the \"Scrap your
26 -- boilerplate\" style of generic programming.
27 --
28 -----------------------------------------------------------------------------
29
30 module Data.Typeable
31   (
32
33         -- * The Typeable class
34         Typeable( typeOf ),     -- :: a -> TypeRep
35
36         -- * Type-safe cast
37         cast,                   -- :: (Typeable a, Typeable b) => a -> Maybe b
38         gcast,                  -- a generalisation of cast
39
40         -- * Type representations
41         TypeRep,        -- abstract, instance of: Eq, Show, Typeable
42         TyCon,          -- abstract, instance of: Eq, Show, Typeable
43
44         -- * Construction of type representations
45         mkTyCon,        -- :: String  -> TyCon
46         mkTyConApp,     -- :: TyCon   -> [TypeRep] -> TypeRep
47         mkAppTy,        -- :: TypeRep -> TypeRep   -> TypeRep
48         mkFunTy,        -- :: TypeRep -> TypeRep   -> TypeRep
49
50         -- * Observation of type representations
51         splitTyConApp,  -- :: TypeRep -> (TyCon, [TypeRep])
52         funResultTy,    -- :: TypeRep -> TypeRep   -> Maybe TypeRep
53         typeRepTyCon,   -- :: TypeRep -> TyCon
54         typeRepArgs,    -- :: TypeRep -> [TypeRep]
55         tyConString,    -- :: TyCon   -> String
56
57         -- * The other Typeable classes
58         -- | /Note:/ The general instances are provided for GHC only.
59         Typeable1( typeOf1 ),   -- :: t a -> TypeRep
60         Typeable2( typeOf2 ),   -- :: t a b -> TypeRep
61         Typeable3( typeOf3 ),   -- :: t a b c -> TypeRep
62         Typeable4( typeOf4 ),   -- :: t a b c d -> TypeRep
63         Typeable5( typeOf5 ),   -- :: t a b c d e -> TypeRep
64         Typeable6( typeOf6 ),   -- :: t a b c d e f -> TypeRep
65         Typeable7( typeOf7 ),   -- :: t a b c d e f g -> TypeRep
66         gcast1,                 -- :: ... => c (t a) -> Maybe (c (t' a))
67         gcast2,                 -- :: ... => c (t a b) -> Maybe (c (t' a b))
68
69         -- * Default instances
70         -- | /Note:/ These are not needed by GHC, for which these instances
71         -- are generated by general instance declarations.
72         typeOfDefault,  -- :: (Typeable1 t, Typeable a) => t a -> TypeRep
73         typeOf1Default, -- :: (Typeable2 t, Typeable a) => t a b -> TypeRep
74         typeOf2Default, -- :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
75         typeOf3Default, -- :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
76         typeOf4Default, -- :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
77         typeOf5Default, -- :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
78         typeOf6Default  -- :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
79
80   ) where
81
82 import qualified Data.HashTable as HT
83 import Data.Maybe
84 import Data.Either
85 import Data.Int
86 import Data.Word
87 import Data.List( foldl )
88
89 #ifdef __GLASGOW_HASKELL__
90 import GHC.Base
91 import GHC.Show
92 import GHC.Err
93 import GHC.Num
94 import GHC.Float
95 import GHC.Real         ( rem, Ratio )
96 import GHC.IOBase       (IORef,newIORef,unsafePerformIO)
97
98 -- These imports are so we can define Typeable instances
99 -- It'd be better to give Typeable instances in the modules themselves
100 -- but they all have to be compiled before Typeable
101 import GHC.IOBase       ( IO, MVar, Exception, ArithException, IOException, 
102                           ArrayException, AsyncException, Handle )
103 import GHC.ST           ( ST )
104 import GHC.STRef        ( STRef )
105 import GHC.Ptr          ( Ptr, FunPtr )
106 import GHC.ForeignPtr   ( ForeignPtr )
107 import GHC.Stable       ( StablePtr, newStablePtr, freeStablePtr,
108                           deRefStablePtr, castStablePtrToPtr,
109                           castPtrToStablePtr )
110 import GHC.Exception    ( block )
111 import GHC.Arr          ( Array, STArray )
112
113 #endif
114
115 #ifdef __HUGS__
116 import Hugs.Prelude     ( Key(..), TypeRep(..), TyCon(..), Ratio,
117                           Exception, ArithException, IOException,
118                           ArrayException, AsyncException, Handle,
119                           Ptr, FunPtr, ForeignPtr, StablePtr )
120 import Hugs.IORef       ( IORef, newIORef, readIORef, writeIORef )
121 import Hugs.IOExts      ( unsafePerformIO, unsafeCoerce )
122         -- For the Typeable instance
123 import Hugs.Array       ( Array )
124 import Hugs.ConcBase    ( MVar )
125 #endif
126
127 #ifdef __GLASGOW_HASKELL__
128 unsafeCoerce :: a -> b
129 unsafeCoerce = unsafeCoerce#
130 #endif
131
132 #ifdef __NHC__
133 import NonStdUnsafeCoerce (unsafeCoerce)
134 import NHC.IOExtras (IORef,newIORef,readIORef,writeIORef,unsafePerformIO)
135 import IO (Handle)
136 import Ratio (Ratio)
137         -- For the Typeable instance
138 import NHC.FFI  ( Ptr,FunPtr,StablePtr,ForeignPtr )
139 import Array    ( Array )
140 #endif
141
142 #include "Typeable.h"
143
144 #ifndef __HUGS__
145
146 -------------------------------------------------------------
147 --
148 --              Type representations
149 --
150 -------------------------------------------------------------
151
152 -- | A concrete representation of a (monomorphic) type.  'TypeRep'
153 -- supports reasonably efficient equality.
154 data TypeRep = TypeRep !Key TyCon [TypeRep] 
155
156 -- Compare keys for equality
157 instance Eq TypeRep where
158   (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
159
160 -- | An abstract representation of a type constructor.  'TyCon' objects can
161 -- be built using 'mkTyCon'.
162 data TyCon = TyCon !Key String
163
164 instance Eq TyCon where
165   (TyCon t1 _) == (TyCon t2 _) = t1 == t2
166
167 #endif
168
169         -- 
170         -- let fTy = mkTyCon "Foo" in show (mkTyConApp (mkTyCon ",,")
171         --                                 [fTy,fTy,fTy])
172         -- 
173         -- returns "(Foo,Foo,Foo)"
174         --
175         -- The TypeRep Show instance promises to print tuple types
176         -- correctly. Tuple type constructors are specified by a 
177         -- sequence of commas, e.g., (mkTyCon ",,,,") returns
178         -- the 5-tuple tycon.
179
180 ----------------- Construction --------------------
181
182 -- | Applies a type constructor to a sequence of types
183 mkTyConApp  :: TyCon -> [TypeRep] -> TypeRep
184 mkTyConApp tc@(TyCon tc_k _) args 
185   = TypeRep (appKeys tc_k arg_ks) tc args
186   where
187     arg_ks = [k | TypeRep k _ _ <- args]
188
189 -- | A special case of 'mkTyConApp', which applies the function 
190 -- type constructor to a pair of types.
191 mkFunTy  :: TypeRep -> TypeRep -> TypeRep
192 mkFunTy f a = mkTyConApp funTc [f,a]
193
194 -- | Splits a type constructor application
195 splitTyConApp :: TypeRep -> (TyCon,[TypeRep])
196 splitTyConApp (TypeRep _ tc trs) = (tc,trs)
197
198 -- | Applies a type to a function type.  Returns: @'Just' u@ if the
199 -- first argument represents a function of type @t -> u@ and the
200 -- second argument represents a function of type @t@.  Otherwise,
201 -- returns 'Nothing'.
202 funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep
203 funResultTy trFun trArg
204   = case splitTyConApp trFun of
205       (tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2
206       _ -> Nothing
207
208 -- | Adds a TypeRep argument to a TypeRep.
209 mkAppTy :: TypeRep -> TypeRep -> TypeRep
210 mkAppTy (TypeRep tr_k tc trs) arg_tr
211   = let (TypeRep arg_k _ _) = arg_tr
212      in  TypeRep (appKey tr_k arg_k) tc (trs++[arg_tr])
213
214 -- If we enforce the restriction that there is only one
215 -- @TyCon@ for a type & it is shared among all its uses,
216 -- we can map them onto Ints very simply. The benefit is,
217 -- of course, that @TyCon@s can then be compared efficiently.
218
219 -- Provided the implementor of other @Typeable@ instances
220 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
221 -- this will work. 
222
223 -- If this constraint does turn out to be a sore thumb, changing
224 -- the Eq instance for TyCons is trivial.
225
226 -- | Builds a 'TyCon' object representing a type constructor.  An
227 -- implementation of "Data.Typeable" should ensure that the following holds:
228 --
229 -- >  mkTyCon "a" == mkTyCon "a"
230 --
231
232 mkTyCon :: String       -- ^ the name of the type constructor (should be unique
233                         -- in the program, so it might be wise to use the
234                         -- fully qualified name).
235         -> TyCon        -- ^ A unique 'TyCon' object
236 mkTyCon str = TyCon (mkTyConKey str) str
237
238 ----------------- Observation ---------------------
239
240 -- | Observe the type constructor of a type representation
241 typeRepTyCon :: TypeRep -> TyCon
242 typeRepTyCon (TypeRep _ tc _) = tc
243
244 -- | Observe the argument types of a type representation
245 typeRepArgs :: TypeRep -> [TypeRep]
246 typeRepArgs (TypeRep _ _ args) = args
247
248 -- | Observe string encoding of a type representation
249 tyConString :: TyCon   -> String
250 tyConString  (TyCon _ str) = str
251
252 ----------------- Showing TypeReps --------------------
253
254 instance Show TypeRep where
255   showsPrec p (TypeRep _ tycon tys) =
256     case tys of
257       [] -> showsPrec p tycon
258       [x]   | tycon == listTc -> showChar '[' . shows x . showChar ']'
259       [a,r] | tycon == funTc  -> showParen (p > 8) $
260                                  showsPrec 9 a .
261                                  showString " -> " .
262                                  showsPrec 8 r
263       xs | isTupleTyCon tycon -> showTuple tycon xs
264          | otherwise         ->
265             showParen (p > 9) $
266             showsPrec p tycon . 
267             showChar ' '      . 
268             showArgs tys
269
270 instance Show TyCon where
271   showsPrec _ (TyCon _ s) = showString s
272
273 isTupleTyCon :: TyCon -> Bool
274 isTupleTyCon (TyCon _ (',':_)) = True
275 isTupleTyCon _                 = False
276
277 -- Some (Show.TypeRep) helpers:
278
279 showArgs :: Show a => [a] -> ShowS
280 showArgs [] = id
281 showArgs [a] = showsPrec 10 a
282 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as 
283
284 showTuple :: TyCon -> [TypeRep] -> ShowS
285 showTuple (TyCon _ str) args = showChar '(' . go str args
286  where
287   go [] [a] = showsPrec 10 a . showChar ')'
288   go _  []  = showChar ')' -- a failure condition, really.
289   go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
290   go _ _   = showChar ')'
291
292 -------------------------------------------------------------
293 --
294 --      The Typeable class and friends
295 --
296 -------------------------------------------------------------
297
298 -- | The class 'Typeable' allows a concrete representation of a type to
299 -- be calculated.
300 class Typeable a where
301   typeOf :: a -> TypeRep
302   -- ^ Takes a value of type @a@ and returns a concrete representation
303   -- of that type.  The /value/ of the argument should be ignored by
304   -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
305   -- the argument.
306
307 -- | Variant for unary type constructors
308 class Typeable1 t where
309   typeOf1 :: t a -> TypeRep
310
311 -- | For defining a 'Typeable' instance from any 'Typeable1' instance.
312 typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
313 typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
314  where
315    argType :: t a -> a
316    argType =  undefined
317
318 -- | Variant for binary type constructors
319 class Typeable2 t where
320   typeOf2 :: t a b -> TypeRep
321
322 -- | For defining a 'Typeable1' instance from any 'Typeable2' instance.
323 typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
324 typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
325  where
326    argType :: t a b -> a
327    argType =  undefined
328
329 -- | Variant for 3-ary type constructors
330 class Typeable3 t where
331   typeOf3 :: t a b c -> TypeRep
332
333 -- | For defining a 'Typeable2' instance from any 'Typeable3' instance.
334 typeOf2Default :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
335 typeOf2Default x = typeOf3 x `mkAppTy` typeOf (argType x)
336  where
337    argType :: t a b c -> a
338    argType =  undefined
339
340 -- | Variant for 4-ary type constructors
341 class Typeable4 t where
342   typeOf4 :: t a b c d -> TypeRep
343
344 -- | For defining a 'Typeable3' instance from any 'Typeable4' instance.
345 typeOf3Default :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
346 typeOf3Default x = typeOf4 x `mkAppTy` typeOf (argType x)
347  where
348    argType :: t a b c d -> a
349    argType =  undefined
350
351 -- | Variant for 5-ary type constructors
352 class Typeable5 t where
353   typeOf5 :: t a b c d e -> TypeRep
354
355 -- | For defining a 'Typeable4' instance from any 'Typeable5' instance.
356 typeOf4Default :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
357 typeOf4Default x = typeOf5 x `mkAppTy` typeOf (argType x)
358  where
359    argType :: t a b c d e -> a
360    argType =  undefined
361
362 -- | Variant for 6-ary type constructors
363 class Typeable6 t where
364   typeOf6 :: t a b c d e f -> TypeRep
365
366 -- | For defining a 'Typeable5' instance from any 'Typeable6' instance.
367 typeOf5Default :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
368 typeOf5Default x = typeOf6 x `mkAppTy` typeOf (argType x)
369  where
370    argType :: t a b c d e f -> a
371    argType =  undefined
372
373 -- | Variant for 7-ary type constructors
374 class Typeable7 t where
375   typeOf7 :: t a b c d e f g -> TypeRep
376
377 -- | For defining a 'Typeable6' instance from any 'Typeable7' instance.
378 typeOf6Default :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
379 typeOf6Default x = typeOf7 x `mkAppTy` typeOf (argType x)
380  where
381    argType :: t a b c d e f g -> a
382    argType =  undefined
383
384 #ifdef __GLASGOW_HASKELL__
385 -- Given a @Typeable@/n/ instance for an /n/-ary type constructor,
386 -- define the instances for partial applications.
387 -- Programmers using non-GHC implementations must do this manually
388 -- for each type constructor.
389 -- (The INSTANCE_TYPEABLE/n/ macros in Typeable.h include this.)
390
391 -- | One Typeable instance for all Typeable1 instances
392 instance (Typeable1 s, Typeable a)
393        => Typeable (s a) where
394   typeOf = typeOfDefault
395
396 -- | One Typeable1 instance for all Typeable2 instances
397 instance (Typeable2 s, Typeable a)
398        => Typeable1 (s a) where
399   typeOf1 = typeOf1Default
400
401 -- | One Typeable2 instance for all Typeable3 instances
402 instance (Typeable3 s, Typeable a)
403        => Typeable2 (s a) where
404   typeOf2 = typeOf2Default
405
406 -- | One Typeable3 instance for all Typeable4 instances
407 instance (Typeable4 s, Typeable a)
408        => Typeable3 (s a) where
409   typeOf3 = typeOf3Default
410
411 -- | One Typeable4 instance for all Typeable5 instances
412 instance (Typeable5 s, Typeable a)
413        => Typeable4 (s a) where
414   typeOf4 = typeOf4Default
415
416 -- | One Typeable5 instance for all Typeable6 instances
417 instance (Typeable6 s, Typeable a)
418        => Typeable5 (s a) where
419   typeOf5 = typeOf5Default
420
421 -- | One Typeable6 instance for all Typeable7 instances
422 instance (Typeable7 s, Typeable a)
423        => Typeable6 (s a) where
424   typeOf6 = typeOf6Default
425
426 #endif /* __GLASGOW_HASKELL__ */
427
428 -------------------------------------------------------------
429 --
430 --              Type-safe cast
431 --
432 -------------------------------------------------------------
433
434 -- | The type-safe cast operation
435 cast :: (Typeable a, Typeable b) => a -> Maybe b
436 cast x = r
437        where
438          r = if typeOf x == typeOf (fromJust r)
439                then Just $ unsafeCoerce x
440                else Nothing
441
442 -- | A flexible variation parameterised in a type constructor
443 gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
444 gcast x = r
445  where
446   r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
447         then Just $ unsafeCoerce x
448         else Nothing
449   getArg :: c x -> x 
450   getArg = undefined
451
452 -- | Cast for * -> *
453 gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a)) 
454 gcast1 x = r
455  where
456   r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
457        then Just $ unsafeCoerce x
458        else Nothing
459   getArg :: c x -> x 
460   getArg = undefined
461
462 -- | Cast for * -> * -> *
463 gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b)) 
464 gcast2 x = r
465  where
466   r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
467        then Just $ unsafeCoerce x
468        else Nothing
469   getArg :: c x -> x 
470   getArg = undefined
471
472 -------------------------------------------------------------
473 --
474 --      Instances of the Typeable classes for Prelude types
475 --
476 -------------------------------------------------------------
477
478 INSTANCE_TYPEABLE0((),unitTc,"()")
479 INSTANCE_TYPEABLE1([],listTc,"[]")
480 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
481 INSTANCE_TYPEABLE1(Ratio,ratioTc,"Ratio")
482 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
483 INSTANCE_TYPEABLE2((->),funTc,"->")
484 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
485
486 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
487 -- Types defined in GHC.IOBase
488 INSTANCE_TYPEABLE1(MVar,mvarTc,"MVar" )
489 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
490 INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
491 INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
492 INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
493 INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
494 #endif
495
496 -- Types defined in GHC.Arr
497 INSTANCE_TYPEABLE2(Array,arrayTc,"Array")
498
499 #ifdef __GLASGOW_HASKELL__
500 -- Hugs has these too, but their Typeable<n> instances are defined
501 -- elsewhere to keep this module within Haskell 98.
502 -- This is important because every invocation of runhugs or ffihugs
503 -- uses this module via Data.Dynamic.
504 INSTANCE_TYPEABLE2(ST,stTc,"ST")
505 INSTANCE_TYPEABLE2(STRef,stRefTc,"STRef")
506 INSTANCE_TYPEABLE3(STArray,sTArrayTc,"STArray")
507 #endif
508
509 #ifndef __NHC__
510 INSTANCE_TYPEABLE2((,),pairTc,",")
511 INSTANCE_TYPEABLE3((,,),tup3Tc,",,")
512
513 tup4Tc :: TyCon
514 tup4Tc = mkTyCon ",,,"
515
516 instance Typeable4 (,,,) where
517   typeOf4 tu = mkTyConApp tup4Tc []
518
519 tup5Tc :: TyCon
520 tup5Tc = mkTyCon ",,,,"
521
522 instance Typeable5 (,,,,) where
523   typeOf5 tu = mkTyConApp tup5Tc []
524
525 tup6Tc :: TyCon
526 tup6Tc = mkTyCon ",,,,,"
527
528 instance Typeable6 (,,,,,) where
529   typeOf6 tu = mkTyConApp tup6Tc []
530
531 tup7Tc :: TyCon
532 tup7Tc = mkTyCon ",,,,,,"
533
534 instance Typeable7 (,,,,,,) where
535   typeOf7 tu = mkTyConApp tup7Tc []
536 #endif /* __NHC__ */
537
538 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
539 INSTANCE_TYPEABLE1(FunPtr,funPtrTc,"FunPtr")
540 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
541 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
542 INSTANCE_TYPEABLE1(IORef,iORefTc,"IORef")
543
544 -------------------------------------------------------
545 --
546 -- Generate Typeable instances for standard datatypes
547 --
548 -------------------------------------------------------
549
550 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
551 INSTANCE_TYPEABLE0(Char,charTc,"Char")
552 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
553 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
554 INSTANCE_TYPEABLE0(Int,intTc,"Int")
555 #ifndef __NHC__
556 INSTANCE_TYPEABLE0(Word,wordTc,"Word" )
557 #endif
558 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
559 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
560 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
561
562 INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
563 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
564 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
565 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
566
567 INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
568 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
569 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
570 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
571
572 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
573 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
574
575 #ifdef __GLASGOW_HASKELL__
576 INSTANCE_TYPEABLE0(RealWorld,realWorldTc,"RealWorld")
577 #endif
578
579 ---------------------------------------------
580 --
581 --              Internals 
582 --
583 ---------------------------------------------
584
585 #ifndef __HUGS__
586 newtype Key = Key Int deriving( Eq )
587 #endif
588
589 data KeyPr = KeyPr !Key !Key deriving( Eq )
590
591 hashKP :: KeyPr -> Int32
592 hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
593
594 data Cache = Cache { next_key :: !(IORef Key),  -- Not used by GHC (calls genSym instead)
595                      tc_tbl   :: !(HT.HashTable String Key),
596                      ap_tbl   :: !(HT.HashTable KeyPr Key) }
597
598 {-# NOINLINE cache #-}
599 #ifdef __GLASGOW_HASKELL__
600 foreign import ccall unsafe "RtsTypeable.h getOrSetTypeableStore"
601     getOrSetTypeableStore :: Ptr a -> IO (Ptr a)
602 #endif
603
604 cache :: Cache
605 cache = unsafePerformIO $ do
606                 empty_tc_tbl <- HT.new (==) HT.hashString
607                 empty_ap_tbl <- HT.new (==) hashKP
608                 key_loc      <- newIORef (Key 1) 
609                 let ret = Cache {       next_key = key_loc,
610                                         tc_tbl = empty_tc_tbl, 
611                                         ap_tbl = empty_ap_tbl }
612 #ifdef __GLASGOW_HASKELL__
613                 block $ do
614                         stable_ref <- newStablePtr ret
615                         let ref = castStablePtrToPtr stable_ref
616                         ref2 <- getOrSetTypeableStore ref
617                         if ref==ref2
618                                 then deRefStablePtr stable_ref
619                                 else do
620                                         freeStablePtr stable_ref
621                                         deRefStablePtr
622                                                 (castPtrToStablePtr ref2)
623 #else
624                 return ret
625 #endif
626
627 newKey :: IORef Key -> IO Key
628 #ifdef __GLASGOW_HASKELL__
629 newKey kloc = do i <- genSym; return (Key i)
630 #else
631 newKey kloc = do { k@(Key i) <- readIORef kloc ;
632                    writeIORef kloc (Key (i+1)) ;
633                    return k }
634 #endif
635
636 #ifdef __GLASGOW_HASKELL__
637 foreign import ccall unsafe "genSymZh"
638   genSym :: IO Int
639 #endif
640
641 mkTyConKey :: String -> Key
642 mkTyConKey str 
643   = unsafePerformIO $ do
644         let Cache {next_key = kloc, tc_tbl = tbl} = cache
645         mb_k <- HT.lookup tbl str
646         case mb_k of
647           Just k  -> return k
648           Nothing -> do { k <- newKey kloc ;
649                           HT.insert tbl str k ;
650                           return k }
651
652 appKey :: Key -> Key -> Key
653 appKey k1 k2
654   = unsafePerformIO $ do
655         let Cache {next_key = kloc, ap_tbl = tbl} = cache
656         mb_k <- HT.lookup tbl kpr
657         case mb_k of
658           Just k  -> return k
659           Nothing -> do { k <- newKey kloc ;
660                           HT.insert tbl kpr k ;
661                           return k }
662   where
663     kpr = KeyPr k1 k2
664
665 appKeys :: Key -> [Key] -> Key
666 appKeys k ks = foldl appKey k ks