[project @ 2005-02-02 13:26:13 by simonpj]
[ghc-base.git] / GHC / Weak.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.Weak
6 -- Copyright   :  (c) The University of Glasgow, 1998-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- Weak pointers.
14 --
15 -----------------------------------------------------------------------------
16
17 module GHC.Weak where
18
19 import GHC.Base
20 import Data.Maybe
21 import GHC.IOBase       ( IO(..), unIO )
22 import Data.Typeable    ( Typeable1(..), mkTyCon, mkTyConApp )
23
24 {-|
25 A weak pointer object with a key and a value.  The value has type @v@.
26
27 A weak pointer expresses a relationship between two objects, the
28 /key/ and the /value/:  if the key is considered to be alive by the
29 garbage collector, then the value is also alive.  A reference from
30 the value to the key does /not/ keep the key alive.
31
32 A weak pointer may also have a finalizer of type @IO ()@; if it does,
33 then the finalizer will be run at most once, at a time after the key
34 has become unreachable by the program (\"dead\").  The storage manager
35 attempts to run the finalizer(s) for an object soon after the object
36 dies, but promptness is not guaranteed.  
37
38 It is not guaranteed that a finalizer will eventually run, and no
39 attempt is made to run outstanding finalizers when the program exits.
40 Therefore finalizers should not be relied on to clean up resources -
41 other methods (eg. exception handlers) should be employed, possibly in
42 addition to finalisers.
43
44 References from the finalizer to the key are treated in the same way
45 as references from the value to the key: they do not keep the key
46 alive.  A finalizer may therefore ressurrect the key, perhaps by
47 storing it in the same data structure.
48
49 The finalizer, and the relationship between the key and the value,
50 exist regardless of whether the program keeps a reference to the
51 'Weak' object or not.
52
53 There may be multiple weak pointers with the same key.  In this
54 case, the finalizers for each of these weak pointers will all be
55 run in some arbitrary order, or perhaps concurrently, when the key
56 dies.  If the programmer specifies a finalizer that assumes it has
57 the only reference to an object (for example, a file that it wishes
58 to close), then the programmer must ensure that there is only one
59 such finalizer.
60
61 If there are no other threads to run, the runtime system will check
62 for runnable finalizers before declaring the system to be deadlocked.
63 -}
64 data Weak v = Weak (Weak# v)
65
66 #include "Typeable.h"
67 INSTANCE_TYPEABLE1(Weak,weakTc,"Weak")
68
69 -- | Establishes a weak pointer to @k@, with value @v@ and a finalizer.
70 --
71 -- This is the most general interface for building a weak pointer.
72 --
73 mkWeak  :: k                            -- ^ key
74         -> v                            -- ^ value
75         -> Maybe (IO ())                -- ^ finalizer
76         -> IO (Weak v)                  -- ^ returns: a weak pointer object
77
78 mkWeak key val (Just finalizer) = IO $ \s ->
79    case mkWeak# key val finalizer s of { (# s1, w #) -> (# s1, Weak w #) }
80 mkWeak key val Nothing = IO $ \s ->
81    case mkWeak# key val (unsafeCoerce# 0#) s of { (# s1, w #) -> (# s1, Weak w #) }
82
83 {-|
84 Dereferences a weak pointer.  If the key is still alive, then
85 @'Just' v@ is returned (where @v@ is the /value/ in the weak pointer), otherwise
86 'Nothing' is returned.
87
88 The return value of 'deRefWeak' depends on when the garbage collector
89 runs, hence it is in the 'IO' monad.
90 -}
91 deRefWeak :: Weak v -> IO (Maybe v)
92 deRefWeak (Weak w) = IO $ \s ->
93    case deRefWeak# w s of
94         (# s1, flag, p #) -> case flag of
95                                 0# -> (# s1, Nothing #)
96                                 _  -> (# s1, Just p #)
97
98 -- | Causes a the finalizer associated with a weak pointer to be run
99 -- immediately.
100 finalize :: Weak v -> IO ()
101 finalize (Weak w) = IO $ \s ->
102    case finalizeWeak# w s of
103         (# s1, 0#, _ #) -> (# s1, () #) -- already dead, or no finaliser
104         (# s1, _,  f #) -> f s1
105
106 {-
107 Instance Eq (Weak v) where
108   (Weak w1) == (Weak w2) = w1 `sameWeak#` w2
109 -}
110
111
112 -- run a batch of finalizers from the garbage collector.  We're given 
113 -- an array of finalizers and the length of the array, and we just
114 -- call each one in turn.
115 --
116 -- the IO primitives are inlined by hand here to get the optimal
117 -- code (sigh) --SDM.
118
119 runFinalizerBatch :: Int -> Array# (IO ()) -> IO ()
120 runFinalizerBatch (I# n) arr = 
121    let  go m  = IO $ \s ->
122                   case m of 
123                   0# -> (# s, () #)
124                   _  -> let m' = m -# 1# in
125                         case indexArray# arr m' of { (# io #) -> 
126                         case unIO io s of          { (# s, _ #) -> 
127                         unIO (go m') s
128                         }}
129    in
130         go n
131
132 \end{code}