1 {-# OPTIONS_GHC -XNoImplicitPrelude -XOverlappingInstances -funbox-strict-fields #-}
3 -- The -XOverlappingInstances 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)
9 -----------------------------------------------------------------------------
11 -- Module : Data.Typeable
12 -- Copyright : (c) The University of Glasgow, CWI 2001--2004
13 -- License : BSD-style (see the file libraries/base/LICENSE)
15 -- Maintainer : libraries@haskell.org
16 -- Stability : experimental
17 -- Portability : portable
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.
28 -----------------------------------------------------------------------------
33 -- * The Typeable class
34 Typeable( typeOf ), -- :: a -> TypeRep
37 cast, -- :: (Typeable a, Typeable b) => a -> Maybe b
38 gcast, -- a generalisation of cast
40 -- * Type representations
41 TypeRep, -- abstract, instance of: Eq, Show, Typeable
42 TyCon, -- abstract, instance of: Eq, Show, Typeable
45 -- * Construction of type representations
46 mkTyCon, -- :: String -> TyCon
47 mkTyConApp, -- :: TyCon -> [TypeRep] -> TypeRep
48 mkAppTy, -- :: TypeRep -> TypeRep -> TypeRep
49 mkFunTy, -- :: TypeRep -> TypeRep -> TypeRep
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
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))
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
84 import qualified Data.HashTable as HT
88 import Data.List( foldl, intersperse )
91 #ifdef __GLASGOW_HASKELL__
93 import GHC.Show (Show(..), ShowS,
94 shows, showString, showChar, showParen)
95 import GHC.Err (undefined)
96 import GHC.Num (Integer, fromInteger, (+))
97 import GHC.Real ( rem, Ratio )
98 import GHC.IOBase (IORef,newIORef,unsafePerformIO)
100 -- These imports are so we can define Typeable instances
101 -- It'd be better to give Typeable instances in the modules themselves
102 -- but they all have to be compiled before Typeable
103 import GHC.IOBase ( IOArray, IO, MVar, Handle, block )
105 import GHC.STRef ( STRef )
106 import GHC.Ptr ( Ptr, FunPtr )
107 import GHC.Stable ( StablePtr, newStablePtr, freeStablePtr,
108 deRefStablePtr, castStablePtrToPtr,
110 import GHC.Arr ( Array, STArray )
115 import Hugs.Prelude ( Key(..), TypeRep(..), TyCon(..), Ratio,
116 Handle, Ptr, FunPtr, ForeignPtr, StablePtr )
117 import Hugs.IORef ( IORef, newIORef, readIORef, writeIORef )
118 import Hugs.IOExts ( unsafePerformIO )
119 -- For the Typeable instance
120 import Hugs.Array ( Array )
122 import Hugs.ConcBase ( MVar )
126 import NHC.IOExtras (IOArray,IORef,newIORef,readIORef,writeIORef,unsafePerformIO)
129 -- For the Typeable instance
130 import NHC.FFI ( Ptr,FunPtr,StablePtr,ForeignPtr )
131 import Array ( Array )
134 #include "Typeable.h"
138 -------------------------------------------------------------
140 -- Type representations
142 -------------------------------------------------------------
144 -- | A concrete representation of a (monomorphic) type. 'TypeRep'
145 -- supports reasonably efficient equality.
146 data TypeRep = TypeRep !Key TyCon [TypeRep]
148 -- Compare keys for equality
149 instance Eq TypeRep where
150 (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
152 -- | An abstract representation of a type constructor. 'TyCon' objects can
153 -- be built using 'mkTyCon'.
154 data TyCon = TyCon !Key String
156 instance Eq TyCon where
157 (TyCon t1 _) == (TyCon t2 _) = t1 == t2
160 -- | Returns a unique integer associated with a 'TypeRep'. This can
161 -- be used for making a mapping with TypeReps
162 -- as the keys, for example. It is guaranteed that @t1 == t2@ if and only if
163 -- @typeRepKey t1 == typeRepKey t2@.
165 -- It is in the 'IO' monad because the actual value of the key may
166 -- vary from run to run of the program. You should only rely on
167 -- the equality property, not any actual key value. The relative ordering
168 -- of keys has no meaning either.
170 typeRepKey :: TypeRep -> IO Int
171 typeRepKey (TypeRep (Key i) _ _) = return i
174 -- let fTy = mkTyCon "Foo" in show (mkTyConApp (mkTyCon ",,")
177 -- returns "(Foo,Foo,Foo)"
179 -- The TypeRep Show instance promises to print tuple types
180 -- correctly. Tuple type constructors are specified by a
181 -- sequence of commas, e.g., (mkTyCon ",,,,") returns
182 -- the 5-tuple tycon.
184 ----------------- Construction --------------------
186 -- | Applies a type constructor to a sequence of types
187 mkTyConApp :: TyCon -> [TypeRep] -> TypeRep
188 mkTyConApp tc@(TyCon tc_k _) args
189 = TypeRep (appKeys tc_k arg_ks) tc args
191 arg_ks = [k | TypeRep k _ _ <- args]
193 -- | A special case of 'mkTyConApp', which applies the function
194 -- type constructor to a pair of types.
195 mkFunTy :: TypeRep -> TypeRep -> TypeRep
196 mkFunTy f a = mkTyConApp funTc [f,a]
198 -- | Splits a type constructor application
199 splitTyConApp :: TypeRep -> (TyCon,[TypeRep])
200 splitTyConApp (TypeRep _ tc trs) = (tc,trs)
202 -- | Applies a type to a function type. Returns: @'Just' u@ if the
203 -- first argument represents a function of type @t -> u@ and the
204 -- second argument represents a function of type @t@. Otherwise,
205 -- returns 'Nothing'.
206 funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep
207 funResultTy trFun trArg
208 = case splitTyConApp trFun of
209 (tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2
212 -- | Adds a TypeRep argument to a TypeRep.
213 mkAppTy :: TypeRep -> TypeRep -> TypeRep
214 mkAppTy (TypeRep tr_k tc trs) arg_tr
215 = let (TypeRep arg_k _ _) = arg_tr
216 in TypeRep (appKey tr_k arg_k) tc (trs++[arg_tr])
218 -- If we enforce the restriction that there is only one
219 -- @TyCon@ for a type & it is shared among all its uses,
220 -- we can map them onto Ints very simply. The benefit is,
221 -- of course, that @TyCon@s can then be compared efficiently.
223 -- Provided the implementor of other @Typeable@ instances
224 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
227 -- If this constraint does turn out to be a sore thumb, changing
228 -- the Eq instance for TyCons is trivial.
230 -- | Builds a 'TyCon' object representing a type constructor. An
231 -- implementation of "Data.Typeable" should ensure that the following holds:
233 -- > mkTyCon "a" == mkTyCon "a"
236 mkTyCon :: String -- ^ the name of the type constructor (should be unique
237 -- in the program, so it might be wise to use the
238 -- fully qualified name).
239 -> TyCon -- ^ A unique 'TyCon' object
240 mkTyCon str = TyCon (mkTyConKey str) str
242 ----------------- Observation ---------------------
244 -- | Observe the type constructor of a type representation
245 typeRepTyCon :: TypeRep -> TyCon
246 typeRepTyCon (TypeRep _ tc _) = tc
248 -- | Observe the argument types of a type representation
249 typeRepArgs :: TypeRep -> [TypeRep]
250 typeRepArgs (TypeRep _ _ args) = args
252 -- | Observe string encoding of a type representation
253 tyConString :: TyCon -> String
254 tyConString (TyCon _ str) = str
256 ----------------- Showing TypeReps --------------------
258 instance Show TypeRep where
259 showsPrec p (TypeRep _ tycon tys) =
261 [] -> showsPrec p tycon
262 [x] | tycon == listTc -> showChar '[' . shows x . showChar ']'
263 [a,r] | tycon == funTc -> showParen (p > 8) $
267 xs | isTupleTyCon tycon -> showTuple xs
274 showsTypeRep :: TypeRep -> ShowS
277 instance Show TyCon where
278 showsPrec _ (TyCon _ s) = showString s
280 isTupleTyCon :: TyCon -> Bool
281 isTupleTyCon (TyCon _ ('(':',':_)) = True
282 isTupleTyCon _ = False
284 -- Some (Show.TypeRep) helpers:
286 showArgs :: Show a => [a] -> ShowS
288 showArgs [a] = showsPrec 10 a
289 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as
291 showTuple :: [TypeRep] -> ShowS
292 showTuple args = showChar '('
293 . (foldr (.) id $ intersperse (showChar ',')
294 $ map (showsPrec 10) args)
297 -------------------------------------------------------------
299 -- The Typeable class and friends
301 -------------------------------------------------------------
303 -- | The class 'Typeable' allows a concrete representation of a type to
305 class Typeable a where
306 typeOf :: a -> TypeRep
307 -- ^ Takes a value of type @a@ and returns a concrete representation
308 -- of that type. The /value/ of the argument should be ignored by
309 -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
312 -- | Variant for unary type constructors
313 class Typeable1 t where
314 typeOf1 :: t a -> TypeRep
316 -- | For defining a 'Typeable' instance from any 'Typeable1' instance.
317 typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
318 typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
323 -- | Variant for binary type constructors
324 class Typeable2 t where
325 typeOf2 :: t a b -> TypeRep
327 -- | For defining a 'Typeable1' instance from any 'Typeable2' instance.
328 typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
329 typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
331 argType :: t a b -> a
334 -- | Variant for 3-ary type constructors
335 class Typeable3 t where
336 typeOf3 :: t a b c -> TypeRep
338 -- | For defining a 'Typeable2' instance from any 'Typeable3' instance.
339 typeOf2Default :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
340 typeOf2Default x = typeOf3 x `mkAppTy` typeOf (argType x)
342 argType :: t a b c -> a
345 -- | Variant for 4-ary type constructors
346 class Typeable4 t where
347 typeOf4 :: t a b c d -> TypeRep
349 -- | For defining a 'Typeable3' instance from any 'Typeable4' instance.
350 typeOf3Default :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
351 typeOf3Default x = typeOf4 x `mkAppTy` typeOf (argType x)
353 argType :: t a b c d -> a
356 -- | Variant for 5-ary type constructors
357 class Typeable5 t where
358 typeOf5 :: t a b c d e -> TypeRep
360 -- | For defining a 'Typeable4' instance from any 'Typeable5' instance.
361 typeOf4Default :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
362 typeOf4Default x = typeOf5 x `mkAppTy` typeOf (argType x)
364 argType :: t a b c d e -> a
367 -- | Variant for 6-ary type constructors
368 class Typeable6 t where
369 typeOf6 :: t a b c d e f -> TypeRep
371 -- | For defining a 'Typeable5' instance from any 'Typeable6' instance.
372 typeOf5Default :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
373 typeOf5Default x = typeOf6 x `mkAppTy` typeOf (argType x)
375 argType :: t a b c d e f -> a
378 -- | Variant for 7-ary type constructors
379 class Typeable7 t where
380 typeOf7 :: t a b c d e f g -> TypeRep
382 -- | For defining a 'Typeable6' instance from any 'Typeable7' instance.
383 typeOf6Default :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
384 typeOf6Default x = typeOf7 x `mkAppTy` typeOf (argType x)
386 argType :: t a b c d e f g -> a
389 #ifdef __GLASGOW_HASKELL__
390 -- Given a @Typeable@/n/ instance for an /n/-ary type constructor,
391 -- define the instances for partial applications.
392 -- Programmers using non-GHC implementations must do this manually
393 -- for each type constructor.
394 -- (The INSTANCE_TYPEABLE/n/ macros in Typeable.h include this.)
396 -- | One Typeable instance for all Typeable1 instances
397 instance (Typeable1 s, Typeable a)
398 => Typeable (s a) where
399 typeOf = typeOfDefault
401 -- | One Typeable1 instance for all Typeable2 instances
402 instance (Typeable2 s, Typeable a)
403 => Typeable1 (s a) where
404 typeOf1 = typeOf1Default
406 -- | One Typeable2 instance for all Typeable3 instances
407 instance (Typeable3 s, Typeable a)
408 => Typeable2 (s a) where
409 typeOf2 = typeOf2Default
411 -- | One Typeable3 instance for all Typeable4 instances
412 instance (Typeable4 s, Typeable a)
413 => Typeable3 (s a) where
414 typeOf3 = typeOf3Default
416 -- | One Typeable4 instance for all Typeable5 instances
417 instance (Typeable5 s, Typeable a)
418 => Typeable4 (s a) where
419 typeOf4 = typeOf4Default
421 -- | One Typeable5 instance for all Typeable6 instances
422 instance (Typeable6 s, Typeable a)
423 => Typeable5 (s a) where
424 typeOf5 = typeOf5Default
426 -- | One Typeable6 instance for all Typeable7 instances
427 instance (Typeable7 s, Typeable a)
428 => Typeable6 (s a) where
429 typeOf6 = typeOf6Default
431 #endif /* __GLASGOW_HASKELL__ */
433 -------------------------------------------------------------
437 -------------------------------------------------------------
439 -- | The type-safe cast operation
440 cast :: (Typeable a, Typeable b) => a -> Maybe b
443 r = if typeOf x == typeOf (fromJust r)
444 then Just $ unsafeCoerce x
447 -- | A flexible variation parameterised in a type constructor
448 gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
451 r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
452 then Just $ unsafeCoerce x
458 gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
461 r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
462 then Just $ unsafeCoerce x
467 -- | Cast for * -> * -> *
468 gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))
471 r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
472 then Just $ unsafeCoerce x
477 -------------------------------------------------------------
479 -- Instances of the Typeable classes for Prelude types
481 -------------------------------------------------------------
483 INSTANCE_TYPEABLE0((),unitTc,"()")
484 INSTANCE_TYPEABLE1([],listTc,"[]")
485 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
486 INSTANCE_TYPEABLE1(Ratio,ratioTc,"Ratio")
487 INSTANCE_TYPEABLE2((->),funTc,"->")
488 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
490 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
491 -- Types defined in GHC.IOBase
492 INSTANCE_TYPEABLE1(MVar,mvarTc,"MVar" )
495 INSTANCE_TYPEABLE2(Array,arrayTc,"Array")
496 INSTANCE_TYPEABLE2(IOArray,iOArrayTc,"IOArray")
498 #ifdef __GLASGOW_HASKELL__
499 -- Hugs has these too, but their Typeable<n> instances are defined
500 -- elsewhere to keep this module within Haskell 98.
501 -- This is important because every invocation of runhugs or ffihugs
502 -- uses this module via Data.Dynamic.
503 INSTANCE_TYPEABLE2(ST,stTc,"ST")
504 INSTANCE_TYPEABLE2(STRef,stRefTc,"STRef")
505 INSTANCE_TYPEABLE3(STArray,sTArrayTc,"STArray")
509 INSTANCE_TYPEABLE2((,),pairTc,"(,)")
510 INSTANCE_TYPEABLE3((,,),tup3Tc,"(,,)")
511 INSTANCE_TYPEABLE4((,,,),tup4Tc,"(,,,)")
512 INSTANCE_TYPEABLE5((,,,,),tup5Tc,"(,,,,)")
513 INSTANCE_TYPEABLE6((,,,,,),tup6Tc,"(,,,,,)")
514 INSTANCE_TYPEABLE7((,,,,,,),tup7Tc,"(,,,,,,)")
517 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
518 INSTANCE_TYPEABLE1(FunPtr,funPtrTc,"FunPtr")
519 #ifndef __GLASGOW_HASKELL__
520 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
522 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
523 INSTANCE_TYPEABLE1(IORef,iORefTc,"IORef")
525 -------------------------------------------------------
527 -- Generate Typeable instances for standard datatypes
529 -------------------------------------------------------
531 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
532 INSTANCE_TYPEABLE0(Char,charTc,"Char")
533 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
534 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
535 INSTANCE_TYPEABLE0(Int,intTc,"Int")
537 INSTANCE_TYPEABLE0(Word,wordTc,"Word" )
539 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
540 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
541 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
543 INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
544 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
545 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
546 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
548 INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
549 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
550 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
551 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
553 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
554 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
556 #ifdef __GLASGOW_HASKELL__
557 INSTANCE_TYPEABLE0(RealWorld,realWorldTc,"RealWorld")
560 ---------------------------------------------
564 ---------------------------------------------
567 newtype Key = Key Int deriving( Eq )
570 data KeyPr = KeyPr !Key !Key deriving( Eq )
572 hashKP :: KeyPr -> Int32
573 hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
575 data Cache = Cache { next_key :: !(IORef Key), -- Not used by GHC (calls genSym instead)
576 tc_tbl :: !(HT.HashTable String Key),
577 ap_tbl :: !(HT.HashTable KeyPr Key) }
579 {-# NOINLINE cache #-}
580 #ifdef __GLASGOW_HASKELL__
581 foreign import ccall unsafe "RtsTypeable.h getOrSetTypeableStore"
582 getOrSetTypeableStore :: Ptr a -> IO (Ptr a)
586 cache = unsafePerformIO $ do
587 empty_tc_tbl <- HT.new (==) HT.hashString
588 empty_ap_tbl <- HT.new (==) hashKP
589 key_loc <- newIORef (Key 1)
590 let ret = Cache { next_key = key_loc,
591 tc_tbl = empty_tc_tbl,
592 ap_tbl = empty_ap_tbl }
593 #ifdef __GLASGOW_HASKELL__
595 stable_ref <- newStablePtr ret
596 let ref = castStablePtrToPtr stable_ref
597 ref2 <- getOrSetTypeableStore ref
599 then deRefStablePtr stable_ref
601 freeStablePtr stable_ref
603 (castPtrToStablePtr ref2)
608 newKey :: IORef Key -> IO Key
609 #ifdef __GLASGOW_HASKELL__
610 newKey _ = do i <- genSym; return (Key i)
612 newKey kloc = do { k@(Key i) <- readIORef kloc ;
613 writeIORef kloc (Key (i+1)) ;
617 #ifdef __GLASGOW_HASKELL__
618 foreign import ccall unsafe "genSymZh"
622 mkTyConKey :: String -> Key
624 = unsafePerformIO $ do
625 let Cache {next_key = kloc, tc_tbl = tbl} = cache
626 mb_k <- HT.lookup tbl str
629 Nothing -> do { k <- newKey kloc ;
630 HT.insert tbl str k ;
633 appKey :: Key -> Key -> Key
635 = unsafePerformIO $ do
636 let Cache {next_key = kloc, ap_tbl = tbl} = cache
637 mb_k <- HT.lookup tbl kpr
640 Nothing -> do { k <- newKey kloc ;
641 HT.insert tbl kpr k ;
646 appKeys :: Key -> [Key] -> Key
647 appKeys k ks = foldl appKey k ks