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 gcast, -- 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 gcast1, -- :: ... => c (t a) -> Maybe (c (t' a))
52 gcast2 -- :: ... => 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 gcast :: (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)]
347 tup6Tc = mkTyCon ",,,,"
349 instance ( Typeable a
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)]
364 tup7Tc = mkTyCon ",,,,"
366 instance ( Typeable a
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)]
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))
388 -------------------------------------------------------
390 -- Generate Typeable instances for standard datatypes
392 -------------------------------------------------------
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")
410 INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
411 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
412 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
413 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
415 INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
416 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
417 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
418 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
420 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
421 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
423 INSTANCE_TYPEABLE1(IORef,ioRefTc,"IORef")
426 #ifdef __GLASGOW_HASKELL__
427 INSTANCE_TYPEABLE0(Word,wordTc,"Word" )
432 ---------------------------------------------
436 ---------------------------------------------
439 newtype Key = Key Int deriving( Eq )
442 data KeyPr = KeyPr !Key !Key deriving( Eq )
444 hashKP :: KeyPr -> Int32
445 hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
447 data Cache = Cache { next_key :: !(IORef Key),
448 tc_tbl :: !(HT.HashTable String Key),
449 ap_tbl :: !(HT.HashTable KeyPr Key) }
451 {-# NOINLINE 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 })
461 newKey :: IORef Key -> IO Key
462 #ifdef __GLASGOW_HASKELL__
463 newKey kloc = do i <- genSym; return (Key i)
465 newKey kloc = do { k@(Key i) <- readIORef kloc ;
466 writeIORef kloc (Key (i+1)) ;
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.
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"
485 mkTyConKey :: String -> Key
487 = unsafePerformIO $ do
488 let Cache {next_key = kloc, tc_tbl = tbl} = cache
489 mb_k <- HT.lookup tbl str
492 Nothing -> do { k <- newKey kloc ;
493 HT.insert tbl str k ;
496 appKey :: Key -> Key -> Key
498 = unsafePerformIO $ do
499 let Cache {next_key = kloc, ap_tbl = tbl} = cache
500 mb_k <- HT.lookup tbl kpr
503 Nothing -> do { k <- newKey kloc ;
504 HT.insert tbl kpr k ;
509 appKeys :: Key -> [Key] -> Key
510 appKeys k ks = foldl appKey k ks
514 ------------------------------------------------------------------------------
516 -- Typeable adopted for unary type constructors
517 -- This adoption is at an experimental stage.
519 ------------------------------------------------------------------------------
522 -- | Variant for unary type constructors
523 class Typeable1 t where
524 typeOf1 :: t a -> TypeRep
527 -- | Variant for binary type constructors
528 class Typeable2 t where
529 typeOf2 :: t a b -> TypeRep
534 -- | Instance for lists
535 instance Typeable1 [] where
536 typeOf1 _ = mkAppTy (typerepTyCon (typeOf (undefined::[()]))) []
539 -- | Instance for maybes
540 instance Typeable1 Maybe where
541 typeOf1 _ = mkAppTy (typerepTyCon (typeOf (undefined::Maybe ()))) []
544 -- | Instance for ratios
545 instance Typeable1 Ratio where
546 typeOf1 _ = mkAppTy (typerepTyCon (typeOf (undefined::Ratio ()))) []
549 -- | Instance for products
550 instance Typeable2 (,) where
551 typeOf2 _ = mkAppTy (typerepTyCon (typeOf (undefined::((),())))) []
554 -- | Instance for sums
555 instance Typeable2 Either where
556 typeOf2 _ = mkAppTy (typerepTyCon (typeOf (undefined::Either () ()))) []
559 -- | Instance for functions
560 instance Typeable2 (->) where
561 typeOf2 _ = mkAppTy (typerepTyCon (typeOf (undefined::() -> ()))) []
567 gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
570 r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
571 then Just $ unsafeCoerce x
577 -- | Cast for * -> * -> *
578 gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))
581 r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
582 then Just $ unsafeCoerce x