1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : Data.Dynamic
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : portable
12 -- The Dynamic interface provides basic support for dynamic types.
14 -- Operations for injecting values of arbitrary type into
15 -- a dynamically typed value, Dynamic, are provided, together
16 -- with operations for converting dynamic values into a concrete
17 -- (monomorphic) type.
19 -----------------------------------------------------------------------------
23 -- * The @Dynamic@ type
24 Dynamic, -- abstract, instance of: Show, Typeable
26 -- * Converting to and from @Dynamic@
27 toDyn, -- :: Typeable a => a -> Dynamic
28 fromDyn, -- :: Typeable a => Dynamic -> a -> a
29 fromDynamic, -- :: Typeable a => Dynamic -> Maybe a
31 -- * Applying functions of dynamic type
35 -- * Concrete Type Representations
37 -- | This section is useful if you need to define your own
38 -- instances of 'Typeable'.
41 typeOf), -- :: a -> TypeRep
43 -- ** Building concrete type representations
44 TypeRep, -- abstract, instance of: Eq, Show, Typeable
45 TyCon, -- abstract, instance of: Eq, Show, Typeable
47 mkTyCon, -- :: String -> TyCon
48 mkAppTy, -- :: TyCon -> [TypeRep] -> TypeRep
49 mkFunTy, -- :: TypeRep -> TypeRep -> TypeRep
50 applyTy, -- :: TypeRep -> TypeRep -> Maybe TypeRep
53 -- let fTy = mkTyCon "Foo" in show (mkAppTy (mkTyCon ",,")
56 -- returns "(Foo,Foo,Foo)"
58 -- The TypeRep Show instance promises to print tuple types
59 -- correctly. Tuple type constructors are specified by a
60 -- sequence of commas, e.g., (mkTyCon ",,,,") returns
70 import Foreign.StablePtr
72 #ifdef __GLASGOW_HASKELL__
87 #ifdef __GLASGOW_HASKELL__
88 unsafeCoerce :: a -> b
89 unsafeCoerce = unsafeCoerce#
95 A value of type 'Dynamic' is an object encapsulated together with its type.
97 A 'Dynamic' may only represent a monomorphic value; an attempt to
98 create a value of type 'Dynamic' from a polymorphically-typed
99 expression will result in an ambiguity error (see 'toDyn').
101 'Show'ing a value of type 'Dynamic' returns a pretty-printed representation
102 of the object\'s type; useful for debugging.
104 data Dynamic = Dynamic TypeRep Obj
106 instance Show Dynamic where
107 -- the instance just prints the type representation.
108 showsPrec _ (Dynamic t _) =
113 #ifdef __GLASGOW_HASKELL__
114 type Obj = forall a . a
115 -- Dummy type to hold the dynamically typed value.
117 -- In GHC's new eval/apply execution model this type must
118 -- be polymorphic. It can't be a constructor, because then
119 -- GHC will use the constructor convention when evaluating it,
120 -- and this will go wrong if the object is really a function. On
121 -- the other hand, if we use a polymorphic type, GHC will use
122 -- a fallback convention for evaluating it that works for all types.
123 -- (using a function type here would also work).
128 -- | A concrete representation of a (monomorphic) type. 'TypeRep'
129 -- supports reasonably efficient equality.
131 = App TyCon [TypeRep]
132 | Fun TypeRep TypeRep
135 instance Show TypeRep where
136 showsPrec p (App tycon tys) =
138 [] -> showsPrec p tycon
139 [x] | tycon == listTc -> showChar '[' . shows x . showChar ']'
141 | isTupleTyCon tycon -> showTuple tycon xs
148 showsPrec p (Fun f a) =
150 showsPrec 9 f . showString " -> " . showsPrec 8 a
152 -- | An abstract representation of a type constructor. 'TyCon' objects can
153 -- be built using 'mkTyCon'.
154 data TyCon = TyCon Int String
156 instance Eq TyCon where
157 (TyCon t1 _) == (TyCon t2 _) = t1 == t2
159 instance Show TyCon where
160 showsPrec _ (TyCon _ s) = showString s
163 -- | Converts an arbitrary value into an object of type 'Dynamic'.
165 -- The type of the object must be an instance of 'Typeable', which
166 -- ensures that only monomorphically-typed objects may be converted to
167 -- 'Dynamic'. To convert a polymorphic object into 'Dynamic', give it
168 -- a monomorphic type signature. For example:
170 -- > toDyn (id :: Int -> Int)
172 toDyn :: Typeable a => a -> Dynamic
173 toDyn v = Dynamic (typeOf v) (unsafeCoerce v)
175 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
176 -- the correct type. See also 'fromDynamic'.
177 fromDyn :: Typeable a
178 => Dynamic -- ^ the dynamically-typed object
179 -> a -- ^ a default value
180 -> a -- ^ returns: the value of the first argument, if
181 -- it has the correct type, otherwise the value of
182 -- the second argument.
183 fromDyn (Dynamic t v) def
184 | typeOf def == t = unsafeCoerce v
187 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
188 -- the correct type. See also 'fromDyn'.
191 => Dynamic -- ^ the dynamically-typed object
192 -> Maybe a -- ^ returns: @'Just' a@, if the dyanmically-typed
193 -- object has the correct type (and @a@ is its value),
194 -- or 'Nothing' otherwise.
195 fromDynamic (Dynamic t v) =
196 case unsafeCoerce v of
197 r | t == typeOf r -> Just r
198 | otherwise -> Nothing
200 -- | The class 'Typeable' allows a concrete representation of a type to
202 class Typeable a where
203 typeOf :: a -> TypeRep
204 -- ^ Takes a value of type @a@ and returns a concrete representation
205 -- of that type. The /value/ of the argument should be ignored by
206 -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
209 isTupleTyCon :: TyCon -> Bool
210 isTupleTyCon (TyCon _ (',':_)) = True
211 isTupleTyCon _ = False
213 -- If we enforce the restriction that there is only one
214 -- @TyCon@ for a type & it is shared among all its uses,
215 -- we can map them onto Ints very simply. The benefit is,
216 -- of course, that @TyCon@s can then be compared efficiently.
218 -- Provided the implementor of other @Typeable@ instances
219 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
222 -- If this constraint does turn out to be a sore thumb, changing
223 -- the Eq instance for TyCons is trivial.
225 -- | Builds a 'TyCon' object representing a type constructor. An
226 -- implementation of "Data.Dynamic" should ensure that the following holds:
228 -- > mkTyCon "a" == mkTyCon "a"
230 -- NOTE: GHC\'s implementation is quite hacky, and the above equation
231 -- does not necessarily hold. For defining your own instances of
232 -- 'Typeable', try to ensure that only one call to 'mkTyCon' exists
233 -- for each type constructor (put it at the top level, and annotate the
234 -- corresponding definition with a @NOINLINE@ pragma).
236 :: 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 = unsafePerformIO $ do
247 uni = unsafePerformIO ( newIORef 0 )
249 -- Some (Show.TypeRep) helpers:
251 showArgs :: Show a => [a] -> ShowS
253 showArgs [a] = showsPrec 10 a
254 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as
256 showTuple :: TyCon -> [TypeRep] -> ShowS
257 showTuple (TyCon _ str) args = showChar '(' . go str args
259 go [] [a] = showsPrec 10 a . showChar ')'
260 go _ [] = showChar ')' -- a failure condition, really.
261 go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
262 go _ _ = showChar ')'
265 -- | Applies a type constructor to a sequence of types
266 mkAppTy :: TyCon -> [TypeRep] -> TypeRep
267 mkAppTy tyc args = App tyc args
269 -- | A special case of 'mkAppTy', which applies the function type constructor to
271 mkFunTy :: TypeRep -> TypeRep -> TypeRep
272 mkFunTy f a = Fun f a
274 -- Auxillary functions
276 -- (f::(a->b)) `dynApply` (x::a) = (f a)::b
277 dynApply :: Dynamic -> Dynamic -> Maybe Dynamic
278 dynApply (Dynamic t1 f) (Dynamic t2 x) =
279 case applyTy t1 t2 of
280 Just t3 -> Just (Dynamic t3 ((unsafeCoerce f) x))
283 dynApp :: Dynamic -> Dynamic -> Dynamic
284 dynApp f x = case dynApply f x of
286 Nothing -> error ("Type error in dynamic application.\n" ++
287 "Can't apply function " ++ show f ++
288 " to argument " ++ show x)
290 -- | Applies a type to a function type. Returns: @'Just' u@ if the
291 -- first argument represents a function of type @t -> u@ and the
292 -- second argument represents a function of type @t@. Otherwise,
293 -- returns 'Nothing'.
294 applyTy :: TypeRep -> TypeRep -> Maybe TypeRep
295 applyTy (Fun t1 t2) t3
297 applyTy _ _ = Nothing
302 listTc = mkTyCon "[]"
304 instance Typeable a => Typeable [a] where
305 typeOf ls = mkAppTy listTc [typeOf ((undefined:: [a] -> a) ls)]
308 unitTc = mkTyCon "()"
310 instance Typeable () where
311 typeOf _ = mkAppTy unitTc []
316 instance (Typeable a, Typeable b) => Typeable (a,b) where
317 typeOf tu = mkAppTy tup2Tc [typeOf ((undefined :: (a,b) -> a) tu),
318 typeOf ((undefined :: (a,b) -> b) tu)]
321 tup3Tc = mkTyCon ",,"
323 instance ( Typeable a , Typeable b , Typeable c) => Typeable (a,b,c) where
324 typeOf tu = mkAppTy tup3Tc [typeOf ((undefined :: (a,b,c) -> a) tu),
325 typeOf ((undefined :: (a,b,c) -> b) tu),
326 typeOf ((undefined :: (a,b,c) -> c) tu)]
329 tup4Tc = mkTyCon ",,,"
331 instance ( Typeable a
334 , Typeable d) => Typeable (a,b,c,d) where
335 typeOf tu = mkAppTy tup4Tc [typeOf ((undefined :: (a,b,c,d) -> a) tu),
336 typeOf ((undefined :: (a,b,c,d) -> b) tu),
337 typeOf ((undefined :: (a,b,c,d) -> c) tu),
338 typeOf ((undefined :: (a,b,c,d) -> d) tu)]
341 tup5Tc = mkTyCon ",,,,"
343 instance ( Typeable a
347 , Typeable e) => Typeable (a,b,c,d,e) where
348 typeOf tu = mkAppTy tup5Tc [typeOf ((undefined :: (a,b,c,d,e) -> a) tu),
349 typeOf ((undefined :: (a,b,c,d,e) -> b) tu),
350 typeOf ((undefined :: (a,b,c,d,e) -> c) tu),
351 typeOf ((undefined :: (a,b,c,d,e) -> d) tu),
352 typeOf ((undefined :: (a,b,c,d,e) -> e) tu)]
354 instance (Typeable a, Typeable b) => Typeable (a -> b) where
355 typeOf f = mkFunTy (typeOf ((undefined :: (a -> b) -> a) f))
356 (typeOf ((undefined :: (a -> b) -> b) f))
358 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
359 INSTANCE_TYPEABLE0(Char,charTc,"Char")
360 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
361 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
362 INSTANCE_TYPEABLE0(Int,intTc,"Int")
363 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
364 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
365 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
366 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
367 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
368 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
369 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
370 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
372 INSTANCE_TYPEABLE0(Int8,int8Tc, "Int8")
373 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
374 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
375 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
377 INSTANCE_TYPEABLE0(Word8,word8Tc, "Word8" )
378 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
379 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
380 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
382 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
383 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
384 INSTANCE_TYPEABLE0(Dynamic,dynamicTc,"Dynamic")
388 INSTANCE_TYPEABLE1(IORef,ioRefTc,"IORef")