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__
86 #ifdef __GLASGOW_HASKELL__
87 unsafeCoerce :: a -> b
88 unsafeCoerce = unsafeCoerce#
94 A value of type 'Dynamic' is an object encapsulated together with its type.
96 A 'Dynamic' may only represent a monomorphic value; an attempt to
97 create a value of type 'Dynamic' from a polymorphically-typed
98 expression will result in an ambiguity error (see 'toDyn').
100 'Show'ing a value of type 'Dynamic' returns a pretty-printed representation
101 of the object\'s type; useful for debugging.
103 data Dynamic = Dynamic TypeRep Obj
105 instance Show Dynamic where
106 -- the instance just prints the type representation.
107 showsPrec _ (Dynamic t _) =
113 -- dummy type to hold the dynamically typed value.
115 -- | A concrete representation of a (monomorphic) type. 'TypeRep'
116 -- supports reasonably efficient equality.
118 = App TyCon [TypeRep]
119 | Fun TypeRep TypeRep
122 instance Show TypeRep where
123 showsPrec p (App tycon tys) =
125 [] -> showsPrec p tycon
126 [x] | tycon == listTc -> showChar '[' . shows x . showChar ']'
128 | isTupleTyCon tycon -> showTuple tycon xs
135 showsPrec p (Fun f a) =
137 showsPrec 9 f . showString " -> " . showsPrec 8 a
139 -- | An abstract representation of a type constructor. 'TyCon' objects can
140 -- be built using 'mkTyCon'.
141 data TyCon = TyCon Int String
143 instance Eq TyCon where
144 (TyCon t1 _) == (TyCon t2 _) = t1 == t2
146 instance Show TyCon where
147 showsPrec _ (TyCon _ s) = showString s
150 -- | Converts an arbitrary value into an object of type 'Dynamic'.
152 -- The type of the object must be an instance of 'Typeable', which
153 -- ensures that only monomorphically-typed objects may be converted to
154 -- 'Dynamic'. To convert a polymorphic object into 'Dynamic', give it
155 -- a monomorphic type signature. For example:
157 -- > toDyn (id :: Int -> Int)
159 toDyn :: Typeable a => a -> Dynamic
160 toDyn v = Dynamic (typeOf v) (unsafeCoerce v)
162 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
163 -- the correct type. See also 'fromDynamic'.
164 fromDyn :: Typeable a
165 => Dynamic -- ^ the dynamically-typed object
166 -> a -- ^ a default value
167 -> a -- ^ returns: the value of the first argument, if
168 -- it has the correct type, otherwise the value of
169 -- the second argument.
170 fromDyn (Dynamic t v) def
171 | typeOf def == t = unsafeCoerce v
174 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
175 -- the correct type. See also 'fromDyn'.
178 => Dynamic -- ^ the dynamically-typed object
179 -> Maybe a -- ^ returns: @'Just' a@, if the dyanmically-typed
180 -- object has the correct type (and @a@ is its value),
181 -- or 'Nothing' otherwise.
182 fromDynamic (Dynamic t v) =
183 case unsafeCoerce v of
184 r | t == typeOf r -> Just r
185 | otherwise -> Nothing
187 -- | The class 'Typeable' allows a concrete representation of a type to
189 class Typeable a where
190 typeOf :: a -> TypeRep
191 -- ^ Takes a value of type @a@ and returns a concrete representation
192 -- of that type. The /value/ of the argument should be ignored by
193 -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
196 isTupleTyCon :: TyCon -> Bool
197 isTupleTyCon (TyCon _ (',':_)) = True
198 isTupleTyCon _ = False
200 -- If we enforce the restriction that there is only one
201 -- @TyCon@ for a type & it is shared among all its uses,
202 -- we can map them onto Ints very simply. The benefit is,
203 -- of course, that @TyCon@s can then be compared efficiently.
205 -- Provided the implementor of other @Typeable@ instances
206 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
209 -- If this constraint does turn out to be a sore thumb, changing
210 -- the Eq instance for TyCons is trivial.
212 -- | Builds a 'TyCon' object representing a type constructor. An
213 -- implementation of "Data.Dynamic" should ensure that the following holds:
215 -- > mkTyCon "a" == mkTyCon "a"
217 -- NOTE: GHC\'s implementation is quite hacky, and the above equation
218 -- does not necessarily hold. For defining your own instances of
219 -- 'Typeable', try to ensure that only one call to 'mkTyCon' exists
220 -- for each type constructor (put it at the top level, and annotate the
221 -- corresponding definition with a @NOINLINE@ pragma).
223 :: String -- ^ the name of the type constructor (should be unique
224 -- in the program, so it might be wise to use the
225 -- fully qualified name).
226 -> TyCon -- ^ A unique 'TyCon' object
227 mkTyCon str = unsafePerformIO $ do
234 uni = unsafePerformIO ( newIORef 0 )
236 -- Some (Show.TypeRep) helpers:
238 showArgs :: Show a => [a] -> ShowS
240 showArgs [a] = showsPrec 10 a
241 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as
243 showTuple :: TyCon -> [TypeRep] -> ShowS
244 showTuple (TyCon _ str) args = showChar '(' . go str args
246 go [] [a] = showsPrec 10 a . showChar ')'
247 go _ [] = showChar ')' -- a failure condition, really.
248 go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
249 go _ _ = showChar ')'
252 -- | Applies a type constructor to a sequence of types
253 mkAppTy :: TyCon -> [TypeRep] -> TypeRep
254 mkAppTy tyc args = App tyc args
256 -- | A special case of 'mkAppTy', which applies the function type constructor to
258 mkFunTy :: TypeRep -> TypeRep -> TypeRep
259 mkFunTy f a = Fun f a
261 -- Auxillary functions
263 -- (f::(a->b)) `dynApply` (x::a) = (f a)::b
264 dynApply :: Dynamic -> Dynamic -> Maybe Dynamic
265 dynApply (Dynamic t1 f) (Dynamic t2 x) =
266 case applyTy t1 t2 of
267 Just t3 -> Just (Dynamic t3 ((unsafeCoerce f) x))
270 dynApp :: Dynamic -> Dynamic -> Dynamic
271 dynApp f x = case dynApply f x of
273 Nothing -> error ("Type error in dynamic application.\n" ++
274 "Can't apply function " ++ show f ++
275 " to argument " ++ show x)
277 -- | Applies a type to a function type. Returns: @'Just' u@ if the
278 -- first argument represents a function of type @t -> u@ and the
279 -- second argument represents a function of type @t@. Otherwise,
280 -- returns 'Nothing'.
281 applyTy :: TypeRep -> TypeRep -> Maybe TypeRep
282 applyTy (Fun t1 t2) t3
284 applyTy _ _ = Nothing
289 listTc = mkTyCon "[]"
291 instance Typeable a => Typeable [a] where
292 typeOf ls = mkAppTy listTc [typeOf ((undefined:: [a] -> a) ls)]
295 unitTc = mkTyCon "()"
297 instance Typeable () where
298 typeOf _ = mkAppTy unitTc []
303 instance (Typeable a, Typeable b) => Typeable (a,b) where
304 typeOf tu = mkAppTy tup2Tc [typeOf ((undefined :: (a,b) -> a) tu),
305 typeOf ((undefined :: (a,b) -> b) tu)]
308 tup3Tc = mkTyCon ",,"
310 instance ( Typeable a , Typeable b , Typeable c) => Typeable (a,b,c) where
311 typeOf tu = mkAppTy tup3Tc [typeOf ((undefined :: (a,b,c) -> a) tu),
312 typeOf ((undefined :: (a,b,c) -> b) tu),
313 typeOf ((undefined :: (a,b,c) -> c) tu)]
316 tup4Tc = mkTyCon ",,,"
318 instance ( Typeable a
321 , Typeable d) => Typeable (a,b,c,d) where
322 typeOf tu = mkAppTy tup4Tc [typeOf ((undefined :: (a,b,c,d) -> a) tu),
323 typeOf ((undefined :: (a,b,c,d) -> b) tu),
324 typeOf ((undefined :: (a,b,c,d) -> c) tu),
325 typeOf ((undefined :: (a,b,c,d) -> d) tu)]
328 tup5Tc = mkTyCon ",,,,"
330 instance ( Typeable a
334 , Typeable e) => Typeable (a,b,c,d,e) where
335 typeOf tu = mkAppTy tup5Tc [typeOf ((undefined :: (a,b,c,d,e) -> a) tu),
336 typeOf ((undefined :: (a,b,c,d,e) -> b) tu),
337 typeOf ((undefined :: (a,b,c,d,e) -> c) tu),
338 typeOf ((undefined :: (a,b,c,d,e) -> d) tu),
339 typeOf ((undefined :: (a,b,c,d,e) -> e) tu)]
341 instance (Typeable a, Typeable b) => Typeable (a -> b) where
342 typeOf f = mkFunTy (typeOf ((undefined :: (a -> b) -> a) f))
343 (typeOf ((undefined :: (a -> b) -> b) f))
345 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
346 INSTANCE_TYPEABLE0(Char,charTc,"Char")
347 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
348 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
349 INSTANCE_TYPEABLE0(Int,intTc,"Int")
350 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
351 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
352 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
353 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
354 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
355 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
356 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
357 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
359 INSTANCE_TYPEABLE0(Int8,int8Tc, "Int8")
360 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
361 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
362 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
364 INSTANCE_TYPEABLE0(Word8,word8Tc, "Word8" )
365 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
366 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
367 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
369 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
370 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
371 INSTANCE_TYPEABLE0(Dynamic,dynamicTc,"Dynamic")