{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StrictData #-}
{-# OPTIONS_GHC -Wno-pattern-namespace-specifier #-}

-- |
-- Module      : Cek.Pykinos.Kont
-- Description : 32-frame unrolled Structure-of-Arrays continuation stack with O(1) CoW capture.
--
-- Eliminates per-step heap closure allocation by packing 32 continuation frames
-- into a 320-byte (5 cache-line) 'MutableByteArray' paired with two pointer lanes.
--
-- === Structure-of-Arrays Continuation Design
--
-- In conventional CEK and Krivine machine implementations, every evaluation step
-- pushes a frame onto a singly-linked list of heap closures (e.g. @data Frame = ...@).
-- This incurs significant allocation overhead, GC pressure, and cache misses during
-- high-frequency interpreter loops.
--
-- 'KontStack' replaces the linked list of heap frames with an unrolled Structure-of-Arrays
-- (SoA) chain of 32-frame blocks ('KontBlock'):
--
--   * 'kbUnboxed': A 320-byte unboxed 'MutableByteArray' spanning exactly 5 cache lines:
--       * Bytes [  0 ..  31]: Block header (Int32[0] = cursor, Int32[1] = frozenCursor).
--       * Bytes [ 32 ..  63]: Lane 0 — 32 x 1-byte 'FrameTag' opcodes.
--       * Bytes [ 64 .. 191]: Lane 1 — 32 x 4-byte 'Int32' integer fields (@intA@).
--       * Bytes [192 .. 319]: Lane 2 — 32 x 4-byte 'Int32' integer fields (@intB@).
--   * 'kbPtrA': A 32-slot 'SmallMutableArray' holding primary boxed term or record pointers.
--   * 'kbPtrB': A 32-slot 'SmallMutableArray' holding secondary boxed environment or argument pointers.
--
-- === O(1) Copy-on-Write Continuation Capture
--
-- First-class continuation capture (such as Scheme's @call/cc@ and Mercury's choice-point
-- backtracking) is achieved in strictly $O(1)$ time without copying the stack:
--
--   1. 'captureKontSoA' records the current block and cursor in 'CapturedKont' and freezes
--      the block by updating its @frozenCursor@.
--   2. Future pushes onto a frozen block perform a lazy copy-on-write clone of the active
--      prefix ('cloneBlockPrefix') only when modifying frozen slots.
--   3. Unfrozen pushes and pops operate in place with zero heap allocations.
module Cek.Pykinos.Kont
  ( -- * Continuation Frame Opcodes
    FrameTag(..)
  , pattern FT_UpdateWHNF
  , pattern FT_App
  , pattern FT_Proj
  , pattern FT_MergeL
  , pattern FT_MergeR
  , pattern FT_StartQuote
  , pattern FT_UpdateNF
  , pattern FT_QuoteBinder
  , pattern FT_BuildBinder
  , pattern FT_QuoteRecord
  , pattern FT_QuoteSpine
  , pattern FT_BuildElim
  , pattern FT_PureDissect

    -- * Block and Stack Structures
  , KontBlock(..)
  , KontStack(..)
  , CapturedKont(..)

    -- * Stack Lifecycle and Operations
  , newKontStack
  , pushFrameSoA
  , popFrameSoA
  , captureKontSoA
  , restoreKontSoA
  ) where

import Control.Monad (when)
import Control.Monad.ST (ST)
import Data.Int (Int32)
import Data.Primitive.ByteArray
  ( MutableByteArray
  , copyMutableByteArray
  , newByteArray
  , readByteArray
  , writeByteArray
  )
import Data.Primitive.SmallArray
  ( SmallMutableArray
  , copySmallMutableArray
  , newSmallArray
  , readSmallArray
  , writeSmallArray
  )
import Data.Word (Word8)
import GHC.Exts (Any, unsafeCoerce#)

-- | Unboxed 1-byte continuation frame opcode stored in Lane 0 of 'KontBlock'.
newtype FrameTag = FrameTag { FrameTag -> Word8
unFrameTag :: Word8 }
  deriving (FrameTag -> FrameTag -> Bool
(FrameTag -> FrameTag -> Bool)
-> (FrameTag -> FrameTag -> Bool) -> Eq FrameTag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FrameTag -> FrameTag -> Bool
== :: FrameTag -> FrameTag -> Bool
$c/= :: FrameTag -> FrameTag -> Bool
/= :: FrameTag -> FrameTag -> Bool
Eq, Eq FrameTag
Eq FrameTag =>
(FrameTag -> FrameTag -> Ordering)
-> (FrameTag -> FrameTag -> Bool)
-> (FrameTag -> FrameTag -> Bool)
-> (FrameTag -> FrameTag -> Bool)
-> (FrameTag -> FrameTag -> Bool)
-> (FrameTag -> FrameTag -> FrameTag)
-> (FrameTag -> FrameTag -> FrameTag)
-> Ord FrameTag
FrameTag -> FrameTag -> Bool
FrameTag -> FrameTag -> Ordering
FrameTag -> FrameTag -> FrameTag
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: FrameTag -> FrameTag -> Ordering
compare :: FrameTag -> FrameTag -> Ordering
$c< :: FrameTag -> FrameTag -> Bool
< :: FrameTag -> FrameTag -> Bool
$c<= :: FrameTag -> FrameTag -> Bool
<= :: FrameTag -> FrameTag -> Bool
$c> :: FrameTag -> FrameTag -> Bool
> :: FrameTag -> FrameTag -> Bool
$c>= :: FrameTag -> FrameTag -> Bool
>= :: FrameTag -> FrameTag -> Bool
$cmax :: FrameTag -> FrameTag -> FrameTag
max :: FrameTag -> FrameTag -> FrameTag
$cmin :: FrameTag -> FrameTag -> FrameTag
min :: FrameTag -> FrameTag -> FrameTag
Ord, Int -> FrameTag -> ShowS
[FrameTag] -> ShowS
FrameTag -> String
(Int -> FrameTag -> ShowS)
-> (FrameTag -> String) -> ([FrameTag] -> ShowS) -> Show FrameTag
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FrameTag -> ShowS
showsPrec :: Int -> FrameTag -> ShowS
$cshow :: FrameTag -> String
show :: FrameTag -> String
$cshowList :: [FrameTag] -> ShowS
showList :: [FrameTag] -> ShowS
Show)

-- | Frame: Overwrite a lazy thunk address in the store with the evaluated WHNF value.
pattern FT_UpdateWHNF  :: FrameTag
pattern $bFT_UpdateWHNF :: FrameTag
$mFT_UpdateWHNF :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_UpdateWHNF  = FrameTag 0

-- | Frame: Apply evaluated function to pending unevaluated argument address.
pattern FT_App         :: FrameTag
pattern $bFT_App :: FrameTag
$mFT_App :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_App         = FrameTag 1

-- | Frame: Project a field from an evaluated record using its slot offset.
pattern FT_Proj        :: FrameTag
pattern $bFT_Proj :: FrameTag
$mFT_Proj :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_Proj        = FrameTag 2

-- | Frame: Merge left operand of a record union (@//@) while waiting on the right operand.
pattern FT_MergeL      :: FrameTag
pattern $bFT_MergeL :: FrameTag
$mFT_MergeL :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_MergeL      = FrameTag 3

-- | Frame: Merge right operand of a record union (@//@) with evaluated left operand.
pattern FT_MergeR      :: FrameTag
pattern $bFT_MergeR :: FrameTag
$mFT_MergeR :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_MergeR      = FrameTag 4

-- | Frame: Enter NbE quote phase to read back a value into a normal-form DAG.
pattern FT_StartQuote  :: FrameTag
pattern $bFT_StartQuote :: FrameTag
$mFT_StartQuote :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_StartQuote  = FrameTag 5

-- | Frame: Update a thunk's memoized normal form in Lane 1 of the store arena.
pattern FT_UpdateNF    :: FrameTag
pattern $bFT_UpdateNF :: FrameTag
$mFT_UpdateNF :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_UpdateNF    = FrameTag 6

-- | Frame: Read back a function abstraction by extending the neutral environment.
pattern FT_QuoteBinder :: FrameTag
pattern $bFT_QuoteBinder :: FrameTag
$mFT_QuoteBinder :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_QuoteBinder = FrameTag 7

-- | Frame: Reconstruct a binder term after its body has been normalized.
pattern FT_BuildBinder :: FrameTag
pattern $bFT_BuildBinder :: FrameTag
$mFT_BuildBinder :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_BuildBinder = FrameTag 8

-- | Frame: Normalize fields of a flat record in sequence.
pattern FT_QuoteRecord :: FrameTag
pattern $bFT_QuoteRecord :: FrameTag
$mFT_QuoteRecord :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_QuoteRecord = FrameTag 9

-- | Frame: Read back arguments in an elimination spine.
pattern FT_QuoteSpine  :: FrameTag
pattern $bFT_QuoteSpine :: FrameTag
$mFT_QuoteSpine :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_QuoteSpine  = FrameTag 10

-- | Frame: Reconstruct an applied neutral term from normalized arguments.
pattern FT_BuildElim   :: FrameTag
pattern $bFT_BuildElim :: FrameTag
$mFT_BuildElim :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_BuildElim   = FrameTag 11

-- | Frame: Generic polynomial dissection frame driving generic AST traversal.
pattern FT_PureDissect :: FrameTag
pattern $bFT_PureDissect :: FrameTag
$mFT_PureDissect :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_PureDissect = FrameTag 12

-- | A 32-frame unrolled Structure-of-Arrays block.
--
-- Layout inside the 320-byte 'kbUnboxed' 'MutableByteArray':
--   * Bytes [  0 ..  31]: Header (Int32[0] = cursor, Int32[1] = frozenCursor)
--   * Bytes [ 32 ..  63]: Lane 0 — 32 x Word8  FrameTag opcodes
--   * Bytes [ 64 .. 191]: Lane 1 — 32 x Int32  IntA (Int32 indices 16 .. 47)
--   * Bytes [192 .. 319]: Lane 2 — 32 x Int32  IntB (Int32 indices 48 .. 79)
data KontBlock s = KontBlock
  { forall s. KontBlock s -> MutableByteArray s
kbUnboxed   :: !(MutableByteArray s)
    -- ^ Unboxed memory holding header, frame tags, and auxiliary integer parameters.
  , forall s. KontBlock s -> SmallMutableArray s Any
kbPtrA      :: !(SmallMutableArray s Any)
    -- ^ Primary pointer lane for closures, terms, or environments.
  , forall s. KontBlock s -> SmallMutableArray s Any
kbPtrB      :: !(SmallMutableArray s Any)
    -- ^ Secondary pointer lane for arguments or continuation records.
  , forall s. KontBlock s -> Maybe (KontBlock s)
kbParent    :: !(Maybe (KontBlock s))
    -- ^ Previous block in the call stack when stack exceeds 32 frames.
  , forall s. KontBlock s -> SmallMutableArray s (Maybe (KontBlock s))
kbFreeChild :: !(SmallMutableArray s (Maybe (KontBlock s)))
    -- ^ Cached reusable allocated child block to eliminate malloc churn during push/pop oscillation.
  }

-- | Mutable reference to the active top 'KontBlock' of the continuation stack.
newtype KontStack s = KontStack (SmallMutableArray s (KontBlock s))

-- | First-class O(1) continuation snapshot for @call/cc@ and backtracking choice points.
data CapturedKont s = CapturedKont
  { forall s. CapturedKont s -> KontBlock s
ckTopBlock :: !(KontBlock s)
    -- ^ Top block at the moment of capture.
  , forall s. CapturedKont s -> Int
ckCursor   :: {-# UNPACK #-} !Int
    -- ^ Stack depth within the top block at capture time.
  }

-- | Allocate an empty 32-frame SoA block linked to 'mbParent'.
{-# INLINE allocKontBlock #-}
allocKontBlock :: Maybe (KontBlock s) -> ST s (KontBlock s)
allocKontBlock :: forall s. Maybe (KontBlock s) -> ST s (KontBlock s)
allocKontBlock !Maybe (KontBlock s)
mbParent = do
  mba  <- Int -> ST s (MutableByteArray (PrimState (ST s)))
forall (m :: * -> *).
PrimMonad m =>
Int -> m (MutableByteArray (PrimState m))
newByteArray Int
320
  writeByteArray mba 0 (0 :: Int32)
  writeByteArray mba 1 (0 :: Int32)
  ptrA <- newSmallArray 32 (unsafeCoerce# ())
  ptrB <- newSmallArray 32 (unsafeCoerce# ())
  free <- newSmallArray 1 Nothing
  pure (KontBlock mba ptrA ptrB mbParent free)

-- | Create a fresh 'KontStack' with one pre-allocated 32-frame block.
newKontStack :: ST s (KontStack s)
newKontStack :: forall s. ST s (KontStack s)
newKontStack = do
  b0  <- Maybe (KontBlock s) -> ST s (KontBlock s)
forall s. Maybe (KontBlock s) -> ST s (KontBlock s)
allocKontBlock Maybe (KontBlock s)
forall a. Maybe a
Nothing
  ref <- newSmallArray 1 b0
  pure (KontStack ref)

-- | Copy-on-Write prefix clone of slots @[0 .. copyLen - 1]@ when pushing onto
--   a block that has been frozen by 'captureKontSoA'.
cloneBlockPrefix :: KontBlock s -> Int -> ST s (KontBlock s)
cloneBlockPrefix :: forall s. KontBlock s -> Int -> ST s (KontBlock s)
cloneBlockPrefix KontBlock s
oldBlock !Int
copyLen = do
  fresh <- Maybe (KontBlock s) -> ST s (KontBlock s)
forall s. Maybe (KontBlock s) -> ST s (KontBlock s)
allocKontBlock (KontBlock s -> Maybe (KontBlock s)
forall s. KontBlock s -> Maybe (KontBlock s)
kbParent KontBlock s
oldBlock)
  copyMutableByteArray (kbUnboxed fresh) 0 (kbUnboxed oldBlock) 0 320
  writeByteArray (kbUnboxed fresh) 0 (fromIntegral copyLen :: Int32)
  writeByteArray (kbUnboxed fresh) 1 (0 :: Int32)
  copySmallMutableArray (kbPtrA fresh) 0 (kbPtrA oldBlock) 0 copyLen
  copySmallMutableArray (kbPtrB fresh) 0 (kbPtrB oldBlock) 0 copyLen
  pure fresh

-- | Push a continuation frame onto the stack in O(1) time.
--
-- Encodes tag, two unboxed integers, and two pointer lanes with zero heap allocations.
{-# INLINE pushFrameSoA #-}
pushFrameSoA
  :: KontStack s
  -> FrameTag
  -> Int32
  -> Int32
  -> Any
  -> Any
  -> ST s ()
pushFrameSoA :: forall s.
KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
pushFrameSoA (KontStack SmallMutableArray s (KontBlock s)
ref) !FrameTag
tag !Int32
intA !Int32
intB !Any
ptrA !Any
ptrB = do
  top <- SmallMutableArray (PrimState (ST s)) (KontBlock s)
-> Int -> ST s (KontBlock s)
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> m a
readSmallArray SmallMutableArray s (KontBlock s)
SmallMutableArray (PrimState (ST s)) (KontBlock s)
ref Int
0
  cur :: Int32 <- readByteArray (kbUnboxed top) 0
  frz :: Int32 <- readByteArray (kbUnboxed top) 1
  if cur < 32
    then do
      top' <- if cur < frz
                then do
                  c <- cloneBlockPrefix top (fromIntegral cur)
                  writeSmallArray ref 0 c
                  pure c
                else pure top
      let !slot = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
cur :: Int
          !mba  = KontBlock s -> MutableByteArray s
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock s
top'
      writeByteArray mba (32 + slot) (unFrameTag tag)
      writeByteArray mba (16 + slot) intA
      writeByteArray mba (48 + slot) intB
      writeSmallArray (kbPtrA top') slot ptrA
      writeSmallArray (kbPtrB top') slot ptrB
      writeByteArray mba 0 (cur + 1)
    else do
      mbChild <- readSmallArray (kbFreeChild top) 0
      child <- case mbChild of
        Just KontBlock s
c  -> do
          SmallMutableArray (PrimState (ST s)) (Maybe (KontBlock s))
-> Int -> Maybe (KontBlock s) -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray (KontBlock s -> SmallMutableArray s (Maybe (KontBlock s))
forall s. KontBlock s -> SmallMutableArray s (Maybe (KontBlock s))
kbFreeChild KontBlock s
top) Int
0 Maybe (KontBlock s)
forall a. Maybe a
Nothing
          MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray (KontBlock s -> MutableByteArray s
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock s
c) Int
0 (Int32
0 :: Int32)
          MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray (KontBlock s -> MutableByteArray s
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock s
c) Int
1 (Int32
0 :: Int32)
          KontBlock s -> ST s (KontBlock s)
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure KontBlock s
c
        Maybe (KontBlock s)
Nothing -> Maybe (KontBlock s) -> ST s (KontBlock s)
forall s. Maybe (KontBlock s) -> ST s (KontBlock s)
allocKontBlock (KontBlock s -> Maybe (KontBlock s)
forall a. a -> Maybe a
Just KontBlock s
top)
      writeSmallArray ref 0 child
      let !mba = KontBlock s -> MutableByteArray s
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock s
child
      writeByteArray mba 32 (unFrameTag tag)
      writeByteArray mba 16 intA
      writeByteArray mba 48 intB
      writeSmallArray (kbPtrA child) 0 ptrA
      writeSmallArray (kbPtrB child) 0 ptrB
      writeByteArray mba 0 (1 :: Int32)

-- | Pop the topmost continuation frame from the stack in O(1) time.
--
-- Clears pointer lanes on pop to avoid memory leaks across deep recursions.
{-# INLINE popFrameSoA #-}
popFrameSoA
  :: KontStack s
  -> ST s (Maybe (FrameTag, Int32, Int32, Any, Any))
popFrameSoA :: forall s.
KontStack s -> ST s (Maybe (FrameTag, Int32, Int32, Any, Any))
popFrameSoA (KontStack SmallMutableArray s (KontBlock s)
ref) = do
  top <- SmallMutableArray (PrimState (ST s)) (KontBlock s)
-> Int -> ST s (KontBlock s)
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> m a
readSmallArray SmallMutableArray s (KontBlock s)
SmallMutableArray (PrimState (ST s)) (KontBlock s)
ref Int
0
  cur :: Int32 <- readByteArray (kbUnboxed top) 0
  if cur > 0
    then do
      let !slot = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32
cur Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1) :: Int
      readAndRetract top slot
    else case kbParent top of
      Maybe (KontBlock s)
Nothing -> Maybe (FrameTag, Int32, Int32, Any, Any)
-> ST s (Maybe (FrameTag, Int32, Int32, Any, Any))
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (FrameTag, Int32, Int32, Any, Any)
forall a. Maybe a
Nothing
      Just KontBlock s
parent -> do
        SmallMutableArray (PrimState (ST s)) (Maybe (KontBlock s))
-> Int -> Maybe (KontBlock s) -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray (KontBlock s -> SmallMutableArray s (Maybe (KontBlock s))
forall s. KontBlock s -> SmallMutableArray s (Maybe (KontBlock s))
kbFreeChild KontBlock s
parent) Int
0 (KontBlock s -> Maybe (KontBlock s)
forall a. a -> Maybe a
Just KontBlock s
top)
        SmallMutableArray (PrimState (ST s)) (KontBlock s)
-> Int -> KontBlock s -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s (KontBlock s)
SmallMutableArray (PrimState (ST s)) (KontBlock s)
ref Int
0 KontBlock s
parent
        pCur :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray (KontBlock s -> MutableByteArray s
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock s
parent) Int
0
        if pCur > 0
          then do
            let !slot = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32
pCur Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1) :: Int
            readAndRetract parent slot
          else pure Nothing
  where
    readAndRetract :: KontBlock (PrimState m)
-> Int -> m (Maybe (FrameTag, b, c, Any, Any))
readAndRetract KontBlock (PrimState m)
blk !Int
slot = do
      let !mba :: MutableByteArray (PrimState m)
mba = KontBlock (PrimState m) -> MutableByteArray (PrimState m)
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock (PrimState m)
blk
      MutableByteArray (PrimState m) -> Int -> Int32 -> m ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray (PrimState m)
mba Int
0 (Int -> Int32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
slot :: Int32)
      !tag  <- Word8 -> FrameTag
FrameTag (Word8 -> FrameTag) -> m Word8 -> m FrameTag
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> MutableByteArray (PrimState m) -> Int -> m Word8
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray (PrimState m)
mba (Int
32 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slot)
      !intA <- readByteArray mba (16 + slot)
      !intB <- readByteArray mba (48 + slot)
      !ptrA <- readSmallArray (kbPtrA blk) slot
      !ptrB <- readSmallArray (kbPtrB blk) slot
      frz :: Int32 <- readByteArray mba 1
      when (fromIntegral slot >= frz) $ do
        writeSmallArray (kbPtrA blk) slot (unsafeCoerce# ())
        writeSmallArray (kbPtrB blk) slot (unsafeCoerce# ())
      pure (Just (tag, intA, intB, ptrA, ptrB))

-- | Capture the current continuation in O(1) by marking the active block chain frozen.
{-# INLINE captureKontSoA #-}
captureKontSoA :: KontStack s -> ST s (CapturedKont s)
captureKontSoA :: forall s. KontStack s -> ST s (CapturedKont s)
captureKontSoA (KontStack SmallMutableArray s (KontBlock s)
ref) = do
  top <- SmallMutableArray (PrimState (ST s)) (KontBlock s)
-> Int -> ST s (KontBlock s)
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> m a
readSmallArray SmallMutableArray s (KontBlock s)
SmallMutableArray (PrimState (ST s)) (KontBlock s)
ref Int
0
  cur :: Int32 <- readByteArray (kbUnboxed top) 0
  freezeChain top cur
  pure (CapturedKont top (fromIntegral cur))
  where
    freezeChain :: KontBlock s -> Int32 -> ST s ()
    freezeChain :: forall s. KontBlock s -> Int32 -> ST s ()
freezeChain !KontBlock s
blk !Int32
frzCursor = do
      existingFrz :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray (KontBlock s -> MutableByteArray s
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock s
blk) Int
1
      when (frzCursor > existingFrz) $
        writeByteArray (kbUnboxed blk) 1 frzCursor
      case kbParent blk of
        Maybe (KontBlock s)
Nothing -> () -> ST s ()
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Just KontBlock s
p  -> KontBlock s -> Int32 -> ST s ()
forall s. KontBlock s -> Int32 -> ST s ()
freezeChain KontBlock s
p Int32
32

-- | Restore a previously captured continuation snapshot in O(1) time.
{-# INLINE restoreKontSoA #-}
restoreKontSoA :: KontStack s -> CapturedKont s -> ST s ()
restoreKontSoA :: forall s. KontStack s -> CapturedKont s -> ST s ()
restoreKontSoA (KontStack SmallMutableArray s (KontBlock s)
ref) (CapturedKont KontBlock s
top Int
cur) = do
  SmallMutableArray (PrimState (ST s)) (KontBlock s)
-> Int -> KontBlock s -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s (KontBlock s)
SmallMutableArray (PrimState (ST s)) (KontBlock s)
ref Int
0 KontBlock s
top
  MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray (KontBlock s -> MutableByteArray s
forall s. KontBlock s -> MutableByteArray s
kbUnboxed KontBlock s
top) Int
0 (Int -> Int32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
cur :: Int32)