[project @ 2004-02-28 15:35:28 by ralf]
[ghc.git] / libraries / base / Data / Typeable.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module : Data.Typeable
5 -- Copyright : (c) The University of Glasgow, CWI 2001--2004
6 -- License : BSD-style (see the file libraries/base/LICENSE)
7 --
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : portable
11 --
12 -- The Typeable class reifies types to some extent by associating type
13 -- representations to types. These type representations can be compared,
14 -- and one can in turn define a type-safe cast operation. To this end,
15 -- an unsafe cast is guarded by a test for type (representation)
16 -- equivalence. The module Data.Dynamic uses Typeable for an
17 -- implementation of dynamics. The module Data.Generics uses Typeable
18 -- and type-safe cast (but not dynamics) to support the \"Scrap your
19 -- boilerplate\" style of generic programming.
20 --
21 -----------------------------------------------------------------------------
22
23 module Data.Typeable
24 (
25
26 -- * The Typeable class
27 Typeable( typeOf ), -- :: a -> TypeRep
28
29 -- * Type-safe cast
30 cast, -- :: (Typeable a, Typeable b) => a -> Maybe b
31 cast0, -- a flexible variation on cast
32
33 -- * Type representations
34 TypeRep, -- abstract, instance of: Eq, Show, Typeable
35 TyCon, -- abstract, instance of: Eq, Show, Typeable
36
37 -- * Construction of type representations
38 mkTyCon, -- :: String -> TyCon
39 mkAppTy, -- :: TyCon -> [TypeRep] -> TypeRep
40 mkFunTy, -- :: TypeRep -> TypeRep -> TypeRep
41 applyTy, -- :: TypeRep -> TypeRep -> Maybe TypeRep
42
43 -- * Observation of type representations
44 typerepTyCon, -- :: TypeRep -> TyCon
45 typerepArgs, -- :: TypeRep -> [TypeRep]
46 tyconString, -- :: TyCon -> String
47
48 -- * The Typeable1 class
49 Typeable1( typeOf1 ), -- :: t a -> TyCon
50 Typeable2( typeOf2 ), -- :: t a b -> TyCon
51 cast1, -- :: ... => c (t a) -> Maybe (c (t' a))
52 cast2 -- :: ... => c (t a b) -> Maybe (c (t' a b))
53
54 ) where
55
56
57 import qualified Data.HashTable as HT
58 import Data.Maybe
59 import Data.Either
60 import Data.Int
61 import Data.Word
62 import Data.List( foldl )
63
64 #ifdef __GLASGOW_HASKELL__
65 import GHC.Base
66 import GHC.Show
67 import GHC.Err
68 import GHC.Num
69 import GHC.Float
70 import GHC.Real( rem, Ratio )
71 import GHC.IOBase
72 import GHC.Ptr -- So we can give Typeable instance for Ptr
73 import GHC.Stable -- So we can give Typeable instance for StablePtr
74 #endif
75
76 #ifdef __HUGS__
77 import Hugs.Prelude
78 import Hugs.IO
79 import Hugs.IORef
80 import Hugs.IOExts
81 #endif
82
83 #ifdef __GLASGOW_HASKELL__
84 unsafeCoerce :: a -> b
85 unsafeCoerce = unsafeCoerce#
86 #endif
87
88 #ifdef __NHC__
89 import NonStdUnsafeCoerce (unsafeCoerce)
90 import NHC.IOExtras (IORef,newIORef,readIORef,writeIORef,unsafePerformIO)
91 #else
92 #include "Typeable.h"
93 #endif
94
95
96 #ifndef __HUGS__
97 -------------------------------------------------------------
98 --
99 -- Type representations
100 --
101 -------------------------------------------------------------
102
103
104 -- | A concrete representation of a (monomorphic) type. 'TypeRep'
105 -- supports reasonably efficient equality.
106 data TypeRep = TypeRep !Key TyCon [TypeRep]
107
108 -- Compare keys for equality
109 instance Eq TypeRep where
110 (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
111
112 -- | An abstract representation of a type constructor. 'TyCon' objects can
113 -- be built using 'mkTyCon'.
114 data TyCon = TyCon !Key String
115
116 instance Eq TyCon where
117 (TyCon t1 _) == (TyCon t2 _) = t1 == t2
118
119 #endif
120
121 --
122 -- let fTy = mkTyCon "Foo" in show (mkAppTy (mkTyCon ",,")
123 -- [fTy,fTy,fTy])
124 --
125 -- returns "(Foo,Foo,Foo)"
126 --
127 -- The TypeRep Show instance promises to print tuple types
128 -- correctly. Tuple type constructors are specified by a
129 -- sequence of commas, e.g., (mkTyCon ",,,,") returns
130 -- the 5-tuple tycon.
131
132 ----------------- Construction --------------------
133
134 -- | Applies a type constructor to a sequence of types
135 mkAppTy :: TyCon -> [TypeRep] -> TypeRep
136 mkAppTy tc@(TyCon tc_k _) args
137 = TypeRep (appKeys tc_k arg_ks) tc args
138 where
139 arg_ks = [k | TypeRep k _ _ <- args]
140
141 funTc :: TyCon
142 funTc = mkTyCon "->"
143
144 -- | A special case of 'mkAppTy', which applies the function
145 -- type constructor to a pair of types.
146 mkFunTy :: TypeRep -> TypeRep -> TypeRep
147 mkFunTy f a = mkAppTy funTc [f,a]
148
149 -- | Applies a type to a function type. Returns: @'Just' u@ if the
150 -- first argument represents a function of type @t -> u@ and the
151 -- second argument represents a function of type @t@. Otherwise,
152 -- returns 'Nothing'.
153 applyTy :: TypeRep -> TypeRep -> Maybe TypeRep
154 applyTy (TypeRep _ tc [t1,t2]) t3
155 | tc == funTc && t1 == t3 = Just t2
156 applyTy _ _ = Nothing
157
158 -- If we enforce the restriction that there is only one
159 -- @TyCon@ for a type & it is shared among all its uses,
160 -- we can map them onto Ints very simply. The benefit is,
161 -- of course, that @TyCon@s can then be compared efficiently.
162
163 -- Provided the implementor of other @Typeable@ instances
164 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
165 -- this will work.
166
167 -- If this constraint does turn out to be a sore thumb, changing
168 -- the Eq instance for TyCons is trivial.
169
170 -- | Builds a 'TyCon' object representing a type constructor. An
171 -- implementation of "Data.Typeable" should ensure that the following holds:
172 --
173 -- > mkTyCon "a" == mkTyCon "a"
174 --
175
176 mkTyCon :: String -- ^ the name of the type constructor (should be unique
177 -- in the program, so it might be wise to use the
178 -- fully qualified name).
179 -> TyCon -- ^ A unique 'TyCon' object
180 mkTyCon str = TyCon (mkTyConKey str) str
181
182
183
184 ----------------- Observation ---------------------
185
186
187 -- | Observe the type constructor of a type representation
188 typerepTyCon :: TypeRep -> TyCon
189 typerepTyCon (TypeRep _ tc _) = tc
190
191
192 -- | Observe the argument types of a type representation
193 typerepArgs :: TypeRep -> [TypeRep]
194 typerepArgs (TypeRep _ _ args) = args
195
196
197 -- | Observe string encoding of a type representation
198 tyconString :: TyCon -> String
199 tyconString (TyCon _ str) = str
200
201
202 ----------------- Showing TypeReps --------------------
203
204 instance Show TypeRep where
205 showsPrec p (TypeRep _ tycon tys) =
206 case tys of
207 [] -> showsPrec p tycon
208 [x] | tycon == listTc -> showChar '[' . shows x . showChar ']'
209 [a,r] | tycon == funTc -> showParen (p > 8) $
210 showsPrec 9 a . showString " -> " . showsPrec 8 r
211 xs | isTupleTyCon tycon -> showTuple tycon xs
212 | otherwise ->
213 showParen (p > 9) $
214 showsPrec p tycon .
215 showChar ' ' .
216 showArgs tys
217
218 instance Show TyCon where
219 showsPrec _ (TyCon _ s) = showString s
220
221 isTupleTyCon :: TyCon -> Bool
222 isTupleTyCon (TyCon _ (',':_)) = True
223 isTupleTyCon _ = False
224
225 -- Some (Show.TypeRep) helpers:
226
227 showArgs :: Show a => [a] -> ShowS
228 showArgs [] = id
229 showArgs [a] = showsPrec 10 a
230 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as
231
232 showTuple :: TyCon -> [TypeRep] -> ShowS
233 showTuple (TyCon _ str) args = showChar '(' . go str args
234 where
235 go [] [a] = showsPrec 10 a . showChar ')'
236 go _ [] = showChar ')' -- a failure condition, really.
237 go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
238 go _ _ = showChar ')'
239
240
241 -------------------------------------------------------------
242 --
243 -- The Typeable class
244 --
245 -------------------------------------------------------------
246
247 -- | The class 'Typeable' allows a concrete representation of a type to
248 -- be calculated.
249 class Typeable a where
250 typeOf :: a -> TypeRep
251 -- ^ Takes a value of type @a@ and returns a concrete representation
252 -- of that type. The /value/ of the argument should be ignored by
253 -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
254 -- the argument.
255
256
257 -------------------------------------------------------------
258 --
259 -- Type-safe cast
260 --
261 -------------------------------------------------------------
262
263 -- | The type-safe cast operation
264 cast :: (Typeable a, Typeable b) => a -> Maybe b
265 cast x = r
266 where
267 r = if typeOf x == typeOf (fromJust r)
268 then Just $ unsafeCoerce x
269 else Nothing
270
271
272 -- | A flexible variation parameterised in a type constructor
273 cast0 :: (Typeable a, Typeable b) => c a -> Maybe (c b)
274 cast0 x = r
275 where
276 r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
277 then Just $ unsafeCoerce x
278 else Nothing
279 getArg :: c x -> x
280 getArg = undefined
281
282
283
284 -------------------------------------------------------------
285 --
286 -- Instances of the Typeable class for Prelude types
287 --
288 -------------------------------------------------------------
289
290 listTc :: TyCon
291 listTc = mkTyCon "[]"
292
293 instance Typeable a => Typeable [a] where
294 typeOf ls = mkAppTy listTc [typeOf ((undefined :: [a] -> a) ls)]
295 -- In GHC we can say
296 -- typeOf (undefined :: a)
297 -- using scoped type variables, but we use the
298 -- more verbose form here, for compatibility with Hugs
299
300 unitTc :: TyCon
301 unitTc = mkTyCon "()"
302
303 instance Typeable () where
304 typeOf _ = mkAppTy unitTc []
305
306 tup2Tc :: TyCon
307 tup2Tc = mkTyCon ","
308
309 instance (Typeable a, Typeable b) => Typeable (a,b) where
310 typeOf tu = mkAppTy tup2Tc [typeOf ((undefined :: (a,b) -> a) tu),
311 typeOf ((undefined :: (a,b) -> b) tu)]
312
313 tup3Tc :: TyCon
314 tup3Tc = mkTyCon ",,"
315
316 instance ( Typeable a , Typeable b , Typeable c) => Typeable (a,b,c) where
317 typeOf tu = mkAppTy tup3Tc [typeOf ((undefined :: (a,b,c) -> a) tu),
318 typeOf ((undefined :: (a,b,c) -> b) tu),
319 typeOf ((undefined :: (a,b,c) -> c) tu)]
320
321 tup4Tc :: TyCon
322 tup4Tc = mkTyCon ",,,"
323
324 instance ( Typeable a
325 , Typeable b
326 , Typeable c
327 , Typeable d) => Typeable (a,b,c,d) where
328 typeOf tu = mkAppTy tup4Tc [typeOf ((undefined :: (a,b,c,d) -> a) tu),
329 typeOf ((undefined :: (a,b,c,d) -> b) tu),
330 typeOf ((undefined :: (a,b,c,d) -> c) tu),
331 typeOf ((undefined :: (a,b,c,d) -> d) tu)]
332 tup5Tc :: TyCon
333 tup5Tc = mkTyCon ",,,,"
334
335 instance ( Typeable a
336 , Typeable b
337 , Typeable c
338 , Typeable d
339 , Typeable e) => Typeable (a,b,c,d,e) where
340 typeOf tu = mkAppTy tup5Tc [typeOf ((undefined :: (a,b,c,d,e) -> a) tu),
341 typeOf ((undefined :: (a,b,c,d,e) -> b) tu),
342 typeOf ((undefined :: (a,b,c,d,e) -> c) tu),
343 typeOf ((undefined :: (a,b,c,d,e) -> d) tu),
344 typeOf ((undefined :: (a,b,c,d,e) -> e) tu)]
345
346 tup6Tc :: TyCon
347 tup6Tc = mkTyCon ",,,,"
348
349 instance ( Typeable a
350 , Typeable b
351 , Typeable c
352 , Typeable d
353 , Typeable e
354 , Typeable f) => Typeable (a,b,c,d,e,f) where
355 typeOf tu = mkAppTy tup6Tc
356 [typeOf ( (undefined :: (a,b,c,d,e,f) -> a) tu),
357 typeOf ((undefined :: (a,b,c,d,e,f) -> b) tu),
358 typeOf ((undefined :: (a,b,c,d,e,f) -> c) tu),
359 typeOf ((undefined :: (a,b,c,d,e,f) -> d) tu),
360 typeOf ((undefined :: (a,b,c,d,e,f) -> e) tu),
361 typeOf ((undefined :: (a,b,c,d,e,f) -> f) tu)]
362
363 tup7Tc :: TyCon
364 tup7Tc = mkTyCon ",,,,"
365
366 instance ( Typeable a
367 , Typeable b
368 , Typeable c
369 , Typeable d
370 , Typeable e
371 , Typeable f
372 , Typeable g) => Typeable (a,b,c,d,e,f,g) where
373 typeOf tu = mkAppTy tup7Tc
374 [typeOf ( (undefined :: (a,b,c,d,e,f,g) -> a) tu),
375 typeOf ((undefined :: (a,b,c,d,e,f,g) -> b) tu),
376 typeOf ((undefined :: (a,b,c,d,e,f,g) -> c) tu),
377 typeOf ((undefined :: (a,b,c,d,e,f,g) -> d) tu),
378 typeOf ((undefined :: (a,b,c,d,e,f,g) -> e) tu),
379 typeOf ((undefined :: (a,b,c,d,e,f,g) -> f) tu),
380 typeOf ((undefined :: (a,b,c,d,e,f,g) -> g) tu)]
381
382 instance (Typeable a, Typeable b) => Typeable (a -> b) where
383 typeOf f = mkFunTy (typeOf ((undefined :: (a -> b) -> a) f))
384 (typeOf ((undefined :: (a -> b) -> b) f))
385
386
387
388 -------------------------------------------------------
389 --
390 -- Generate Typeable instances for standard datatypes
391 --
392 -------------------------------------------------------
393
394 #ifndef __NHC__
395 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
396 INSTANCE_TYPEABLE0(Char,charTc,"Char")
397 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
398 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
399 INSTANCE_TYPEABLE0(Int,intTc,"Int")
400 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
401 INSTANCE_TYPEABLE1(Ratio,ratioTc,"Ratio")
402 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
403 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
404 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
405 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
406 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
407 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
408 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
409
410 INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
411 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
412 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
413 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
414
415 INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
416 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
417 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
418 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
419
420 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
421 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
422
423 INSTANCE_TYPEABLE1(IORef,ioRefTc,"IORef")
424 #endif
425
426 #ifdef __GLASGOW_HASKELL__
427 INSTANCE_TYPEABLE0(Word,wordTc,"Word" )
428 #endif
429
430
431
432 ---------------------------------------------
433 --
434 -- Internals
435 --
436 ---------------------------------------------
437
438 #ifndef __HUGS__
439 newtype Key = Key Int deriving( Eq )
440 #endif
441
442 data KeyPr = KeyPr !Key !Key deriving( Eq )
443
444 hashKP :: KeyPr -> Int32
445 hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
446
447 data Cache = Cache { next_key :: !(IORef Key),
448 tc_tbl :: !(HT.HashTable String Key),
449 ap_tbl :: !(HT.HashTable KeyPr Key) }
450
451 {-# NOINLINE cache #-}
452 cache :: Cache
453 cache = unsafePerformIO $ do
454 empty_tc_tbl <- HT.new (==) HT.hashString
455 empty_ap_tbl <- HT.new (==) hashKP
456 key_loc <- newIORef (Key 1)
457 return (Cache { next_key = key_loc,
458 tc_tbl = empty_tc_tbl,
459 ap_tbl = empty_ap_tbl })
460
461 newKey :: IORef Key -> IO Key
462 #ifdef __GLASGOW_HASKELL__
463 newKey kloc = do i <- genSym; return (Key i)
464 #else
465 newKey kloc = do { k@(Key i) <- readIORef kloc ;
466 writeIORef kloc (Key (i+1)) ;
467 return k }
468 #endif
469
470 #ifdef __GLASGOW_HASKELL__
471 -- In GHC we use the RTS's genSym function to get a new unique,
472 -- because in GHCi we might have two copies of the Data.Typeable
473 -- library running (one in the compiler and one in the running
474 -- program), and we need to make sure they don't share any keys.
475 --
476 -- This is really a hack. A better solution would be to centralise the
477 -- whole mutable state used by this module, i.e. both hashtables. But
478 -- the current solution solves the immediate problem, which is that
479 -- dynamics generated in one world with one type were erroneously
480 -- being recognised by the other world as having a different type.
481 foreign import ccall unsafe "genSymZh"
482 genSym :: IO Int
483 #endif
484
485 mkTyConKey :: String -> Key
486 mkTyConKey str
487 = unsafePerformIO $ do
488 let Cache {next_key = kloc, tc_tbl = tbl} = cache
489 mb_k <- HT.lookup tbl str
490 case mb_k of
491 Just k -> return k
492 Nothing -> do { k <- newKey kloc ;
493 HT.insert tbl str k ;
494 return k }
495
496 appKey :: Key -> Key -> Key
497 appKey k1 k2
498 = unsafePerformIO $ do
499 let Cache {next_key = kloc, ap_tbl = tbl} = cache
500 mb_k <- HT.lookup tbl kpr
501 case mb_k of
502 Just k -> return k
503 Nothing -> do { k <- newKey kloc ;
504 HT.insert tbl kpr k ;
505 return k }
506 where
507 kpr = KeyPr k1 k2
508
509 appKeys :: Key -> [Key] -> Key
510 appKeys k ks = foldl appKey k ks
511
512
513
514 ------------------------------------------------------------------------------
515 --
516 -- Typeable adopted for unary type constructors
517 -- This adoption is at an experimental stage.
518 --
519 ------------------------------------------------------------------------------
520
521
522 -- | Variant for unary type constructors
523 class Typeable1 t where
524 typeOf1 :: t a -> TyCon
525
526
527 -- | Variant for binary type constructors
528 class Typeable2 t where
529 typeOf2 :: t a b -> TyCon
530
531
532 #ifndef __NHC__
533
534 -- | Instance for lists
535 instance Typeable1 [] where
536 typeOf1 _ = typerepTyCon (typeOf (undefined::[()]))
537
538
539 -- | Instance for maybes
540 instance Typeable1 Maybe where
541 typeOf1 _ = typerepTyCon (typeOf (undefined::Maybe ()))
542
543
544 -- | Instance for ratios
545 instance Typeable1 Ratio where
546 typeOf1 _ = typerepTyCon (typeOf (undefined::Ratio ()))
547
548
549 -- | Instance for products
550 instance Typeable2 (,) where
551 typeOf2 _ = typerepTyCon (typeOf (undefined::((),())))
552
553
554 -- | Instance for sums
555 instance Typeable2 Either where
556 typeOf2 _ = typerepTyCon (typeOf (undefined::Either () ()))
557
558
559 -- | Instance for functions
560 instance Typeable2 (->) where
561 typeOf2 _ = typerepTyCon (typeOf (undefined::() -> ()))
562
563 #endif
564
565
566 -- | Cast for * -> *
567 cast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
568 cast1 x = r
569 where
570 r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
571 then Just $ unsafeCoerce x
572 else Nothing
573 getArg :: c x -> x
574 getArg = undefined
575
576
577 -- | Cast for * -> * -> *
578 cast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))
579 cast2 x = r
580 where
581 r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
582 then Just $ unsafeCoerce x
583 else Nothing
584 getArg :: c x -> x
585 getArg = undefined