GC: refactored Ptr specific test implementation into Mate/Tests/MockRefs;
[mate.git] / Mate / GC.hs
1 {-# LANGUAGE ScopedTypeVariables #-}
2 module Mate.GC 
3   ( RefObj(..), PrintableRef(..), traverseIO, markTree'' 
4     {- dont export generic versions for high performance -> remove for production -}) where
5
6 import Control.Monad
7 import qualified Data.Set as S
8
9 import Foreign.Ptr (IntPtr)
10
11 class (Eq a, Ord a) => RefObj a where
12   
13   payload :: a -> IO IntPtr
14
15   refs      :: a -> IO [a]
16   patchRefs :: a -> [a] -> IO ()
17   newRef    :: a -> a -> IO ()
18   
19   marked  :: a -> IO Bool
20   mark    :: a -> IO ()
21   unmark  :: a -> IO ()
22   
23   copy :: a -> IO a
24
25 class PrintableRef a where
26   printRef :: a -> IO ()
27
28 -- | Generically marks a graph (can be used to set mark bit and reset mark bit at the same time
29 -- using customized loopcheck and marker funcs (i.e. to set the bit check on ==1 and on ==0 otherwise)
30 -- Furthermore it produces a list of visited nodes (this can be all live one (or dead on respectively)
31 markTree'' :: RefObj a => (a -> IO Bool) -> (a -> IO ()) -> [a] -> a -> IO [a]
32 markTree'' loopcheck marker ws root = do loop <- loopcheck root
33                                          if loop then return ws else liftM (root :) continue
34     where continue = marker root >> refs root >>= foldM (markTree'' loopcheck marker) ws
35
36 -- | For debugging only (implements custom loop check with Data.Set!)
37 traverseIO :: RefObj o => (o -> IO ()) -> o -> IO ()
38 traverseIO f = void . traverseIO' f S.empty
39
40 traverseIO' ::  RefObj a => (a -> IO ()) -> S.Set a -> a -> IO (S.Set a)
41 traverseIO' f ws root = if S.member root ws then f root >> return ws
42                            else f root >> refs root >>= cont
43   where cont = foldM (\ws x -> do let ws' = S.insert x ws
44                                   traverseIO' f ws' x) ws'
45         ws' = S.insert root ws
46
47 markTree :: RefObj a => a -> IO ()
48 markTree root = marked root >>= (`unless` continue)
49   where continue = mark root >> refs root >>= mapM_  markTree
50