[project @ 2002-12-11 15:55:17 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 __HUGS__
82 import Hugs.IO
83 import Hugs.IORef
84 import Hugs.IOExts
85 #endif
86
87 #ifdef __GLASGOW_HASKELL__
88 unsafeCoerce :: a -> b
89 unsafeCoerce = unsafeCoerce#
90 #endif
91
92 #include "Dynamic.h"
93
94 {-|
95   A value of type 'Dynamic' is an object encapsulated together with its type.
96
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').
100
101   'Show'ing a value of type 'Dynamic' returns a pretty-printed representation
102   of the object\'s type; useful for debugging.
103 -}
104 data Dynamic = Dynamic TypeRep Obj
105
106 instance Show Dynamic where
107    -- the instance just prints the type representation.
108    showsPrec _ (Dynamic t _) = 
109           showString "<<" . 
110           showsPrec 0 t   . 
111           showString ">>"
112
113 type Obj = forall a . a
114  -- Dummy type to hold the dynamically typed value.
115  --
116  -- In GHC's new eval/apply execution model this type must
117  -- be polymorphic.  It can't be a constructor, because then
118  -- GHC will use the constructor convention when evaluating it,
119  -- and this will go wrong if the object is really a function.  On
120  -- the other hand, if we use a polymorphic type, GHC will use
121  -- a fallback convention for evaluating it that works for all types.
122  -- (using a function type here would also work).
123
124 -- | A concrete representation of a (monomorphic) type.  'TypeRep'
125 -- supports reasonably efficient equality.
126 data TypeRep
127  = App TyCon   [TypeRep] 
128  | Fun TypeRep TypeRep
129    deriving ( Eq )
130
131 instance Show TypeRep where
132   showsPrec p (App tycon tys) =
133     case tys of
134       [] -> showsPrec p tycon
135       [x] | tycon == listTc    -> showChar '[' . shows x . showChar ']'
136       xs  
137         | isTupleTyCon tycon -> showTuple tycon xs
138         | otherwise          ->
139             showParen (p > 9) $
140             showsPrec p tycon . 
141             showChar ' '      . 
142             showArgs tys
143
144   showsPrec p (Fun f a) =
145      showParen (p > 8) $
146      showsPrec 9 f . showString " -> " . showsPrec 8 a
147
148 -- | An abstract representation of a type constructor.  'TyCon' objects can
149 -- be built using 'mkTyCon'.
150 data TyCon = TyCon Int String
151
152 instance Eq TyCon where
153   (TyCon t1 _) == (TyCon t2 _) = t1 == t2
154
155 instance Show TyCon where
156   showsPrec _ (TyCon _ s) = showString s
157
158
159 -- | Converts an arbitrary value into an object of type 'Dynamic'.  
160 --
161 -- The type of the object must be an instance of 'Typeable', which
162 -- ensures that only monomorphically-typed objects may be converted to
163 -- 'Dynamic'.  To convert a polymorphic object into 'Dynamic', give it
164 -- a monomorphic type signature.  For example:
165 --
166 -- >    toDyn (id :: Int -> Int)
167 --
168 toDyn :: Typeable a => a -> Dynamic
169 toDyn v = Dynamic (typeOf v) (unsafeCoerce v)
170
171 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
172 -- the correct type.  See also 'fromDynamic'.
173 fromDyn :: Typeable a
174         => Dynamic      -- ^ the dynamically-typed object
175         -> a            -- ^ a default value 
176         -> a            -- ^ returns: the value of the first argument, if
177                         -- it has the correct type, otherwise the value of
178                         -- the second argument.
179 fromDyn (Dynamic t v) def
180   | typeOf def == t = unsafeCoerce v
181   | otherwise       = def
182
183 -- | Converts a 'Dynamic' object back into an ordinary Haskell value of
184 -- the correct type.  See also 'fromDyn'.
185 fromDynamic
186         :: Typeable a
187         => Dynamic      -- ^ the dynamically-typed object
188         -> Maybe a      -- ^ returns: @'Just' a@, if the dyanmically-typed
189                         -- object has the correct type (and @a@ is its value), 
190                         -- or 'Nothing' otherwise.
191 fromDynamic (Dynamic t v) =
192   case unsafeCoerce v of 
193     r | t == typeOf r -> Just r
194       | otherwise     -> Nothing
195
196 -- | The class 'Typeable' allows a concrete representation of a type to
197 -- be calculated.
198 class Typeable a where
199   typeOf :: a -> TypeRep
200   -- ^ Takes a value of type @a@ and returns a concrete representation
201   -- of that type.  The /value/ of the argument should be ignored by
202   -- any instance of 'Typeable', so that it is safe to pass 'undefined' as
203   -- the argument.
204
205 isTupleTyCon :: TyCon -> Bool
206 isTupleTyCon (TyCon _ (',':_)) = True
207 isTupleTyCon _                 = False
208
209 -- If we enforce the restriction that there is only one
210 -- @TyCon@ for a type & it is shared among all its uses,
211 -- we can map them onto Ints very simply. The benefit is,
212 -- of course, that @TyCon@s can then be compared efficiently.
213
214 -- Provided the implementor of other @Typeable@ instances
215 -- takes care of making all the @TyCon@s CAFs (toplevel constants),
216 -- this will work. 
217
218 -- If this constraint does turn out to be a sore thumb, changing
219 -- the Eq instance for TyCons is trivial.
220
221 -- | Builds a 'TyCon' object representing a type constructor.  An
222 -- implementation of "Data.Dynamic" should ensure that the following holds:
223 --
224 -- >  mkTyCon "a" == mkTyCon "a"
225 --
226 -- NOTE: GHC\'s implementation is quite hacky, and the above equation
227 -- does not necessarily hold.  For defining your own instances of
228 -- 'Typeable', try to ensure that only one call to 'mkTyCon' exists
229 -- for each type constructor (put it at the top level, and annotate the
230 -- corresponding definition with a @NOINLINE@ pragma).
231 mkTyCon
232         :: String       -- ^ the name of the type constructor (should be unique
233                         -- in the program, so it might be wise to use the
234                         -- fully qualified name).
235         -> TyCon        -- ^ A unique 'TyCon' object
236 mkTyCon str = unsafePerformIO $ do
237    v <- readIORef uni
238    writeIORef uni (v+1)
239    return (TyCon v str)
240
241 {-# NOINLINE uni #-}
242 uni :: IORef Int
243 uni = unsafePerformIO ( newIORef 0 )
244
245 -- Some (Show.TypeRep) helpers:
246
247 showArgs :: Show a => [a] -> ShowS
248 showArgs [] = id
249 showArgs [a] = showsPrec 10 a
250 showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as 
251
252 showTuple :: TyCon -> [TypeRep] -> ShowS
253 showTuple (TyCon _ str) args = showChar '(' . go str args
254  where
255   go [] [a] = showsPrec 10 a . showChar ')'
256   go _  []  = showChar ')' -- a failure condition, really.
257   go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
258   go _ _   = showChar ')'
259
260
261 -- | Applies a type constructor to a sequence of types
262 mkAppTy  :: TyCon   -> [TypeRep] -> TypeRep
263 mkAppTy tyc args = App tyc args
264
265 -- | A special case of 'mkAppTy', which applies the function type constructor to
266 -- a pair of types.
267 mkFunTy  :: TypeRep -> TypeRep   -> TypeRep
268 mkFunTy f a = Fun f a
269
270 -- Auxillary functions
271
272 -- (f::(a->b)) `dynApply` (x::a) = (f a)::b
273 dynApply :: Dynamic -> Dynamic -> Maybe Dynamic
274 dynApply (Dynamic t1 f) (Dynamic t2 x) =
275   case applyTy t1 t2 of
276     Just t3 -> Just (Dynamic t3 ((unsafeCoerce f) x))
277     Nothing -> Nothing
278
279 dynApp :: Dynamic -> Dynamic -> Dynamic
280 dynApp f x = case dynApply f x of 
281              Just r -> r
282              Nothing -> error ("Type error in dynamic application.\n" ++
283                                "Can't apply function " ++ show f ++
284                                " to argument " ++ show x)
285
286 -- | Applies a type to a function type.  Returns: @'Just' u@ if the
287 -- first argument represents a function of type @t -> u@ and the
288 -- second argument represents a function of type @t@.  Otherwise,
289 -- returns 'Nothing'.
290 applyTy :: TypeRep -> TypeRep -> Maybe TypeRep
291 applyTy (Fun t1 t2) t3
292   | t1 == t3    = Just t2
293 applyTy _ _     = Nothing
294
295 -- Prelude types
296
297 listTc :: TyCon
298 listTc = mkTyCon "[]"
299
300 instance Typeable a => Typeable [a] where
301   typeOf ls = mkAppTy listTc [typeOf ((undefined:: [a] -> a) ls)]
302
303 unitTc :: TyCon
304 unitTc = mkTyCon "()"
305
306 instance Typeable () where
307   typeOf _ = mkAppTy unitTc []
308
309 tup2Tc :: TyCon
310 tup2Tc = mkTyCon ","
311
312 instance (Typeable a, Typeable b) => Typeable (a,b) where
313   typeOf tu = mkAppTy tup2Tc [typeOf ((undefined :: (a,b) -> a) tu),
314                               typeOf ((undefined :: (a,b) -> b) tu)]
315
316 tup3Tc :: TyCon
317 tup3Tc = mkTyCon ",,"
318
319 instance ( Typeable a , Typeable b , Typeable c) => Typeable (a,b,c) where
320   typeOf tu = mkAppTy tup3Tc [typeOf ((undefined :: (a,b,c) -> a) tu),
321                               typeOf ((undefined :: (a,b,c) -> b) tu),
322                               typeOf ((undefined :: (a,b,c) -> c) tu)]
323
324 tup4Tc :: TyCon
325 tup4Tc = mkTyCon ",,,"
326
327 instance ( Typeable a
328          , Typeable b
329          , Typeable c
330          , Typeable d) => Typeable (a,b,c,d) where
331   typeOf tu = mkAppTy tup4Tc [typeOf ((undefined :: (a,b,c,d) -> a) tu),
332                               typeOf ((undefined :: (a,b,c,d) -> b) tu),
333                               typeOf ((undefined :: (a,b,c,d) -> c) tu),
334                               typeOf ((undefined :: (a,b,c,d) -> d) tu)]
335
336 tup5Tc :: TyCon
337 tup5Tc = mkTyCon ",,,,"
338
339 instance ( Typeable a
340          , Typeable b
341          , Typeable c
342          , Typeable d
343          , Typeable e) => Typeable (a,b,c,d,e) where
344   typeOf tu = mkAppTy tup5Tc [typeOf ((undefined :: (a,b,c,d,e) -> a) tu),
345                               typeOf ((undefined :: (a,b,c,d,e) -> b) tu),
346                               typeOf ((undefined :: (a,b,c,d,e) -> c) tu),
347                               typeOf ((undefined :: (a,b,c,d,e) -> d) tu),
348                               typeOf ((undefined :: (a,b,c,d,e) -> e) tu)]
349
350 instance (Typeable a, Typeable b) => Typeable (a -> b) where
351   typeOf f = mkFunTy (typeOf ((undefined :: (a -> b) -> a) f))
352                      (typeOf ((undefined :: (a -> b) -> b) f))
353
354 INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
355 INSTANCE_TYPEABLE0(Char,charTc,"Char")
356 INSTANCE_TYPEABLE0(Float,floatTc,"Float")
357 INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
358 INSTANCE_TYPEABLE0(Int,intTc,"Int")
359 INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
360 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
361 INSTANCE_TYPEABLE1(IO,ioTc,"IO")
362 INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
363 INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
364 INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
365 INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
366 INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
367
368 INSTANCE_TYPEABLE0(Int8,int8Tc, "Int8")
369 INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
370 INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
371 INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
372
373 INSTANCE_TYPEABLE0(Word8,word8Tc, "Word8" )
374 INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
375 INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
376 INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
377
378 INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
379 INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
380 INSTANCE_TYPEABLE0(Dynamic,dynamicTc,"Dynamic")
381
382 #ifndef __NHC__
383 #include "Dynamic.h"
384 INSTANCE_TYPEABLE1(IORef,ioRefTc,"IORef")
385 #endif