[project @ 2002-07-03 13:05:28 by simonmar]
[ghc-base.git] / Data / Dynamic.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Data.Dynamic
5 -- Copyright   :  (c) The University of Glasgow 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  experimental
10 -- Portability :  portable
11 --
12 -- The Dynamic interface provides basic support for dynamic types.
13 -- 
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.
18 -- 
19 -----------------------------------------------------------------------------
20
21 module Data.Dynamic
22   (
23         -- * The @Dynamic@ type
24         Dynamic,        -- abstract, instance of: Show, Typeable
25
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
30         
31         -- * Applying functions of dynamic type
32         dynApply,
33         dynApp,
34
35         -- * Concrete Type Representations
36         
37         -- | This section is useful if you need to define your own
38         -- instances of 'Typeable'.
39
40         Typeable(
41              typeOf),   -- :: a -> TypeRep
42
43         -- ** Building concrete type representations
44         TypeRep,        -- abstract, instance of: Eq, Show, Typeable
45         TyCon,          -- abstract, instance of: Eq, Show, Typeable
46
47         mkTyCon,        -- :: String  -> TyCon
48         mkAppTy,        -- :: TyCon   -> [TypeRep] -> TypeRep
49         mkFunTy,        -- :: TypeRep -> TypeRep   -> TypeRep
50         applyTy,        -- :: TypeRep -> TypeRep   -> Maybe TypeRep
51
52         -- 
53         -- let fTy = mkTyCon "Foo" in show (mkAppTy (mkTyCon ",,")
54         --                                 [fTy,fTy,fTy])
55         -- 
56         -- returns "(Foo,Foo,Foo)"
57         --
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
61         -- the 5-tuple tycon.
62         ) where
63
64
65 import Data.Maybe
66 import Data.Either
67 import Data.Int
68 import Data.Word
69 import Foreign.Ptr
70 import Foreign.StablePtr
71
72 #ifdef __GLASGOW_HASKELL__
73 import GHC.Base
74 import GHC.Show
75 import GHC.Err
76 import GHC.Num
77 import GHC.Float
78 import GHC.IOBase
79 #endif
80
81 #ifdef __GLASGOW_HASKELL__
82 unsafeCoerce :: a -> b
83 unsafeCoerce = unsafeCoerce#
84 #endif
85
86 #include "Dynamic.h"
87
88 {-|
89   A value of type 'Dynamic' is an object encapsulated together with its type.
90
91   A 'Dynamic' may only represent a monomorphic value; an attempt to
92   create a value of type 'Dynamic' from a polymorphically-typed
93   expression will result in an ambiguity error (see 'toDyn').
94
95   'Show'ing a value of type 'Dynamic' returns a pretty-printed representation
96   of the object\'s type; useful for debugging.
97 -}
98 data Dynamic = Dynamic TypeRep Obj
99
100 instance Show Dynamic where
101    -- the instance just prints the type representation.
102    showsPrec _ (Dynamic t _) = 
103           showString "<<" . 
104           showsPrec 0 t   . 
105           showString ">>"
106
107 data Obj = Obj  
108  -- dummy type to hold the dynamically typed value.
109
110 -- | A concrete representation of a (monomorphic) type.  'TypeRep'
111 -- supports reasonably efficient equality.
112 data TypeRep
113  = App TyCon   [TypeRep] 
114  | Fun TypeRep TypeRep
115    deriving ( Eq )
116
117 instance Show TypeRep where
118   showsPrec p (App tycon tys) =
119     case tys of
120       [] -> showsPrec p tycon
121       [x] | tycon == listTc    -> showChar '[' . shows x . showChar ']'
122       xs  
123         | isTupleTyCon tycon -> showTuple tycon xs
124         | otherwise          ->
125             showParen (p > 9) $
126             showsPrec p tycon . 
127             showChar ' '      . 
128             showArgs tys
129
130   showsPrec p (Fun f a) =
131      showParen (p > 8) $
132      showsPrec 9 f . showString " -> " . showsPrec 8 a
133
134 -- | An abstract representation of a type constructor.  'TyCon' objects can
135 -- be built using 'mkTyCon'.
136 data TyCon = TyCon Int String
137
138 instance Eq TyCon where
139   (TyCon t1 _) == (TyCon t2 _) = t1 == t2
140
141 instance Show TyCon where
142   showsPrec _ (TyCon _ s) = showString s
143
144
145 -- | Converts an arbitrary value into an object of type 'Dynamic'.  
146 --
147 -- The type of the object must be an instance of 'Typeable', which
148 -- ensures that only monomorphically-typed objects may be converted to
149 -- 'Dynamic'.  To convert a polymorphic object into 'Dynamic', give it
150 -- a monomorphic type signature.  For example:
151 --
152 -- >    toDyn (id :: Int -> Int)
153 --
154 toDyn :: Typeable a => a -> Dynamic
155 toDyn v = Dynamic (typeOf v) (unsafeCoerce v)
156
157 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
158 -- the correct type.  See also 'fromDynamic'.
159 fromDyn :: Typeable a
160         => Dynamic      -- ^ the dynamically-typed object
161         -> a            -- ^ a default value 
162         -> a            -- ^ returns: the value of the first argument, if
163                         -- it has the correct type, otherwise the value of
164                         -- the second argument.
165 fromDyn (Dynamic t v) def
166   | typeOf def == t = unsafeCoerce v
167   | otherwise       = def
168
169 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
170 -- the correct type.  See also 'fromDyn'.
171 fromDynamic
172         :: Typeable a
173         => Dynamic      -- ^ the dynamically-typed object
174         -> Maybe a      -- ^ returns: @'Just' a@, if the dyanmically-typed
175                         -- object has the correct type (and @a@ is its value), 
176                         -- or 'Nothing' otherwise.
177 fromDynamic (Dynamic t v) =
178   case unsafeCoerce v of 
179     r | t == typeOf r -> Just r
180       | otherwise     -> Nothing
181
182 -- | The class 'Typeable' allows a concrete representation of a type to
183 -- be calculated.
184 class Typeable a where
185   typeOf :: a -> TypeRep
186   -- ^ Takes a value of type @a@ and returns a concrete representation
187   -- of that type.  The /value/ of the argument should be ignored by
188   -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
189   -- the argument.
190
191 isTupleTyCon :: TyCon -> Bool
192 isTupleTyCon (TyCon _ (',':_)) = True
193 isTupleTyCon _                 = False
194
195 -- If we enforce the restriction that there is only one
196 -- @TyCon@ for a type & it is shared among all its uses,
197 -- we can map them onto Ints very simply. The benefit is,
198 -- of course, that @TyCon@s can then be compared efficiently.
199
200 -- Provided the implementor of other @Typeable@ instances
201 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
202 -- this will work. 
203
204 -- If this constraint does turn out to be a sore thumb, changing
205 -- the Eq instance for TyCons is trivial.
206
207 -- | Builds a 'TyCon' object representing a type constructor.  An
208 -- implementation of "Data.Dynamic" should ensure that the following holds:
209 --
210 -- >  mkTyCon "a" == mkTyCon "a"
211 --
212 -- NOTE: GHC\'s implementation is quite hacky, and the above equation
213 -- does not necessarily hold.  For defining your own instances of
214 -- 'Typeable', try to ensure that only one call to 'mkTyCon' exists
215 -- for each type constructor (put it at the top level, and annotate the
216 -- corresponding definition with a @NOINLINE@ pragma).
217 mkTyCon
218         :: String       -- ^ the name of the type constructor (should be unique
219                         -- in the program, so it might be wise to use the
220                         -- fully qualified name).
221         -> TyCon        -- ^ A unique 'TyCon' object
222 mkTyCon str = unsafePerformIO $ do
223    v <- readIORef uni
224    writeIORef uni (v+1)
225    return (TyCon v str)
226
227 {-# NOINLINE uni #-}
228 uni :: IORef Int
229 uni = unsafePerformIO ( newIORef 0 )
230
231 -- Some (Show.TypeRep) helpers:
232
233 showArgs :: Show a => [a] -> ShowS
234 showArgs [] = id
235 showArgs [a] = showsPrec 10 a
236 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as 
237
238 showTuple :: TyCon -> [TypeRep] -> ShowS
239 showTuple (TyCon _ str) args = showChar '(' . go str args
240  where
241   go [] [a] = showsPrec 10 a . showChar ')'
242   go _  []  = showChar ')' -- a failure condition, really.
243   go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
244   go _ _   = showChar ')'
245
246
247 -- | Applies a type constructor to a sequence of types
248 mkAppTy  :: TyCon   -> [TypeRep] -> TypeRep
249 mkAppTy tyc args = App tyc args
250
251 -- | A special case of 'mkAppTy', which applies the function type constructor to
252 -- a pair of types.
253 mkFunTy  :: TypeRep -> TypeRep   -> TypeRep
254 mkFunTy f a = Fun f a
255
256 -- Auxillary functions
257
258 -- (f::(a->b)) `dynApply` (x::a) = (f a)::b
259 dynApply :: Dynamic -> Dynamic -> Maybe Dynamic
260 dynApply (Dynamic t1 f) (Dynamic t2 x) =
261   case applyTy t1 t2 of
262     Just t3 -> Just (Dynamic t3 ((unsafeCoerce f) x))
263     Nothing -> Nothing
264
265 dynApp :: Dynamic -> Dynamic -> Dynamic
266 dynApp f x = case dynApply f x of 
267              Just r -> r
268              Nothing -> error ("Type error in dynamic application.\n" ++
269                                "Can't apply function " ++ show f ++
270                                " to argument " ++ show x)
271
272 -- | Applies a type to a function type.  Returns: @'Just' u@ if the
273 -- first argument represents a function of type @t -> u@ and the
274 -- second argument represents a function of type @t@.  Otherwise,
275 -- returns 'Nothing'.
276 applyTy :: TypeRep -> TypeRep -> Maybe TypeRep
277 applyTy (Fun t1 t2) t3
278   | t1 == t3    = Just t2
279 applyTy _ _     = Nothing
280
281 -- Prelude types
282
283 listTc :: TyCon
284 listTc = mkTyCon "[]"
285
286 instance Typeable a => Typeable [a] where
287   typeOf ls = mkAppTy listTc [typeOf ((undefined:: [a] -> a) ls)]
288
289 unitTc :: TyCon
290 unitTc = mkTyCon "()"
291
292 instance Typeable () where
293   typeOf _ = mkAppTy unitTc []
294
295 tup2Tc :: TyCon
296 tup2Tc = mkTyCon ","
297
298 instance (Typeable a, Typeable b) => Typeable (a,b) where
299   typeOf tu = mkAppTy tup2Tc [typeOf ((undefined :: (a,b) -> a) tu),
300                               typeOf ((undefined :: (a,b) -> b) tu)]
301
302 tup3Tc :: TyCon
303 tup3Tc = mkTyCon ",,"
304
305 instance ( Typeable a , Typeable b , Typeable c) => Typeable (a,b,c) where
306   typeOf tu = mkAppTy tup3Tc [typeOf ((undefined :: (a,b,c) -> a) tu),
307                               typeOf ((undefined :: (a,b,c) -> b) tu),
308                               typeOf ((undefined :: (a,b,c) -> c) tu)]
309
310 tup4Tc :: TyCon
311 tup4Tc = mkTyCon ",,,"
312
313 instance ( Typeable a
314          , Typeable b
315          , Typeable c
316          , Typeable d) => Typeable (a,b,c,d) where
317   typeOf tu = mkAppTy tup4Tc [typeOf ((undefined :: (a,b,c,d) -> a) tu),
318                               typeOf ((undefined :: (a,b,c,d) -> b) tu),
319                               typeOf ((undefined :: (a,b,c,d) -> c) tu),
320                               typeOf ((undefined :: (a,b,c,d) -> d) tu)]
321
322 tup5Tc :: TyCon
323 tup5Tc = mkTyCon ",,,,"
324
325 instance ( Typeable a
326          , Typeable b
327          , Typeable c
328          , Typeable d
329          , Typeable e) => Typeable (a,b,c,d,e) where
330   typeOf tu = mkAppTy tup5Tc [typeOf ((undefined :: (a,b,c,d,e) -> a) tu),
331                               typeOf ((undefined :: (a,b,c,d,e) -> b) tu),
332                               typeOf ((undefined :: (a,b,c,d,e) -> c) tu),
333                               typeOf ((undefined :: (a,b,c,d,e) -> d) tu),
334                               typeOf ((undefined :: (a,b,c,d,e) -> e) tu)]
335
336 instance (Typeable a, Typeable b) => Typeable (a -> b) where
337   typeOf f = mkFunTy (typeOf ((undefined :: (a -> b) -> a) f))
338                      (typeOf ((undefined :: (a -> b) -> b) f))
339
340 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
341 INSTANCE_TYPEABLE0(Char,charTc,"Char")
342 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
343 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
344 INSTANCE_TYPEABLE0(Int,intTc,"Int")
345 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
346 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
347 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
348 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
349 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
350 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
351 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
352 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
353
354 INSTANCE_TYPEABLE0(Int8,int8Tc, "Int8")
355 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
356 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
357 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
358
359 INSTANCE_TYPEABLE0(Word8,word8Tc, "Word8" )
360 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
361 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
362 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
363
364 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
365 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
366 INSTANCE_TYPEABLE0(Dynamic,dynamicTc,"Dynamic")