1 {-# LANGUAGE MagicHash, BangPatterns #-}
7 import System.Environment
13 args <- map length `fmap` getArgs
15 (l ++ l2 ++ args) `deepseq` return ()
17 let x = l ++ l2 ++ args
19 putStrLn "ghc-heap-view-demo"
20 putStrLn "Here are a few different lists."
21 putStrLn $ "The first one, l, found at " ++ show (asBox l) ++ " is a module-level constant, and fully evaluated:"
22 getClosureData l >>= print
23 putStrLn $ "The second one, l2, found at " ++ show (asBox l2) ++ " is locally defined as l2 = 4:l. See how the cons-cell references l!"
24 getClosureData l2 >>= print
25 putStrLn $ "And here is the list args (" ++ show (asBox args) ++ ") that is static, but not known at compiletime, as it depends on the command line arguments:"
26 getClosureData args >>= print
27 putStrLn $ "And now we have, at " ++ show (asBox x) ++ ", the concatenation of them, but unevaluated. The thunk keeps a reference to l2 and args, but not l, as that is at a static address, unless you are running this in GHCi:"
28 getClosureData x >>= print
31 putStrLn "Now to some more closure types:"
32 let !(I# m) = length args + 42
33 let !(I# m') = length args + 23
34 let f = \x n -> take (I# m + I# x) n ++ args
36 putStrLn $ "The following value f (" ++ show (asBox f) ++ ") is a locally defined function that has args as a free variable, as well as an unboxed integer (42):"
37 getClosureData f >>= print
38 putStrLn "And the following is a thunk that applies f (also references here) to an unboxed value (23) and l2:"
39 getClosureData t >>= print
42 putStrLn "Here is the standard example for self reference:"
43 putStrLn "> let x = id (:) () x"
45 putStrLn $ "This is what x (" ++ show (asBox x) ++ ") looks like, at least without -O:"
46 getClosureData x >>= print
48 putStrLn $ "So it is unevaluated. Let us evaluate it using seq. Now we have, still at " ++ show (asBox x) ++ ":"
49 getClosureData x >>= print
50 IndClosure {indirectee = target} <- getClosureData x
51 putStrLn $ "The thunk was replaced by an indirection. If we look at the target, " ++ show target ++ ", we see that it is a newly created cons-cell referencing the original location of x:"
52 getHValueClosureData target >>= print
54 putStrLn $ "After running the garbage collector (performGC), we find that the address of x is now " ++ show (asBox x) ++ " and that the self-reference is without indirections:"
55 getClosureData x >>= print
58 recurse :: Int -> Box -> IO ()
60 where go i b = if i >= m then return () else do
61 putStrLn $ ind ++ show b
62 c <- getHValueClosureData b
63 putStrLn $ ind ++ show c
64 mapM_ (go (succ i)) (allPtrs c)
66 ind = concat $ replicate i " "