FIX dynamic001 dynamic002: isTupleTyCon had rotted
[ghc-base.git] / Data / Typeable.hs
1 {-# OPTIONS_GHC -fno-implicit-prelude -fallow-overlapping-instances -funbox-strict-fields #-}
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         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.Either
87 import Data.Int
88 import Data.Word
89 import Data.List( foldl )
90 import Unsafe.Coerce
91
92 #ifdef __GLASGOW_HASKELL__
93 import GHC.Base
94 import GHC.Show
95 import GHC.Err
96 import GHC.Num
97 import GHC.Float
98 import GHC.Real         ( rem, Ratio )
99 import GHC.IOBase       (IORef,newIORef,unsafePerformIO)
100
101 -- These imports are so we can define Typeable instances
102 -- It'd be better to give Typeable instances in the modules themselves
103 -- but they all have to be compiled before Typeable
104 import GHC.IOBase       ( IO, MVar, Exception, ArithException, IOException, 
105                           ArrayException, AsyncException, Handle )
106 import GHC.ST           ( ST )
107 import GHC.STRef        ( STRef )
108 import GHC.Ptr          ( Ptr, FunPtr )
109 import GHC.ForeignPtr   ( ForeignPtr )
110 import GHC.Stable       ( StablePtr, newStablePtr, freeStablePtr,
111                           deRefStablePtr, castStablePtrToPtr,
112                           castPtrToStablePtr )
113 import GHC.Exception    ( block )
114 import GHC.Arr          ( Array, STArray )
115
116 #endif
117
118 #ifdef __HUGS__
119 import Hugs.Prelude     ( Key(..), TypeRep(..), TyCon(..), Ratio,
120                           Exception, ArithException, IOException,
121                           ArrayException, AsyncException, Handle,
122                           Ptr, FunPtr, ForeignPtr, StablePtr )
123 import Hugs.IORef       ( IORef, newIORef, readIORef, writeIORef )
124 import Hugs.IOExts      ( unsafePerformIO )
125         -- For the Typeable instance
126 import Hugs.Array       ( Array )
127 import Hugs.ConcBase    ( MVar )
128 #endif
129
130 #ifdef __NHC__
131 import NHC.IOExtras (IORef,newIORef,readIORef,writeIORef,unsafePerformIO)
132 import IO (Handle)
133 import Ratio (Ratio)
134         -- For the Typeable instance
135 import NHC.FFI  ( Ptr,FunPtr,StablePtr,ForeignPtr )
136 import Array    ( Array )
137 #endif
138
139 #include "Typeable.h"
140
141 #ifndef __HUGS__
142
143 -------------------------------------------------------------
144 --
145 --              Type representations
146 --
147 -------------------------------------------------------------
148
149 -- | A concrete representation of a (monomorphic) type.  'TypeRep'
150 -- supports reasonably efficient equality.
151 data TypeRep = TypeRep !Key TyCon [TypeRep] 
152
153 -- Compare keys for equality
154 instance Eq TypeRep where
155   (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
156
157 -- | An abstract representation of a type constructor.  'TyCon' objects can
158 -- be built using 'mkTyCon'.
159 data TyCon = TyCon !Key String
160
161 instance Eq TyCon where
162   (TyCon t1 _) == (TyCon t2 _) = t1 == t2
163 #endif
164
165 -- | Returns a unique integer associated with a 'TypeRep'.  This can
166 -- be used for making a mapping with TypeReps
167 -- as the keys, for example.  It is guaranteed that @t1 == t2@ if and only if
168 -- @typeRepKey t1 == typeRepKey t2@.
169 --
170 -- It is in the 'IO' monad because the actual value of the key may
171 -- vary from run to run of the program.  You should only rely on
172 -- the equality property, not any actual key value.  The relative ordering
173 -- of keys has no meaning either.
174 --
175 typeRepKey :: TypeRep -> IO Int
176 typeRepKey (TypeRep (Key i) _ _) = return i
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 showsTypeRep :: TypeRep -> ShowS
280 showsTypeRep = shows
281
282 instance Show TyCon where
283   showsPrec _ (TyCon _ s) = showString s
284
285 isTupleTyCon :: TyCon -> Bool
286 isTupleTyCon (TyCon _ ('(':',':_)) = True
287 isTupleTyCon _                     = False
288
289 -- Some (Show.TypeRep) helpers:
290
291 showArgs :: Show a => [a] -> ShowS
292 showArgs [] = id
293 showArgs [a] = showsPrec 10 a
294 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as 
295
296 showTuple :: TyCon -> [TypeRep] -> ShowS
297 showTuple (TyCon _ str) args = showChar '(' . go str args
298  where
299   go [] [a] = showsPrec 10 a . showChar ')'
300   go _  []  = showChar ')' -- a failure condition, really.
301   go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
302   go _ _   = showChar ')'
303
304 -------------------------------------------------------------
305 --
306 --      The Typeable class and friends
307 --
308 -------------------------------------------------------------
309
310 -- | The class 'Typeable' allows a concrete representation of a type to
311 -- be calculated.
312 class Typeable a where
313   typeOf :: a -> TypeRep
314   -- ^ Takes a value of type @a@ and returns a concrete representation
315   -- of that type.  The /value/ of the argument should be ignored by
316   -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
317   -- the argument.
318
319 -- | Variant for unary type constructors
320 class Typeable1 t where
321   typeOf1 :: t a -> TypeRep
322
323 -- | For defining a 'Typeable' instance from any 'Typeable1' instance.
324 typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
325 typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
326  where
327    argType :: t a -> a
328    argType =  undefined
329
330 -- | Variant for binary type constructors
331 class Typeable2 t where
332   typeOf2 :: t a b -> TypeRep
333
334 -- | For defining a 'Typeable1' instance from any 'Typeable2' instance.
335 typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
336 typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
337  where
338    argType :: t a b -> a
339    argType =  undefined
340
341 -- | Variant for 3-ary type constructors
342 class Typeable3 t where
343   typeOf3 :: t a b c -> TypeRep
344
345 -- | For defining a 'Typeable2' instance from any 'Typeable3' instance.
346 typeOf2Default :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
347 typeOf2Default x = typeOf3 x `mkAppTy` typeOf (argType x)
348  where
349    argType :: t a b c -> a
350    argType =  undefined
351
352 -- | Variant for 4-ary type constructors
353 class Typeable4 t where
354   typeOf4 :: t a b c d -> TypeRep
355
356 -- | For defining a 'Typeable3' instance from any 'Typeable4' instance.
357 typeOf3Default :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
358 typeOf3Default x = typeOf4 x `mkAppTy` typeOf (argType x)
359  where
360    argType :: t a b c d -> a
361    argType =  undefined
362
363 -- | Variant for 5-ary type constructors
364 class Typeable5 t where
365   typeOf5 :: t a b c d e -> TypeRep
366
367 -- | For defining a 'Typeable4' instance from any 'Typeable5' instance.
368 typeOf4Default :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
369 typeOf4Default x = typeOf5 x `mkAppTy` typeOf (argType x)
370  where
371    argType :: t a b c d e -> a
372    argType =  undefined
373
374 -- | Variant for 6-ary type constructors
375 class Typeable6 t where
376   typeOf6 :: t a b c d e f -> TypeRep
377
378 -- | For defining a 'Typeable5' instance from any 'Typeable6' instance.
379 typeOf5Default :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
380 typeOf5Default x = typeOf6 x `mkAppTy` typeOf (argType x)
381  where
382    argType :: t a b c d e f -> a
383    argType =  undefined
384
385 -- | Variant for 7-ary type constructors
386 class Typeable7 t where
387   typeOf7 :: t a b c d e f g -> TypeRep
388
389 -- | For defining a 'Typeable6' instance from any 'Typeable7' instance.
390 typeOf6Default :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
391 typeOf6Default x = typeOf7 x `mkAppTy` typeOf (argType x)
392  where
393    argType :: t a b c d e f g -> a
394    argType =  undefined
395
396 #ifdef __GLASGOW_HASKELL__
397 -- Given a @Typeable@/n/ instance for an /n/-ary type constructor,
398 -- define the instances for partial applications.
399 -- Programmers using non-GHC implementations must do this manually
400 -- for each type constructor.
401 -- (The INSTANCE_TYPEABLE/n/ macros in Typeable.h include this.)
402
403 -- | One Typeable instance for all Typeable1 instances
404 instance (Typeable1 s, Typeable a)
405        => Typeable (s a) where
406   typeOf = typeOfDefault
407
408 -- | One Typeable1 instance for all Typeable2 instances
409 instance (Typeable2 s, Typeable a)
410        => Typeable1 (s a) where
411   typeOf1 = typeOf1Default
412
413 -- | One Typeable2 instance for all Typeable3 instances
414 instance (Typeable3 s, Typeable a)
415        => Typeable2 (s a) where
416   typeOf2 = typeOf2Default
417
418 -- | One Typeable3 instance for all Typeable4 instances
419 instance (Typeable4 s, Typeable a)
420        => Typeable3 (s a) where
421   typeOf3 = typeOf3Default
422
423 -- | One Typeable4 instance for all Typeable5 instances
424 instance (Typeable5 s, Typeable a)
425        => Typeable4 (s a) where
426   typeOf4 = typeOf4Default
427
428 -- | One Typeable5 instance for all Typeable6 instances
429 instance (Typeable6 s, Typeable a)
430        => Typeable5 (s a) where
431   typeOf5 = typeOf5Default
432
433 -- | One Typeable6 instance for all Typeable7 instances
434 instance (Typeable7 s, Typeable a)
435        => Typeable6 (s a) where
436   typeOf6 = typeOf6Default
437
438 #endif /* __GLASGOW_HASKELL__ */
439
440 -------------------------------------------------------------
441 --
442 --              Type-safe cast
443 --
444 -------------------------------------------------------------
445
446 -- | The type-safe cast operation
447 cast :: (Typeable a, Typeable b) => a -> Maybe b
448 cast x = r
449        where
450          r = if typeOf x == typeOf (fromJust r)
451                then Just $ unsafeCoerce x
452                else Nothing
453
454 -- | A flexible variation parameterised in a type constructor
455 gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
456 gcast x = r
457  where
458   r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
459         then Just $ unsafeCoerce x
460         else Nothing
461   getArg :: c x -> x 
462   getArg = undefined
463
464 -- | Cast for * -> *
465 gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a)) 
466 gcast1 x = r
467  where
468   r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
469        then Just $ unsafeCoerce x
470        else Nothing
471   getArg :: c x -> x 
472   getArg = undefined
473
474 -- | Cast for * -> * -> *
475 gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b)) 
476 gcast2 x = r
477  where
478   r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
479        then Just $ unsafeCoerce x
480        else Nothing
481   getArg :: c x -> x 
482   getArg = undefined
483
484 -------------------------------------------------------------
485 --
486 --      Instances of the Typeable classes for Prelude types
487 --
488 -------------------------------------------------------------
489
490 INSTANCE_TYPEABLE0((),unitTc,"()")
491 INSTANCE_TYPEABLE1([],listTc,"[]")
492 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
493 INSTANCE_TYPEABLE1(Ratio,ratioTc,"Ratio")
494 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
495 INSTANCE_TYPEABLE2((->),funTc,"->")
496 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
497
498 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
499 -- Types defined in GHC.IOBase
500 INSTANCE_TYPEABLE1(MVar,mvarTc,"MVar" )
501 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
502 INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
503 INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
504 INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
505 INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
506 #endif
507
508 -- Types defined in GHC.Arr
509 INSTANCE_TYPEABLE2(Array,arrayTc,"Array")
510
511 #ifdef __GLASGOW_HASKELL__
512 -- Hugs has these too, but their Typeable<n> instances are defined
513 -- elsewhere to keep this module within Haskell 98.
514 -- This is important because every invocation of runhugs or ffihugs
515 -- uses this module via Data.Dynamic.
516 INSTANCE_TYPEABLE2(ST,stTc,"ST")
517 INSTANCE_TYPEABLE2(STRef,stRefTc,"STRef")
518 INSTANCE_TYPEABLE3(STArray,sTArrayTc,"STArray")
519 #endif
520
521 #ifndef __NHC__
522 INSTANCE_TYPEABLE2((,),pairTc,"(,)")
523 INSTANCE_TYPEABLE3((,,),tup3Tc,"(,,)")
524
525 tup4Tc :: TyCon
526 tup4Tc = mkTyCon "(,,,)"
527
528 instance Typeable4 (,,,) where
529   typeOf4 tu = mkTyConApp tup4Tc []
530
531 tup5Tc :: TyCon
532 tup5Tc = mkTyCon "(,,,,)"
533
534 instance Typeable5 (,,,,) where
535   typeOf5 tu = mkTyConApp tup5Tc []
536
537 tup6Tc :: TyCon
538 tup6Tc = mkTyCon "(,,,,,)"
539
540 instance Typeable6 (,,,,,) where
541   typeOf6 tu = mkTyConApp tup6Tc []
542
543 tup7Tc :: TyCon
544 tup7Tc = mkTyCon "(,,,,,,)"
545
546 instance Typeable7 (,,,,,,) where
547   typeOf7 tu = mkTyConApp tup7Tc []
548 #endif /* __NHC__ */
549
550 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
551 INSTANCE_TYPEABLE1(FunPtr,funPtrTc,"FunPtr")
552 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
553 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
554 INSTANCE_TYPEABLE1(IORef,iORefTc,"IORef")
555
556 -------------------------------------------------------
557 --
558 -- Generate Typeable instances for standard datatypes
559 --
560 -------------------------------------------------------
561
562 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
563 INSTANCE_TYPEABLE0(Char,charTc,"Char")
564 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
565 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
566 INSTANCE_TYPEABLE0(Int,intTc,"Int")
567 #ifndef __NHC__
568 INSTANCE_TYPEABLE0(Word,wordTc,"Word" )
569 #endif
570 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
571 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
572 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
573
574 INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
575 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
576 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
577 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
578
579 INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
580 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
581 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
582 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
583
584 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
585 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
586
587 #ifdef __GLASGOW_HASKELL__
588 INSTANCE_TYPEABLE0(RealWorld,realWorldTc,"RealWorld")
589 #endif
590
591 ---------------------------------------------
592 --
593 --              Internals 
594 --
595 ---------------------------------------------
596
597 #ifndef __HUGS__
598 newtype Key = Key Int deriving( Eq )
599 #endif
600
601 data KeyPr = KeyPr !Key !Key deriving( Eq )
602
603 hashKP :: KeyPr -> Int32
604 hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
605
606 data Cache = Cache { next_key :: !(IORef Key),  -- Not used by GHC (calls genSym instead)
607                      tc_tbl   :: !(HT.HashTable String Key),
608                      ap_tbl   :: !(HT.HashTable KeyPr Key) }
609
610 {-# NOINLINE cache #-}
611 #ifdef __GLASGOW_HASKELL__
612 foreign import ccall unsafe "RtsTypeable.h getOrSetTypeableStore"
613     getOrSetTypeableStore :: Ptr a -> IO (Ptr a)
614 #endif
615
616 cache :: Cache
617 cache = unsafePerformIO $ do
618                 empty_tc_tbl <- HT.new (==) HT.hashString
619                 empty_ap_tbl <- HT.new (==) hashKP
620                 key_loc      <- newIORef (Key 1) 
621                 let ret = Cache {       next_key = key_loc,
622                                         tc_tbl = empty_tc_tbl, 
623                                         ap_tbl = empty_ap_tbl }
624 #ifdef __GLASGOW_HASKELL__
625                 block $ do
626                         stable_ref <- newStablePtr ret
627                         let ref = castStablePtrToPtr stable_ref
628                         ref2 <- getOrSetTypeableStore ref
629                         if ref==ref2
630                                 then deRefStablePtr stable_ref
631                                 else do
632                                         freeStablePtr stable_ref
633                                         deRefStablePtr
634                                                 (castPtrToStablePtr ref2)
635 #else
636                 return ret
637 #endif
638
639 newKey :: IORef Key -> IO Key
640 #ifdef __GLASGOW_HASKELL__
641 newKey kloc = do i <- genSym; return (Key i)
642 #else
643 newKey kloc = do { k@(Key i) <- readIORef kloc ;
644                    writeIORef kloc (Key (i+1)) ;
645                    return k }
646 #endif
647
648 #ifdef __GLASGOW_HASKELL__
649 foreign import ccall unsafe "genSymZh"
650   genSym :: IO Int
651 #endif
652
653 mkTyConKey :: String -> Key
654 mkTyConKey str 
655   = unsafePerformIO $ do
656         let Cache {next_key = kloc, tc_tbl = tbl} = cache
657         mb_k <- HT.lookup tbl str
658         case mb_k of
659           Just k  -> return k
660           Nothing -> do { k <- newKey kloc ;
661                           HT.insert tbl str k ;
662                           return k }
663
664 appKey :: Key -> Key -> Key
665 appKey k1 k2
666   = unsafePerformIO $ do
667         let Cache {next_key = kloc, ap_tbl = tbl} = cache
668         mb_k <- HT.lookup tbl kpr
669         case mb_k of
670           Just k  -> return k
671           Nothing -> do { k <- newKey kloc ;
672                           HT.insert tbl kpr k ;
673                           return k }
674   where
675     kpr = KeyPr k1 k2
676
677 appKeys :: Key -> [Key] -> Key
678 appKeys k ks = foldl appKey k ks