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