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