1 {-# LANGUAGE ScopedTypeVariables #-}
3 ( RefObj(..), PrintableRef(..), traverseIO, markTree''
4 {- dont export generic versions for high performance -> remove for production -}) where
7 import qualified Data.Set as S
9 import Foreign.Ptr (IntPtr)
11 class (Eq a, Ord a) => RefObj a where
13 payload :: a -> IO IntPtr
16 patchRefs :: a -> [a] -> IO ()
17 newRef :: a -> a -> IO ()
19 marked :: a -> IO Bool
25 class PrintableRef a where
26 printRef :: a -> IO ()
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
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
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
47 markTree :: RefObj a => a -> IO ()
48 markTree root = marked root >>= (`unless` continue)
49 where continue = mark root >> refs root >>= mapM_ markTree