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