1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : Data.Typeable
5 -- Copyright : (c) The University of Glasgow, CWI 2001--2004
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : portable
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.
21 -----------------------------------------------------------------------------
26 -- * The Typeable class
27 Typeable( typeOf ), -- :: a -> TypeRep
30 cast, -- :: (Typeable a, Typeable b) => a -> Maybe b
31 cast0, -- a flexible variation on cast
33 -- * Type representations
34 TypeRep, -- abstract, instance of: Eq, Show, Typeable
35 TyCon, -- abstract, instance of: Eq, Show, Typeable
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
43 -- * Observation of type representations
44 typerepTyCon, -- :: TypeRep -> TyCon
45 typerepArgs, -- :: TypeRep -> [TypeRep]
46 tyconString, -- :: TyCon -> String
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))
57 import qualified Data.HashTable as HT
62 import Data.List( foldl )
64 #ifdef __GLASGOW_HASKELL__
70 import GHC.Real( rem, Ratio )
72 import GHC.Ptr -- So we can give Typeable instance for Ptr
73 import GHC.Stable -- So we can give Typeable instance for StablePtr
83 #ifdef __GLASGOW_HASKELL__
84 unsafeCoerce :: a -> b
85 unsafeCoerce = unsafeCoerce#
89 import NonStdUnsafeCoerce (unsafeCoerce)
90 import NHC.IOExtras (IORef,newIORef,readIORef,writeIORef,unsafePerformIO)
97 -------------------------------------------------------------
99 -- Type representations
101 -------------------------------------------------------------
104 -- | A concrete representation of a (monomorphic) type. 'TypeRep'
105 -- supports reasonably efficient equality.
106 data TypeRep = TypeRep !Key TyCon [TypeRep]
108 -- Compare keys for equality
109 instance Eq TypeRep where
110 (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
112 -- | An abstract representation of a type constructor. 'TyCon' objects can
113 -- be built using 'mkTyCon'.
114 data TyCon = TyCon !Key String
116 instance Eq TyCon where
117 (TyCon t1 _) == (TyCon t2 _) = t1 == t2
122 -- let fTy = mkTyCon "Foo" in show (mkAppTy (mkTyCon ",,")
125 -- returns "(Foo,Foo,Foo)"
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.
132 ----------------- Construction --------------------
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
139 arg_ks = [k | TypeRep k _ _ <- args]
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]
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
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.
163 -- Provided the implementor of other @Typeable@ instances
164 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
167 -- If this constraint does turn out to be a sore thumb, changing
168 -- the Eq instance for TyCons is trivial.
170 -- | Builds a 'TyCon' object representing a type constructor. An
171 -- implementation of "Data.Typeable" should ensure that the following holds:
173 -- > mkTyCon "a" == mkTyCon "a"
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
184 ----------------- Observation ---------------------
187 -- | Observe the type constructor of a type representation
188 typerepTyCon :: TypeRep -> TyCon
189 typerepTyCon (TypeRep _ tc _) = tc
192 -- | Observe the argument types of a type representation
193 typerepArgs :: TypeRep -> [TypeRep]
194 typerepArgs (TypeRep _ _ args) = args
197 -- | Observe string encoding of a type representation
198 tyconString :: TyCon -> String
199 tyconString (TyCon _ str) = str
202 ----------------- Showing TypeReps --------------------
204 instance Show TypeRep where
205 showsPrec p (TypeRep _ tycon tys) =
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
218 instance Show TyCon where
219 showsPrec _ (TyCon _ s) = showString s
221 isTupleTyCon :: TyCon -> Bool
222 isTupleTyCon (TyCon _ (',':_)) = True
223 isTupleTyCon _ = False
225 -- Some (Show.TypeRep) helpers:
227 showArgs :: Show a => [a] -> ShowS
229 showArgs [a] = showsPrec 10 a
230 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as
232 showTuple :: TyCon -> [TypeRep] -> ShowS
233 showTuple (TyCon _ str) args = showChar '(' . go str args
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 ')'
241 -------------------------------------------------------------
243 -- The Typeable class
245 -------------------------------------------------------------
247 -- | The class 'Typeable' allows a concrete representation of a type to
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
257 -------------------------------------------------------------
261 -------------------------------------------------------------
263 -- | The type-safe cast operation
264 cast :: (Typeable a, Typeable b) => a -> Maybe b
267 r = if typeOf x == typeOf (fromJust r)
268 then Just $ unsafeCoerce x
272 -- | A flexible variation parameterised in a type constructor
273 cast0 :: (Typeable a, Typeable b) => c a -> Maybe (c b)
276 r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
277 then Just $ unsafeCoerce x
284 -------------------------------------------------------------
286 -- Instances of the Typeable class for Prelude types
288 -------------------------------------------------------------
291 listTc = mkTyCon "[]"
293 instance Typeable a => Typeable [a] where
294 typeOf ls = mkAppTy listTc [typeOf ((undefined :: [a] -> a) ls)]
296 -- typeOf (undefined :: a)
297 -- using scoped type variables, but we use the
298 -- more verbose form here, for compatibility with Hugs
301 unitTc = mkTyCon "()"
303 instance Typeable () where
304 typeOf _ = mkAppTy unitTc []
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)]
314 tup3Tc = mkTyCon ",,"
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)]
322 tup4Tc = mkTyCon ",,,"
324 instance ( Typeable a
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)]
333 tup5Tc = mkTyCon ",,,,"
335 instance ( Typeable a
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)]
346 instance (Typeable a, Typeable b) => Typeable (a -> b) where
347 typeOf f = mkFunTy (typeOf ((undefined :: (a -> b) -> a) f))
348 (typeOf ((undefined :: (a -> b) -> b) f))
352 -------------------------------------------------------
354 -- Generate Typeable instances for standard datatypes
356 -------------------------------------------------------
359 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
360 INSTANCE_TYPEABLE0(Char,charTc,"Char")
361 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
362 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
363 INSTANCE_TYPEABLE0(Int,intTc,"Int")
364 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
365 INSTANCE_TYPEABLE1(Ratio,ratioTc,"Ratio")
366 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
367 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
368 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
369 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
370 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
371 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
372 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
374 INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
375 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
376 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
377 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
379 INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
380 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
381 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
382 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
384 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
385 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
387 INSTANCE_TYPEABLE1(IORef,ioRefTc,"IORef")
392 ---------------------------------------------
396 ---------------------------------------------
399 newtype Key = Key Int deriving( Eq )
402 data KeyPr = KeyPr !Key !Key deriving( Eq )
404 hashKP :: KeyPr -> Int32
405 hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
407 data Cache = Cache { next_key :: !(IORef Key),
408 tc_tbl :: !(HT.HashTable String Key),
409 ap_tbl :: !(HT.HashTable KeyPr Key) }
411 {-# NOINLINE cache #-}
413 cache = unsafePerformIO $ do
414 empty_tc_tbl <- HT.new (==) HT.hashString
415 empty_ap_tbl <- HT.new (==) hashKP
416 key_loc <- newIORef (Key 1)
417 return (Cache { next_key = key_loc,
418 tc_tbl = empty_tc_tbl,
419 ap_tbl = empty_ap_tbl })
421 newKey :: IORef Key -> IO Key
422 #ifdef __GLASGOW_HASKELL__
423 newKey kloc = do i <- genSym; return (Key i)
425 newKey kloc = do { k@(Key i) <- readIORef kloc ;
426 writeIORef kloc (Key (i+1)) ;
430 #ifdef __GLASGOW_HASKELL__
431 -- In GHC we use the RTS's genSym function to get a new unique,
432 -- because in GHCi we might have two copies of the Data.Typeable
433 -- library running (one in the compiler and one in the running
434 -- program), and we need to make sure they don't share any keys.
436 -- This is really a hack. A better solution would be to centralise the
437 -- whole mutable state used by this module, i.e. both hashtables. But
438 -- the current solution solves the immediate problem, which is that
439 -- dynamics generated in one world with one type were erroneously
440 -- being recognised by the other world as having a different type.
441 foreign import ccall unsafe "genSymZh"
445 mkTyConKey :: String -> Key
447 = unsafePerformIO $ do
448 let Cache {next_key = kloc, tc_tbl = tbl} = cache
449 mb_k <- HT.lookup tbl str
452 Nothing -> do { k <- newKey kloc ;
453 HT.insert tbl str k ;
456 appKey :: Key -> Key -> Key
458 = unsafePerformIO $ do
459 let Cache {next_key = kloc, ap_tbl = tbl} = cache
460 mb_k <- HT.lookup tbl kpr
463 Nothing -> do { k <- newKey kloc ;
464 HT.insert tbl kpr k ;
469 appKeys :: Key -> [Key] -> Key
470 appKeys k ks = foldl appKey k ks
474 ------------------------------------------------------------------------------
476 -- Typeable adopted for unary type constructors
477 -- This adoption is at an experimental stage.
479 ------------------------------------------------------------------------------
482 -- | Variant for unary type constructors
483 class Typeable1 t where
484 typeOf1 :: t a -> TyCon
487 -- | Variant for binary type constructors
488 class Typeable2 t where
489 typeOf2 :: t a b -> TyCon
492 -- | Instance for lists
493 instance Typeable1 [] where
494 typeOf1 _ = typerepTyCon (typeOf (undefined::[()]))
497 -- | Instance for maybes
498 instance Typeable1 Maybe where
499 typeOf1 _ = typerepTyCon (typeOf (undefined::Maybe ()))
502 -- | Instance for products
503 instance Typeable2 (,) where
504 typeOf2 _ = typerepTyCon (typeOf (undefined::((),())))
507 -- | Instance for sums
508 instance Typeable2 Either where
509 typeOf2 _ = typerepTyCon (typeOf (undefined::Either () ()))
512 -- | Instance for functions
513 instance Typeable2 (->) where
514 typeOf2 _ = typerepTyCon (typeOf (undefined::() -> ()))
518 cast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
521 r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
522 then Just $ unsafeCoerce x
528 -- | Cast for * -> * -> *
529 cast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))
532 r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
533 then Just $ unsafeCoerce x