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 generalisation of 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 mkTyConApp, -- :: TyCon -> [TypeRep] -> TypeRep
40 mkAppTy, -- :: TypeRep -> TypeRep -> TypeRep
41 mkFunTy, -- :: TypeRep -> TypeRep -> TypeRep
42 splitTyConApp, -- :: TypeRep -> (TyCon, [TypeRep])
43 funResultTy, -- :: TypeRep -> TypeRep -> Maybe TypeRep
45 -- * Observation of type representations
46 typerepTyCon, -- :: TypeRep -> TyCon
47 typerepArgs, -- :: TypeRep -> [TypeRep]
48 tyconString, -- :: TyCon -> String
50 -- * The other Typeable classes
51 -- | /Note:/ The general instances are provided for GHC only.
52 Typeable1( typeOf1 ), -- :: t a -> TypeRep
53 Typeable2( typeOf2 ), -- :: t a b -> TypeRep
54 Typeable3( typeOf3 ), -- :: t a b c -> TypeRep
55 Typeable4( typeOf4 ), -- :: t a b c d -> TypeRep
56 Typeable5( typeOf5 ), -- :: t a b c d e -> TypeRep
57 Typeable6( typeOf6 ), -- :: t a b c d e f -> TypeRep
58 Typeable7( typeOf7 ), -- :: t a b c d e f g -> TypeRep
59 gcast1, -- :: ... => c (t a) -> Maybe (c (t' a))
60 gcast2, -- :: ... => c (t a b) -> Maybe (c (t' a b))
62 -- * Default instances
63 -- | /Note:/ These are not needed by GHC, for which these instances
64 -- are generated by general instance declarations.
65 typeOfDefault, -- :: (Typeable1 t, Typeable a) => t a -> TypeRep
66 typeOf1Default, -- :: (Typeable2 t, Typeable a) => t a b -> TypeRep
67 typeOf2Default, -- :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
68 typeOf3Default, -- :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
69 typeOf4Default, -- :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
70 typeOf5Default, -- :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
71 typeOf6Default -- :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
75 import qualified Data.HashTable as HT
80 import Data.List( foldl )
82 #ifdef __GLASGOW_HASKELL__
88 import GHC.Real( rem, Ratio )
90 import GHC.Ptr -- So we can give Typeable instance for Ptr
91 import GHC.Stable -- So we can give Typeable instance for StablePtr
101 #ifdef __GLASGOW_HASKELL__
102 unsafeCoerce :: a -> b
103 unsafeCoerce = unsafeCoerce#
107 import NonStdUnsafeCoerce (unsafeCoerce)
108 import NHC.IOExtras (IORef,newIORef,readIORef,writeIORef,unsafePerformIO)
110 #include "Typeable.h"
115 -------------------------------------------------------------
117 -- Type representations
119 -------------------------------------------------------------
121 -- | A concrete representation of a (monomorphic) type. 'TypeRep'
122 -- supports reasonably efficient equality.
123 data TypeRep = TypeRep !Key TyCon [TypeRep]
125 -- Compare keys for equality
126 instance Eq TypeRep where
127 (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
129 -- | An abstract representation of a type constructor. 'TyCon' objects can
130 -- be built using 'mkTyCon'.
131 data TyCon = TyCon !Key String
133 instance Eq TyCon where
134 (TyCon t1 _) == (TyCon t2 _) = t1 == t2
139 -- let fTy = mkTyCon "Foo" in show (mkTyConApp (mkTyCon ",,")
142 -- returns "(Foo,Foo,Foo)"
144 -- The TypeRep Show instance promises to print tuple types
145 -- correctly. Tuple type constructors are specified by a
146 -- sequence of commas, e.g., (mkTyCon ",,,,") returns
147 -- the 5-tuple tycon.
149 ----------------- Construction --------------------
151 -- | Applies a type constructor to a sequence of types
152 mkTyConApp :: TyCon -> [TypeRep] -> TypeRep
153 mkTyConApp tc@(TyCon tc_k _) args
154 = TypeRep (appKeys tc_k arg_ks) tc args
156 arg_ks = [k | TypeRep k _ _ <- args]
158 -- | A special case of 'mkTyConApp', which applies the function
159 -- type constructor to a pair of types.
160 mkFunTy :: TypeRep -> TypeRep -> TypeRep
161 mkFunTy f a = mkTyConApp funTc [f,a]
163 -- | Splits a type constructor application
164 splitTyConApp :: TypeRep -> (TyCon,[TypeRep])
165 splitTyConApp (TypeRep _ tc trs) = (tc,trs)
167 -- | Applies a type to a function type. Returns: @'Just' u@ if the
168 -- first argument represents a function of type @t -> u@ and the
169 -- second argument represents a function of type @t@. Otherwise,
170 -- returns 'Nothing'.
171 funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep
172 funResultTy trFun trArg
173 = case splitTyConApp trFun of
174 (tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2
177 -- | Adds a TypeRep argument to a TypeRep.
178 mkAppTy :: TypeRep -> TypeRep -> TypeRep
179 mkAppTy (TypeRep tr_k tc trs) arg_tr
180 = let (TypeRep arg_k _ _) = arg_tr
181 in TypeRep (appKey tr_k arg_k) tc (trs++[arg_tr])
183 -- If we enforce the restriction that there is only one
184 -- @TyCon@ for a type & it is shared among all its uses,
185 -- we can map them onto Ints very simply. The benefit is,
186 -- of course, that @TyCon@s can then be compared efficiently.
188 -- Provided the implementor of other @Typeable@ instances
189 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
192 -- If this constraint does turn out to be a sore thumb, changing
193 -- the Eq instance for TyCons is trivial.
195 -- | Builds a 'TyCon' object representing a type constructor. An
196 -- implementation of "Data.Typeable" should ensure that the following holds:
198 -- > mkTyCon "a" == mkTyCon "a"
201 mkTyCon :: String -- ^ the name of the type constructor (should be unique
202 -- in the program, so it might be wise to use the
203 -- fully qualified name).
204 -> TyCon -- ^ A unique 'TyCon' object
205 mkTyCon str = TyCon (mkTyConKey str) str
207 ----------------- Observation ---------------------
209 -- | Observe the type constructor of a type representation
210 typerepTyCon :: TypeRep -> TyCon
211 typerepTyCon (TypeRep _ tc _) = tc
213 -- | Observe the argument types of a type representation
214 typerepArgs :: TypeRep -> [TypeRep]
215 typerepArgs (TypeRep _ _ args) = args
217 -- | Observe string encoding of a type representation
218 tyconString :: TyCon -> String
219 tyconString (TyCon _ str) = str
221 ----------------- Showing TypeReps --------------------
223 instance Show TypeRep where
224 showsPrec p (TypeRep _ tycon tys) =
226 [] -> showsPrec p tycon
227 [x] | tycon == listTc -> showChar '[' . shows x . showChar ']'
228 [a,r] | tycon == funTc -> showParen (p > 8) $
232 xs | isTupleTyCon tycon -> showTuple tycon xs
239 instance Show TyCon where
240 showsPrec _ (TyCon _ s) = showString s
242 isTupleTyCon :: TyCon -> Bool
243 isTupleTyCon (TyCon _ (',':_)) = True
244 isTupleTyCon _ = False
246 -- Some (Show.TypeRep) helpers:
248 showArgs :: Show a => [a] -> ShowS
250 showArgs [a] = showsPrec 10 a
251 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as
253 showTuple :: TyCon -> [TypeRep] -> ShowS
254 showTuple (TyCon _ str) args = showChar '(' . go str args
256 go [] [a] = showsPrec 10 a . showChar ')'
257 go _ [] = showChar ')' -- a failure condition, really.
258 go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
259 go _ _ = showChar ')'
261 -------------------------------------------------------------
263 -- The Typeable class and friends
265 -------------------------------------------------------------
267 -- | The class 'Typeable' allows a concrete representation of a type to
269 class Typeable a where
270 typeOf :: a -> TypeRep
271 -- ^ Takes a value of type @a@ and returns a concrete representation
272 -- of that type. The /value/ of the argument should be ignored by
273 -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
276 -- | Variant for unary type constructors
277 class Typeable1 t where
278 typeOf1 :: t a -> TypeRep
280 -- | For defining a 'Typeable' instance from any 'Typeable1' instance.
281 typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
282 typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
287 -- | Variant for binary type constructors
288 class Typeable2 t where
289 typeOf2 :: t a b -> TypeRep
291 -- | For defining a 'Typeable1' instance from any 'Typeable2' instance.
292 typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
293 typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
295 argType :: t a b -> a
298 -- | Variant for 3-ary type constructors
299 class Typeable3 t where
300 typeOf3 :: t a b c -> TypeRep
302 -- | For defining a 'Typeable2' instance from any 'Typeable3' instance.
303 typeOf2Default :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
304 typeOf2Default x = typeOf3 x `mkAppTy` typeOf (argType x)
306 argType :: t a b c -> a
309 -- | Variant for 4-ary type constructors
310 class Typeable4 t where
311 typeOf4 :: t a b c d -> TypeRep
313 -- | For defining a 'Typeable3' instance from any 'Typeable4' instance.
314 typeOf3Default :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
315 typeOf3Default x = typeOf4 x `mkAppTy` typeOf (argType x)
317 argType :: t a b c d -> a
320 -- | Variant for 5-ary type constructors
321 class Typeable5 t where
322 typeOf5 :: t a b c d e -> TypeRep
324 -- | For defining a 'Typeable4' instance from any 'Typeable5' instance.
325 typeOf4Default :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
326 typeOf4Default x = typeOf5 x `mkAppTy` typeOf (argType x)
328 argType :: t a b c d e -> a
331 -- | Variant for 6-ary type constructors
332 class Typeable6 t where
333 typeOf6 :: t a b c d e f -> TypeRep
335 -- | For defining a 'Typeable5' instance from any 'Typeable6' instance.
336 typeOf5Default :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
337 typeOf5Default x = typeOf6 x `mkAppTy` typeOf (argType x)
339 argType :: t a b c d e f -> a
342 -- | Variant for 7-ary type constructors
343 class Typeable7 t where
344 typeOf7 :: t a b c d e f g -> TypeRep
346 -- | For defining a 'Typeable6' instance from any 'Typeable7' instance.
347 typeOf6Default :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
348 typeOf6Default x = typeOf7 x `mkAppTy` typeOf (argType x)
350 argType :: t a b c d e f g -> a
353 #ifdef __GLASGOW_HASKELL__
354 -- Given a @Typeable@/n/ instance for an /n/-ary type constructor,
355 -- define the instances for partial applications.
356 -- Programmers using non-GHC implementations must do this manually
357 -- for each type constructor.
358 -- (The INSTANCE_TYPEABLE/n/ macros in Typeable.h include this.)
360 -- | One Typeable instance for all Typeable1 instances
361 instance (Typeable1 s, Typeable a)
362 => Typeable (s a) where
363 typeOf = typeOfDefault
365 -- | One Typeable1 instance for all Typeable2 instances
366 instance (Typeable2 s, Typeable a)
367 => Typeable1 (s a) where
368 typeOf1 = typeOf1Default
370 -- | One Typeable2 instance for all Typeable3 instances
371 instance (Typeable3 s, Typeable a)
372 => Typeable2 (s a) where
373 typeOf2 = typeOf2Default
375 -- | One Typeable3 instance for all Typeable4 instances
376 instance (Typeable4 s, Typeable a)
377 => Typeable3 (s a) where
378 typeOf3 = typeOf3Default
380 -- | One Typeable4 instance for all Typeable5 instances
381 instance (Typeable5 s, Typeable a)
382 => Typeable4 (s a) where
383 typeOf4 = typeOf4Default
385 -- | One Typeable5 instance for all Typeable6 instances
386 instance (Typeable6 s, Typeable a)
387 => Typeable5 (s a) where
388 typeOf5 = typeOf5Default
390 -- | One Typeable6 instance for all Typeable7 instances
391 instance (Typeable7 s, Typeable a)
392 => Typeable6 (s a) where
393 typeOf6 = typeOf6Default
395 #endif /* __GLASGOW_HASKELL__ */
397 -------------------------------------------------------------
401 -------------------------------------------------------------
403 -- | The type-safe cast operation
404 cast :: (Typeable a, Typeable b) => a -> Maybe b
407 r = if typeOf x == typeOf (fromJust r)
408 then Just $ unsafeCoerce x
411 -- | A flexible variation parameterised in a type constructor
412 gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
415 r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
416 then Just $ unsafeCoerce x
422 gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
425 r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
426 then Just $ unsafeCoerce x
431 -- | Cast for * -> * -> *
432 gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))
435 r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
436 then Just $ unsafeCoerce x
441 -------------------------------------------------------------
443 -- Instances of the Typeable classes for Prelude types
445 -------------------------------------------------------------
448 INSTANCE_TYPEABLE1([],listTc,"[]")
449 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
450 INSTANCE_TYPEABLE1(Ratio,ratioTc,"Ratio")
451 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
452 INSTANCE_TYPEABLE2((->),funTc,"->")
453 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
454 INSTANCE_TYPEABLE0((),unitTc,"()")
455 INSTANCE_TYPEABLE2((,),pairTc,",")
456 INSTANCE_TYPEABLE3((,,),tup3Tc,",,")
459 tup4Tc = mkTyCon ",,,"
461 instance Typeable4 (,,,) where
462 typeOf4 tu = mkTyConApp tup4Tc []
465 tup5Tc = mkTyCon ",,,,"
467 instance Typeable5 (,,,,) where
468 typeOf5 tu = mkTyConApp tup5Tc []
471 tup6Tc = mkTyCon ",,,,,"
473 instance Typeable6 (,,,,,) where
474 typeOf6 tu = mkTyConApp tup6Tc []
477 tup7Tc = mkTyCon ",,,,,"
479 instance Typeable7 (,,,,,,) where
480 typeOf7 tu = mkTyConApp tup7Tc []
482 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Foreign.Ptr.Ptr")
483 INSTANCE_TYPEABLE1(StablePtr,stableptrTc,"Foreign.StablePtr.StablePtr")
484 INSTANCE_TYPEABLE1(IORef,iorefTc,"Data.IORef.IORef")
485 #endif /* ! __NHC__ */
487 -------------------------------------------------------
489 -- Generate Typeable instances for standard datatypes
491 -------------------------------------------------------
494 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
495 INSTANCE_TYPEABLE0(Char,charTc,"Char")
496 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
497 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
498 INSTANCE_TYPEABLE0(Int,intTc,"Int")
499 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
500 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
501 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
503 INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
504 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
505 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
506 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
508 INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
509 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
510 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
511 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
513 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
514 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
515 #endif /* !__NHC__ */
517 #ifdef __GLASGOW_HASKELL__
518 INSTANCE_TYPEABLE0(Word,wordTc,"Word" )
521 ---------------------------------------------
525 ---------------------------------------------
528 newtype Key = Key Int deriving( Eq )
531 data KeyPr = KeyPr !Key !Key deriving( Eq )
533 hashKP :: KeyPr -> Int32
534 hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
536 data Cache = Cache { next_key :: !(IORef Key),
537 tc_tbl :: !(HT.HashTable String Key),
538 ap_tbl :: !(HT.HashTable KeyPr Key) }
540 {-# NOINLINE cache #-}
542 cache = unsafePerformIO $ do
543 empty_tc_tbl <- HT.new (==) HT.hashString
544 empty_ap_tbl <- HT.new (==) hashKP
545 key_loc <- newIORef (Key 1)
546 return (Cache { next_key = key_loc,
547 tc_tbl = empty_tc_tbl,
548 ap_tbl = empty_ap_tbl })
550 newKey :: IORef Key -> IO Key
551 #ifdef __GLASGOW_HASKELL__
552 newKey kloc = do i <- genSym; return (Key i)
554 newKey kloc = do { k@(Key i) <- readIORef kloc ;
555 writeIORef kloc (Key (i+1)) ;
559 #ifdef __GLASGOW_HASKELL__
560 -- In GHC we use the RTS's genSym function to get a new unique,
561 -- because in GHCi we might have two copies of the Data.Typeable
562 -- library running (one in the compiler and one in the running
563 -- program), and we need to make sure they don't share any keys.
565 -- This is really a hack. A better solution would be to centralise the
566 -- whole mutable state used by this module, i.e. both hashtables. But
567 -- the current solution solves the immediate problem, which is that
568 -- dynamics generated in one world with one type were erroneously
569 -- being recognised by the other world as having a different type.
570 foreign import ccall unsafe "genSymZh"
574 mkTyConKey :: String -> Key
576 = unsafePerformIO $ do
577 let Cache {next_key = kloc, tc_tbl = tbl} = cache
578 mb_k <- HT.lookup tbl str
581 Nothing -> do { k <- newKey kloc ;
582 HT.insert tbl str k ;
585 appKey :: Key -> Key -> Key
587 = unsafePerformIO $ do
588 let Cache {next_key = kloc, ap_tbl = tbl} = cache
589 mb_k <- HT.lookup tbl kpr
592 Nothing -> do { k <- newKey kloc ;
593 HT.insert tbl kpr k ;
598 appKeys :: Key -> [Key] -> Key
599 appKeys k ks = foldl appKey k ks