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

-- |
-- Module      : Cek.Examples.Mercury
-- Description : Prolog/Mercury relational unification and backtracking engine on KontStack.
--
-- Demonstrates how 'KontStack' (O(1) copy-on-write continuation capture) and
-- 'SoAStore' (monotonic cell allocation with WAM conditional trailing) support
-- nondeterministic relational search, deep term unification, and @semidet@ commits.
--
-- === Architecture: WAM Relational Search on SoA Structures
--
-- The Warren Abstract Machine (WAM) achieves high-speed execution of Prolog and Mercury
-- by pairing three distinct memory areas:
--
--   1. An allocation heap for terms: mapped onto the 4096-cell chunked 'SoAStore'.
--   2. A continuation stack for clause dispatch: mapped onto the unrolled 32-frame 'KontStack'.
--   3. An undo trail for unbinding variables during backtracking: stored in an unboxed
--      'MutableByteArray' ('leTrail').
--
-- === WAM Conditional Trailing Invariant
--
-- When binding an unbound logic variable at cell @varAddr@ to a target term at @targetAddr@:
--
--   * If @varAddr < heapWatermark@ (where @heapWatermark@ is the store allocation cursor at
--     the most recent choice point), the variable was allocated /before/ the choice point
--     and must be recorded on the trail ('leTrail') so it can be reset to 'CT_Unbound'
--     upon failure.
--   * If @varAddr >= heapWatermark@, the variable was created /within/ the current alternative.
--     Backtracking simply resets the store allocation pointer, so trailing is bypassed.
--
-- === Delimited Commits and Choice-Point Pruning
--
-- Mercury's @semidet@ deterministic commits (or Prolog cuts @!@) prune choice points.
-- In 'solveMercury', cuts simply reset the choice point counter @cpCursor@ to the saved
-- watermark, instantly reclaiming all intermediate choice point states.
--
-- > **Demonstrative Reference Implementation**: This package is an educational
-- > and demonstrative reference implementation showcasing relational unification,
-- > WAM conditional trailing, and nondeterministic search over KontStack choice points.
-- > It is provided primarily as an executable architectural example within the @cek@
-- > ecosystem documentation.
--
module Cek.Mercury
  ( -- * Relational AST and Goals
    LogicTerm(..)
  , Goal(..)

    -- * WAM Engine State
  , LogicEngine(..)

    -- * Continuation Frame Tags
  , pattern FT_ConjR
  , pattern FT_CommitCut
  , pattern FT_UnifyArgs

    -- * Engine Lifecycle and Solver
  , newLogicEngine
  , solveMercury
  ) where

import Control.Monad (when)
import Control.Monad.ST (ST, runST)
import Data.Bits (shiftR, (.&.))
import Data.Int (Int32)
import Data.Primitive.ByteArray
  ( MutableByteArray
  , newByteArray
  , readByteArray
  , writeByteArray
  )
import Data.Primitive.SmallArray
  ( SmallArray
  , SmallMutableArray
  , indexSmallArray
  , newSmallArray
  , readSmallArray
  , sizeofSmallArray
  , smallArrayFromList
  , writeSmallArray
  )
import Data.Word (Word32)
import GHC.Exts (unsafeCoerce#)

import Cek.Pykinos.Kont
  ( CapturedKont(..)
  , FrameTag(..)
  , KontBlock
  , KontStack
  , captureKontSoA
  , newKontStack
  , popFrameSoA
  , pushFrameSoA
  , restoreKontSoA
  )
import Cek.Pykinos.Store
  ( CellTag(..)
  , SoAStore(..)
  , StoreChunk(..)
  , acquireSlot
  , allocWLitSoA
  , newSoAStore
  , pattern CT_Thunk
  , pattern CT_Unbound
  , pattern CT_WLit
  , pattern CT_WRecord
  , readCellPhaseSoA
  , unCellTag
  )

-- | Frame tag for evaluating the right-hand conjunct @g2@ after @g1@ succeeds.
pattern FT_ConjR     :: FrameTag
pattern $bFT_ConjR :: FrameTag
$mFT_ConjR :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_ConjR     = FrameTag 20

-- | Frame tag for committing a @once@ / cut block by pruning choice points.
pattern FT_CommitCut :: FrameTag
pattern $bFT_CommitCut :: FrameTag
$mFT_CommitCut :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_CommitCut = FrameTag 21

-- | Frame tag for continuing deep unification of remaining compound functor arguments.
pattern FT_UnifyArgs :: FrameTag
pattern $bFT_UnifyArgs :: FrameTag
$mFT_UnifyArgs :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_UnifyArgs = FrameTag 22

-- | First-order logic terms (variables, unboxed integer constants, and compound functors).
data LogicTerm
  = LVar !Int
    -- ^ Logic variable reference resolved through the local lexical environment.
  | LLit !Int32
    -- ^ 32-bit signed integer literal constant.
  | LFun !Word32 !(SmallArray LogicTerm)
    -- ^ Compound functor term @f(t0, t1, ...)@ with symbol ID and argument array.
  deriving (LogicTerm -> LogicTerm -> Bool
(LogicTerm -> LogicTerm -> Bool)
-> (LogicTerm -> LogicTerm -> Bool) -> Eq LogicTerm
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LogicTerm -> LogicTerm -> Bool
== :: LogicTerm -> LogicTerm -> Bool
$c/= :: LogicTerm -> LogicTerm -> Bool
/= :: LogicTerm -> LogicTerm -> Bool
Eq, Int -> LogicTerm -> ShowS
[LogicTerm] -> ShowS
LogicTerm -> String
(Int -> LogicTerm -> ShowS)
-> (LogicTerm -> String)
-> ([LogicTerm] -> ShowS)
-> Show LogicTerm
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LogicTerm -> ShowS
showsPrec :: Int -> LogicTerm -> ShowS
$cshow :: LogicTerm -> String
show :: LogicTerm -> String
$cshowList :: [LogicTerm] -> ShowS
showList :: [LogicTerm] -> ShowS
Show)

-- | Relational goal calculus supporting conjunction, disjunction, fresh variables, and commits.
data Goal
  = GSuccess
    -- ^ Trivial success goal (@true@ in Prolog).
  | GFail
    -- ^ Trivial failure goal that immediately triggers backtracking.
  | GUnify !LogicTerm !LogicTerm
    -- ^ Bidirectional Robinson unification between two terms @t1 = t2@.
  | GFresh !Goal
    -- ^ Fresh logic variable binder introducing a new unbound cell in 'SoAStore'.
  | GConj  !Goal !Goal
    -- ^ Logical conjunction @(g1 , g2)@ evaluated left-to-right.
  | GDisj  ![Goal]
    -- ^ Nondeterministic disjunction @(g1 ; g2 ; ...)@ creating a choice point.
  | GOnce  !Goal
    -- ^ Prune choice points created within @g@ upon first successful solution (@once/1@).
  deriving (Goal -> Goal -> Bool
(Goal -> Goal -> Bool) -> (Goal -> Goal -> Bool) -> Eq Goal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Goal -> Goal -> Bool
== :: Goal -> Goal -> Bool
$c/= :: Goal -> Goal -> Bool
/= :: Goal -> Goal -> Bool
Eq, Int -> Goal -> ShowS
[Goal] -> ShowS
Goal -> String
(Int -> Goal -> ShowS)
-> (Goal -> String) -> ([Goal] -> ShowS) -> Show Goal
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Goal -> ShowS
showsPrec :: Int -> Goal -> ShowS
$cshow :: Goal -> String
show :: Goal -> String
$cshowList :: [Goal] -> ShowS
showList :: [Goal] -> ShowS
Show)

-- | Mutable WAM execution state combining 'SoAStore', 'KontStack', an unboxed trail,
--   and an unboxed choice-point watermark stack.
data LogicEngine s = LogicEngine
  { forall s. LogicEngine s -> SoAStore s
leStore     :: !(SoAStore s)
    -- ^ Term and variable allocation arena.
  , forall s. LogicEngine s -> KontStack s
leKont      :: !(KontStack s)
    -- ^ Small-step goal continuation stack.
  , forall s. LogicEngine s -> MutableByteArray s
leTrail     :: !(MutableByteArray s)
    -- ^ Unboxed array of trailed variable addresses to be reset on backtrack.
  , forall s. LogicEngine s -> MutableByteArray s
leCpUnboxed :: !(MutableByteArray s)
    -- ^ Unboxed choice-point table (kCur, storeNext, trailCur).
  , forall s. LogicEngine s -> SmallMutableArray s (KontBlock s)
leCpKontBlk :: !(SmallMutableArray s (KontBlock s))
    -- ^ Saved top continuation blocks for frozen choice points.
  , forall s. LogicEngine s -> SmallMutableArray s ([Goal], [Int32])
leCpAlts    :: !(SmallMutableArray s ([Goal], [Int32]))
    -- ^ Remaining alternative goals and environment frames per choice point.
  , forall s. LogicEngine s -> MutableByteArray s
leCounters  :: !(MutableByteArray s)
    -- ^ Engine registers: Int32[0] = trailCursor, Int32[1] = cpCursor, Int32[2] = heapWatermark
  }

-- | Initialize a fresh 'LogicEngine' with pre-allocated trail and choice-point slabs.
newLogicEngine :: ST s (LogicEngine s)
newLogicEngine :: forall s. ST s (LogicEngine s)
newLogicEngine = do
  leStore     <- ST s (SoAStore s)
forall s. ST s (SoAStore s)
newSoAStore
  leKont      <- newKontStack
  leTrail     <- newByteArray (16384 * 4)
  leCpUnboxed <- newByteArray (1024 * 16)
  leCpKontBlk <- newSmallArray 1024 (unsafeCoerce# ())
  leCpAlts    <- newSmallArray 1024 ([], [])
  leCounters  <- newByteArray 12
  writeByteArray leCounters 0 (0 :: Int32)
  writeByteArray leCounters 1 (0 :: Int32)
  writeByteArray leCounters 2 (0 :: Int32)
  pure LogicEngine{..}

-- | Allocate an unbound unification variable ('CT_Unbound') in 'SoAStore' with 0 pointer writes.
{-# INLINE allocUnboundVar #-}
allocUnboundVar :: SoAStore s -> ST s Int32
allocUnboundVar :: forall s. SoAStore s -> ST s Int32
allocUnboundVar SoAStore s
store = do
  (!addr, StoreChunk{..}, !slot) <- SoAStore s -> ST s (Int32, StoreChunk s, Int)
forall s. SoAStore s -> ST s (Int32, StoreChunk s, Int)
acquireSlot SoAStore s
store
  writeByteArray scUnboxed slot (unCellTag CT_Unbound)
  pure addr

-- | Dereference variable indirection chains ('CT_Thunk' -> targetAddr) in 'SoAStore'.
{-# INLINE derefLogicAddr #-}
derefLogicAddr :: SoAStore s -> Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
derefLogicAddr :: forall s.
SoAStore s
-> Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
derefLogicAddr SoAStore s
store !Int32
addr0 = Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
go Int32
addr0
  where
    go :: Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
go !Int32
addr = do
      (!tag, !aux, !chunk, !slot) <- SoAStore s -> Int32 -> ST s (CellTag, Int32, StoreChunk s, Int)
forall s.
SoAStore s -> Int32 -> ST s (CellTag, Int32, StoreChunk s, Int)
readCellPhaseSoA SoAStore s
store Int32
addr
      if tag == CT_Thunk
        then go aux
        else pure (addr, tag, aux, chunk, slot)

-- | Bind an unbound logic variable at 'varAddr' to 'targetAddr' using WAM conditional trailing.
{-# INLINE bindLogicVar #-}
bindLogicVar :: LogicEngine s -> Int32 -> Int32 -> ST s ()
bindLogicVar :: forall s. LogicEngine s -> Int32 -> Int32 -> ST s ()
bindLogicVar LogicEngine{MutableByteArray s
SmallMutableArray s ([Goal], [Int32])
SmallMutableArray s (KontBlock s)
KontStack s
SoAStore s
leTrail :: forall s. LogicEngine s -> MutableByteArray s
leStore :: forall s. LogicEngine s -> SoAStore s
leKont :: forall s. LogicEngine s -> KontStack s
leCpUnboxed :: forall s. LogicEngine s -> MutableByteArray s
leCpKontBlk :: forall s. LogicEngine s -> SmallMutableArray s (KontBlock s)
leCpAlts :: forall s. LogicEngine s -> SmallMutableArray s ([Goal], [Int32])
leCounters :: forall s. LogicEngine s -> MutableByteArray s
leStore :: SoAStore s
leKont :: KontStack s
leTrail :: MutableByteArray s
leCpUnboxed :: MutableByteArray s
leCpKontBlk :: SmallMutableArray s (KontBlock s)
leCpAlts :: SmallMutableArray s ([Goal], [Int32])
leCounters :: MutableByteArray s
..} !Int32
varAddr !Int32
targetAddr
  | Int32
varAddr Int32 -> Int32 -> Bool
forall a. Eq a => a -> a -> Bool
== Int32
targetAddr = () -> ST s ()
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  | Bool
otherwise = do
      let !ix :: Int
ix   = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
varAddr :: Int
          !slot :: Int
slot = Int
ix Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
0xFFF
      StoreChunk{..} <- SmallMutableArray (PrimState (ST s)) (StoreChunk s)
-> Int -> ST s (StoreChunk s)
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> m a
readSmallArray (SoAStore s -> SmallMutableArray s (StoreChunk s)
forall s. SoAStore s -> SmallMutableArray s (StoreChunk s)
ssChunks SoAStore s
leStore) (Int
ix Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`shiftR` Int
12)
      writeByteArray scUnboxed slot (unCellTag CT_Thunk)
      writeByteArray scUnboxed (5120 + slot) targetAddr
      watermark :: Int32 <- readByteArray leCounters 2
      when (varAddr < watermark) $ do
        tCur :: Int32 <- readByteArray leCounters 0
        writeByteArray leTrail (fromIntegral tCur) varAddr
        writeByteArray leCounters 0 (tCur + 1)

-- | Materialize a syntax 'LogicTerm' into a 'SoAStore' cell address.
instantiateTerm :: LogicEngine s -> [Int32] -> LogicTerm -> ST s Int32
instantiateTerm :: forall s. LogicEngine s -> [Int32] -> LogicTerm -> ST s Int32
instantiateTerm eng :: LogicEngine s
eng@LogicEngine{MutableByteArray s
SmallMutableArray s ([Goal], [Int32])
SmallMutableArray s (KontBlock s)
KontStack s
SoAStore s
leTrail :: forall s. LogicEngine s -> MutableByteArray s
leStore :: forall s. LogicEngine s -> SoAStore s
leKont :: forall s. LogicEngine s -> KontStack s
leCpUnboxed :: forall s. LogicEngine s -> MutableByteArray s
leCpKontBlk :: forall s. LogicEngine s -> SmallMutableArray s (KontBlock s)
leCpAlts :: forall s. LogicEngine s -> SmallMutableArray s ([Goal], [Int32])
leCounters :: forall s. LogicEngine s -> MutableByteArray s
leStore :: SoAStore s
leKont :: KontStack s
leTrail :: MutableByteArray s
leCpUnboxed :: MutableByteArray s
leCpKontBlk :: SmallMutableArray s (KontBlock s)
leCpAlts :: SmallMutableArray s ([Goal], [Int32])
leCounters :: MutableByteArray s
..} [Int32]
env = \case
  LVar Int
ix        -> Int32 -> ST s Int32
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Int32]
env [Int32] -> Int -> Int32
forall a. HasCallStack => [a] -> Int -> a
!! Int
ix)
  LLit Int32
n         -> SoAStore s -> Int32 -> ST s Int32
forall s. SoAStore s -> Int32 -> ST s Int32
allocWLitSoA SoAStore s
leStore Int32
n
  LFun Word32
fSym SmallArray LogicTerm
args -> do
    let !n :: Int
n = SmallArray LogicTerm -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray LogicTerm
args
    argAddrs <- (Int -> ST s Int32) -> [Int] -> ST s [Int32]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (\Int
i -> LogicEngine s -> [Int32] -> LogicTerm -> ST s Int32
forall s. LogicEngine s -> [Int32] -> LogicTerm -> ST s Int32
instantiateTerm LogicEngine s
eng [Int32]
env (SmallArray LogicTerm -> Int -> LogicTerm
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray LogicTerm
args Int
i)) [Int
0 .. Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
    (!addr, StoreChunk{..}, !slot) <- acquireSlot leStore
    writeByteArray scUnboxed slot (unCellTag CT_WRecord)
    writeByteArray scUnboxed (5120 + slot) (fromIntegral fSym :: Int32)
    writeSmallArray scPtrA slot (unsafeCoerce# (smallArrayFromList argAddrs))
    pure addr

-- | Execute a relational 'Goal' over @numQueryVars@ root variables and collect up to
--   @maxSolutions@ integer bindings per query variable across backtracking branches.
solveMercury :: Int -> Int -> Goal -> [[Maybe Int32]]
solveMercury :: Int -> Int -> Goal -> [[Maybe Int32]]
solveMercury !Int
maxSolutions !Int
numQueryVars Goal
rootGoal = (forall s. ST s [[Maybe Int32]]) -> [[Maybe Int32]]
forall a. (forall s. ST s a) -> a
runST ((forall s. ST s [[Maybe Int32]]) -> [[Maybe Int32]])
-> (forall s. ST s [[Maybe Int32]]) -> [[Maybe Int32]]
forall a b. (a -> b) -> a -> b
$ do
  eng@LogicEngine{..} <- ST s (LogicEngine s)
forall s. ST s (LogicEngine s)
newLogicEngine
  queryAddrs <- mapM (\Int
_ -> SoAStore s -> ST s Int32
forall s. SoAStore s -> ST s Int32
allocUnboundVar SoAStore s
leStore) [1 .. numQueryVars]
  let readQueryBinding !Int32
qAddr = do
        (!_a, !tag, !aux, !_chk, !_slot) <- SoAStore s
-> Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
forall s.
SoAStore s
-> Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
derefLogicAddr SoAStore s
leStore Int32
qAddr
        if tag == CT_WLit
          then pure (Just aux)
          else pure Nothing

      evalGoal !Goal
goal ![Int32]
env ![[Maybe Int32]]
accSols
        | [[Maybe Int32]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[Maybe Int32]]
accSols Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
maxSolutions = [[Maybe Int32]] -> ST s [[Maybe Int32]]
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([[Maybe Int32]] -> [[Maybe Int32]]
forall a. [a] -> [a]
reverse [[Maybe Int32]]
accSols)
        | Bool
otherwise = case Goal
goal of
            -- Success: proceed to the next pending continuation frame in KontStack
            Goal
GSuccess -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
continueSuccess [[Maybe Int32]]
accSols
            -- Failure: trigger choice-point restoration and trail unwinding
            Goal
GFail    -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
backtrack [[Maybe Int32]]
accSols

            -- Allocate fresh unbound unification variable and extend lexical scope
            GFresh Goal
body -> do
              vAddr <- SoAStore s -> ST s Int32
forall s. SoAStore s -> ST s Int32
allocUnboundVar SoAStore s
leStore
              evalGoal body (vAddr : env) accSols

            -- Conjunction: push right goal onto KontStack and evaluate left goal
            GConj Goal
g1 Goal
g2 -> do
              KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
forall s.
KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
pushFrameSoA KontStack s
leKont FrameTag
FT_ConjR Int32
0 Int32
0 (Goal -> Any
forall a b. a -> b
unsafeCoerce# Goal
g2) ([Int32] -> Any
forall a b. a -> b
unsafeCoerce# [Int32]
env)
              Goal -> [Int32] -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
evalGoal Goal
g1 [Int32]
env [[Maybe Int32]]
accSols

            -- Once / Cut: save current choice point watermark and commit on success
            GOnce Goal
g -> do
              cpCur :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCounters Int
1
              pushFrameSoA leKont FT_CommitCut cpCur 0 (unsafeCoerce# ()) (unsafeCoerce# ())
              evalGoal g env accSols

            -- Empty disjunction: no alternatives left; initiate backtrack
            GDisj []       -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
backtrack [[Maybe Int32]]
accSols
            -- Single disjunct: deterministic execution without creating a choice point
            GDisj [Goal
single] -> Goal -> [Int32] -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
evalGoal Goal
single [Int32]
env [[Maybe Int32]]
accSols
            -- Multiple disjuncts: freeze KontStack, record trail and store cursors
            GDisj (Goal
firstAlt : [Goal]
restAlts) -> do
              CapturedKont topBlk kCur <- KontStack s -> ST s (CapturedKont s)
forall s. KontStack s -> ST s (CapturedKont s)
captureKontSoA KontStack s
leKont
              storeNext :: Int32 <- readByteArray (ssState leStore) 0
              trailCur  :: Int32 <- readByteArray leCounters 0
              cpCur     :: Int32 <- readByteArray leCounters 1
              let !cpIx = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
cpCur :: Int
                  !base = Int
cpIx Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
4
              -- Save choice point registers into unboxed table:
              writeByteArray leCpUnboxed (base + 0) (fromIntegral kCur :: Int32)
              writeByteArray leCpUnboxed (base + 1) storeNext
              writeByteArray leCpUnboxed (base + 2) trailCur
              -- Save frozen continuation block and remaining alternatives:
              writeSmallArray leCpKontBlk cpIx topBlk
              writeSmallArray leCpAlts    cpIx (restAlts, env)
              writeByteArray leCounters 1 (cpCur + 1)
              writeByteArray leCounters 2 storeNext
              evalGoal firstAlt env accSols

            -- Robinson first-order unification between instantiated terms
            GUnify LogicTerm
t1 LogicTerm
t2 -> do
              a1 <- LogicEngine s -> [Int32] -> LogicTerm -> ST s Int32
forall s. LogicEngine s -> [Int32] -> LogicTerm -> ST s Int32
instantiateTerm LogicEngine s
eng [Int32]
env LogicTerm
t1
              a2 <- instantiateTerm eng env t2
              unifyAddrs a1 a2 accSols

      unifyAddrs !Int32
u1 !Int32
u2 ![[Maybe Int32]]
accSols = do
        (!a1, !tag1, !aux1, !chk1, !slot1) <- SoAStore s
-> Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
forall s.
SoAStore s
-> Int32 -> ST s (Int32, CellTag, Int32, StoreChunk s, Int)
derefLogicAddr SoAStore s
leStore Int32
u1
        (!a2, !tag2, !aux2, !chk2, !slot2) <- derefLogicAddr leStore u2
        -- Identical cell addresses unify trivially without memory writes
        if a1 == a2
          then continueSuccess accSols
          else case (tag1, tag2) of
            -- Unbound variable on left: bind to right address with trailing
            (CellTag
CT_Unbound, CellTag
_) -> LogicEngine s -> Int32 -> Int32 -> ST s ()
forall s. LogicEngine s -> Int32 -> Int32 -> ST s ()
bindLogicVar LogicEngine s
eng Int32
a1 Int32
a2 ST s () -> ST s [[Maybe Int32]] -> ST s [[Maybe Int32]]
forall a b. ST s a -> ST s b -> ST s b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [[Maybe Int32]] -> ST s [[Maybe Int32]]
continueSuccess [[Maybe Int32]]
accSols
            -- Unbound variable on right: bind to left address with trailing
            (CellTag
_, CellTag
CT_Unbound) -> LogicEngine s -> Int32 -> Int32 -> ST s ()
forall s. LogicEngine s -> Int32 -> Int32 -> ST s ()
bindLogicVar LogicEngine s
eng Int32
a2 Int32
a1 ST s () -> ST s [[Maybe Int32]] -> ST s [[Maybe Int32]]
forall a b. ST s a -> ST s b -> ST s b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [[Maybe Int32]] -> ST s [[Maybe Int32]]
continueSuccess [[Maybe Int32]]
accSols
            -- Primitive integer literals: test equality of unboxed AuxInt values
            (CellTag
CT_WLit, CellTag
CT_WLit)
              | Int32
aux1 Int32 -> Int32 -> Bool
forall a. Eq a => a -> a -> Bool
== Int32
aux2 -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
continueSuccess [[Maybe Int32]]
accSols
              | Bool
otherwise    -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
backtrack [[Maybe Int32]]
accSols
            -- Compound record/functor structures: compare symbol IDs and unify arguments
            (CellTag
CT_WRecord, CellTag
CT_WRecord)
              | Int32
aux1 Int32 -> Int32 -> Bool
forall a. Eq a => a -> a -> Bool
== Int32
aux2 -> do
                  arr1 :: SmallArray Int32 <- Any -> SmallArray Int32
forall a b. a -> b
unsafeCoerce# (Any -> SmallArray Int32) -> ST s Any -> ST s (SmallArray Int32)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SmallMutableArray (PrimState (ST s)) Any -> Int -> ST s Any
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> m a
readSmallArray (StoreChunk s -> SmallMutableArray s Any
forall s. StoreChunk s -> SmallMutableArray s Any
scPtrA StoreChunk s
chk1) Int
slot1
                  arr2 :: SmallArray Int32 <- unsafeCoerce# <$> readSmallArray (scPtrA chk2) slot2
                  let !n1 = SmallArray Int32 -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray Int32
arr1
                      !n2 = SmallArray Int32 -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray Int32
arr2
                  if n1 /= n2
                    then backtrack accSols
                    else if n1 == 0
                      then continueSuccess accSols
                      else do
                        -- Push remaining arguments onto KontStack for incremental verification:
                        when (n1 > 1) $
                          pushFrameSoA leKont FT_UnifyArgs 1 (fromIntegral n1)
                            (unsafeCoerce# arr1) (unsafeCoerce# arr2)
                        unifyAddrs (indexSmallArray arr1 0) (indexSmallArray arr2 0) accSols
            (CellTag, CellTag)
_ -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
backtrack [[Maybe Int32]]
accSols

      continueSuccess ![[Maybe Int32]]
accSols = do
        mbFrame <- KontStack s -> ST s (Maybe (FrameTag, Int32, Int32, Any, Any))
forall s.
KontStack s -> ST s (Maybe (FrameTag, Int32, Int32, Any, Any))
popFrameSoA KontStack s
leKont
        case mbFrame of
          -- No more frames on KontStack: an entire relational solution was derived
          Maybe (FrameTag, Int32, Int32, Any, Any)
Nothing -> do
            sol <- (Int32 -> ST s (Maybe Int32)) -> [Int32] -> ST s [Maybe Int32]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Int32 -> ST s (Maybe Int32)
readQueryBinding [Int32]
queryAddrs
            let !accSols' = [Maybe Int32]
sol [Maybe Int32] -> [[Maybe Int32]] -> [[Maybe Int32]]
forall a. a -> [a] -> [a]
: [[Maybe Int32]]
accSols
            if length accSols' >= maxSolutions
              then pure (reverse accSols')
              else backtrack accSols'

          Just (FrameTag
ft, Int32
intA, Int32
intB, Any
ptrA, Any
ptrB)
            -- Resume right-hand conjunct
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_ConjR -> do
                let !g2 :: Goal
g2  = Any -> Goal
forall a b. a -> b
unsafeCoerce# Any
ptrA :: Goal
                    !env :: [Int32]
env = Any -> [Int32]
forall a b. a -> b
unsafeCoerce# Any
ptrB :: [Int32]
                Goal -> [Int32] -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
evalGoal Goal
g2 [Int32]
env [[Maybe Int32]]
accSols
            -- Commit cut: prune choice points older than the cut watermark
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_CommitCut -> do
                MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCounters Int
1 Int32
intA
                if Int32
intA Int32 -> Int32 -> Bool
forall a. Ord a => a -> a -> Bool
> Int32
0
                  then do
                    prevWm :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCpUnboxed (Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32
intA Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1) Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
4 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
                    writeByteArray leCounters 2 prevWm
                  else MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCounters Int
2 (Int32
0 :: Int32)
                [[Maybe Int32]] -> ST s [[Maybe Int32]]
continueSuccess [[Maybe Int32]]
accSols
            -- Resume argument unification
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_UnifyArgs -> do
                let !cur :: Int
cur  = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
intA :: Int
                    !len :: Int
len  = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
intB :: Int
                    !arr1 :: SmallArray Int32
arr1 = Any -> SmallArray Int32
forall a b. a -> b
unsafeCoerce# Any
ptrA :: SmallArray Int32
                    !arr2 :: SmallArray Int32
arr2 = Any -> SmallArray Int32
forall a b. a -> b
unsafeCoerce# Any
ptrB :: SmallArray Int32
                Bool -> ST s () -> ST s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
cur Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
len) (ST s () -> ST s ()) -> ST s () -> ST s ()
forall a b. (a -> b) -> a -> b
$
                  KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
forall s.
KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
pushFrameSoA KontStack s
leKont FrameTag
FT_UnifyArgs (Int32
intA Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
+ Int32
1) Int32
intB Any
ptrA Any
ptrB
                Int32 -> Int32 -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
unifyAddrs (SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
arr1 Int
cur) (SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
arr2 Int
cur) [[Maybe Int32]]
accSols
            | Bool
otherwise -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([[Maybe Int32]] -> [[Maybe Int32]]
forall a. [a] -> [a]
reverse [[Maybe Int32]]
accSols)

      backtrack ![[Maybe Int32]]
accSols = do
        cpCur :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCounters Int
1
        -- If no choice points remain, all search branches have been exhausted
        if cpCur <= 0
          then pure (reverse accSols)
          else do
            let !cpIx = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32
cpCur Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1) :: Int
                !base = Int
cpIx Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
4
            !savedKCur      :: Int32 <- readByteArray leCpUnboxed (base + 0)
            !savedStoreNext :: Int32 <- readByteArray leCpUnboxed (base + 1)
            !savedTrailCur  :: Int32 <- readByteArray leCpUnboxed (base + 2)
            !savedKBlk      <- readSmallArray leCpKontBlk cpIx
            (!alts, !env)   <- readSmallArray leCpAlts cpIx

            -- 1. Unwind trailed variable bindings back to CT_Unbound
            curTrail :: Int32 <- readByteArray leCounters 0
            let unwindTrail !Int32
t
                  | Int32
t Int32 -> Int32 -> Bool
forall a. Ord a => a -> a -> Bool
<= Int32
savedTrailCur = () -> f ()
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
                  | Bool
otherwise = do
                      !trailedAddr :: Int32 <- MutableByteArray (PrimState f) -> Int -> f Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState f)
leTrail (Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32
t Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1))
                      let !ix   = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
trailedAddr :: Int
                          !slot = Int
ix Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
0xFFF
                      StoreChunk{..} <- readSmallArray (ssChunks leStore) (ix `shiftR` 12)
                      writeByteArray scUnboxed slot (unCellTag CT_Unbound)
                      unwindTrail (t - 1)
            unwindTrail curTrail
            writeByteArray leCounters 0 savedTrailCur

            -- 2. Reclaim all speculative SoAStore allocations in O(1)
            writeByteArray (ssState leStore) 0 savedStoreNext

            -- 3. Restore the 32-frame SoA KontStack in O(1)
            restoreKontSoA leKont (CapturedKont savedKBlk (fromIntegral savedKCur))

            -- 4. Advance or pop choice point
            case alts of
              [] -> do
                MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCounters Int
1 (Int32
cpCur Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1)
                [[Maybe Int32]] -> ST s [[Maybe Int32]]
backtrack [[Maybe Int32]]
accSols
              [Goal
lastAlt] -> do
                MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCounters Int
1 (Int32
cpCur Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1)
                if Int32
cpCur Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
1 Int32 -> Int32 -> Bool
forall a. Ord a => a -> a -> Bool
> Int32
0
                  then do
                    prevWm :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCpUnboxed (Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32
cpCur Int32 -> Int32 -> Int32
forall a. Num a => a -> a -> a
- Int32
2) Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
4 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
                    writeByteArray leCounters 2 prevWm
                  else MutableByteArray (PrimState (ST s)) -> Int -> Int32 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
leCounters Int
2 (Int32
0 :: Int32)
                Goal -> [Int32] -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
evalGoal Goal
lastAlt [Int32]
env [[Maybe Int32]]
accSols
              (Goal
nextAlt : [Goal]
moreAlts) -> do
                SmallMutableArray (PrimState (ST s)) ([Goal], [Int32])
-> Int -> ([Goal], [Int32]) -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s ([Goal], [Int32])
SmallMutableArray (PrimState (ST s)) ([Goal], [Int32])
leCpAlts Int
cpIx ([Goal]
moreAlts, [Int32]
env)
                Goal -> [Int32] -> [[Maybe Int32]] -> ST s [[Maybe Int32]]
evalGoal Goal
nextAlt [Int32]
env [[Maybe Int32]]
accSols

  evalGoal rootGoal queryAddrs []