{-|
Module: Internal.Finalizer
Description: Make resource-safe wrappers for values, with finalizers

This module wrappers for values to which finalizers can safely be
attached, without worrying that they may be collected early. It is
useful when the natural thing to attach a finalizer to is a simple
datatype.

From the docs for the 'Weak' type:

> WARNING: weak pointers to ordinary non-primitive Haskell types
> are particularly fragile, because the compiler is free to optimise
> away or duplicate the underlying data structure. Therefore
> attempting to place a finalizer on an ordinary Haskell type may
> well result in the finalizer running earlier than you expected.
>
> [...]
>
> Finalizers can be used reliably for types that are created
> explicitly and have identity, such as IORef and MVar. [...]

So instead, we provide a 'Cell' type, which:

* Wraps simple value
* Can be created and read inside STM, and
* May safely have finalizers, using the 'addFinalizer' function in
  this module.
* Ensures that the finalizers will not be run before any transaction that
  reads data is complete.

Note that it is *not* safe to use the primitives from "Sys.Mem.Weak" to
add finalizers.

-}
{-# LANGUAGE NamedFieldPuns #-}
module Internal.Finalizer (Cell, get, newCell, addFinalizer) where

import Control.Concurrent.MVar (MVar, mkWeakMVar, newEmptyMVar)
import Control.Concurrent.STM
    (STM, TVar, atomically, modifyTVar', newTVar, readTVar)

-- | A cell, containing a value and possibly finalizers.
newtype Cell a
    = Cell (TVar (CellData a))
    deriving(Cell a -> Cell a -> Bool
(Cell a -> Cell a -> Bool)
-> (Cell a -> Cell a -> Bool) -> Eq (Cell a)
forall a. Cell a -> Cell a -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Cell a -> Cell a -> Bool
$c/= :: forall a. Cell a -> Cell a -> Bool
== :: Cell a -> Cell a -> Bool
$c== :: forall a. Cell a -> Cell a -> Bool
Eq)

-- The actual contents of a cell. This is wrapped in a 'TVar' to force accesses
-- to add the a reference the transaction log from which the finalizers are
-- reachable, thus preventing them from running before the completion of any
-- transaction that examines the value.
data CellData a = CellData
    { CellData a -> a
value      :: a
    -- ^ The value wrapped by the cell.

    , CellData a -> [MVar ()]
finalizers :: [MVar ()]
    -- ^ Experimentally, TVars appear not to be safe for finalizers, so
    -- instead we create MVars for the finalizers, and store them this
    -- list so that we maintain a reference to them.
    }
    deriving(CellData a -> CellData a -> Bool
(CellData a -> CellData a -> Bool)
-> (CellData a -> CellData a -> Bool) -> Eq (CellData a)
forall a. Eq a => CellData a -> CellData a -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: CellData a -> CellData a -> Bool
$c/= :: forall a. Eq a => CellData a -> CellData a -> Bool
== :: CellData a -> CellData a -> Bool
$c== :: forall a. Eq a => CellData a -> CellData a -> Bool
Eq)

-- | Get the value from a cell
get :: Cell a -> STM a
get :: Cell a -> STM a
get (Cell TVar (CellData a)
state) = CellData a -> a
forall a. CellData a -> a
value (CellData a -> a) -> STM (CellData a) -> STM a
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar (CellData a) -> STM (CellData a)
forall a. TVar a -> STM a
readTVar TVar (CellData a)
state

-- Create  a new cell, initially with no finalizers.
newCell :: a -> STM (Cell a)
newCell :: a -> STM (Cell a)
newCell a
value = TVar (CellData a) -> Cell a
forall a. TVar (CellData a) -> Cell a
Cell (TVar (CellData a) -> Cell a)
-> STM (TVar (CellData a)) -> STM (Cell a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CellData a -> STM (TVar (CellData a))
forall a. a -> STM (TVar a)
newTVar CellData :: forall a. a -> [MVar ()] -> CellData a
CellData { a
value :: a
value :: a
value, finalizers :: [MVar ()]
finalizers = [] }

-- Add a new finalizer to the cell. Cells may have many finalizers
-- attached.
addFinalizer :: Cell a -> STM () -> IO ()
addFinalizer :: Cell a -> STM () -> IO ()
addFinalizer (Cell TVar (CellData a)
stateVar) STM ()
fin = do
    MVar ()
mvar <- IO (MVar ())
forall a. IO (MVar a)
newEmptyMVar
    Weak (MVar ())
_ <- MVar () -> IO () -> IO (Weak (MVar ()))
forall a. MVar a -> IO () -> IO (Weak (MVar a))
mkWeakMVar MVar ()
mvar (IO () -> IO (Weak (MVar ()))) -> IO () -> IO (Weak (MVar ()))
forall a b. (a -> b) -> a -> b
$ STM () -> IO ()
forall a. STM a -> IO a
atomically STM ()
fin
    STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TVar (CellData a) -> (CellData a -> CellData a) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' TVar (CellData a)
stateVar ((CellData a -> CellData a) -> STM ())
-> (CellData a -> CellData a) -> STM ()
forall a b. (a -> b) -> a -> b
$ \state :: CellData a
state@CellData{[MVar ()]
finalizers :: [MVar ()]
finalizers :: forall a. CellData a -> [MVar ()]
finalizers} ->
        CellData a
state { finalizers :: [MVar ()]
finalizers = MVar ()
mvar MVar () -> [MVar ()] -> [MVar ()]
forall a. a -> [a] -> [a]
: [MVar ()]
finalizers }