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