summaryrefslogtreecommitdiff
path: root/libraries/ghc-heap/tests/heap_weak.hs
blob: 47784f22979208b43de0bfe74c9d294228a6c4d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-- The simplifier changes the shapes of closures that we expect.
{-# OPTIONS_GHC -O0 #-}
{-# LANGUAGE MagicHash, UnboxedTuples, LambdaCase #-}

import GHC.Exts.Heap
import GHC.IORef
import GHC.Weak
import System.Mem

main :: IO ()
main = do
    key <- newIORef "key"
    let val = "val"
    wk@(Weak w) <- mkWeak key val Nothing

    getClosureData w >>= \case
      WeakClosure{} -> putStrLn "OK"
      _ -> error "Weak is not a WeakClosure"

    deRefWeak wk >>= \case
      Nothing -> error "Weak dead when key alive"
      Just _ -> pure ()

    readIORef key >>= putStrLn

    performMajorGC

    deRefWeak wk >>= \case
      Nothing -> pure ()
      Just _ -> error "Weak alive when key dead"

    getClosureData w >>= \case
      ConstrClosure{} -> putStrLn "OK"
      _ -> error "dead Weak should be a ConstrClosure"