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