{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StrictData #-}

-- |
-- Module      : Cek.Polytropos.Dissect
-- Description : Universal O(1) array cursor dissection over Polytropos.Core.Rep.
--
-- Replaces O(N) nested 'GHC.Generics' sum/product continuation frames with a
-- single flat cursor over 'Polytropos.Core.Rep'.
--
-- === The Problem of Generic Dissection Overhead
--
-- Standard polynomial functor dissection via GHC's 'Generic1' introduces deeply
-- nested tree structures of binary sums (':+:') and binary products (':*:').
-- For a constructor with \(k\) arguments, the generic representation requires
-- \(k\) nested 'Prod2' frame allocations. Each frame allocation costs multiple
-- heap words and pointer traversals.
--
-- === Flat Representation Dissection
--
-- In 'Polytropos.Core', every algebraic data type or record constructor is represented
-- as a single contiguous array ('Rep'):
--
-- @
-- data Rep (f :: Type -> Type) a = Rep {-# UNPACK #-} !Word !(SmallArray Any)
-- @
--
-- 'PolyDissect' exploits this contiguous representation by turning functor dissection
-- into a single integer cursor ('pdCursor') sliding across a 'SmallArray':
--
--   * Slots @[0 .. pdCursor - 1]@: Contain evaluated Clowns (@c@).
--   * Slot @pdCursor@: The active evaluation hole currently being reduced.
--   * Slots @[pdCursor + 1 .. n - 1]@: Contain unevaluated Jokers (@j@).
--
-- This reduces frame allocation to an unboxed cursor increment, achieving $O(1)$
-- stepping with optimal cache locality and zero tree-pointer chasing.
module Cek.Polytropos.Dissect
  ( -- * Flat Dissection Representation
    PolyDissect(..)

    -- * Dissection Stepping Operations
  , polyStepIn
  , polyStepNext
  ) where

import Data.Bifunctor (Bifunctor(..))
import Data.Primitive.SmallArray
  ( SmallArray
  , indexSmallArray
  , runSmallArray
  , sizeofSmallArray
  , thawSmallArray
  , writeSmallArray
  )
import GHC.Exts (Any, unsafeCoerce#)
import Polytropos.Core (Rep(..))

-- | Universal dissection state for any 'Polytropos.Core.Rep' syntax node.
--
-- Invariant: in 'pdSlots', indices @[0 .. pdCursor - 1]@ hold evaluated
-- Clowns @c@, index 'pdCursor' is the active hole, and indices
-- @[pdCursor + 1 .. n - 1]@ hold unevaluated Jokers @j@.
data PolyDissect c j = PolyDissect
  { forall c j. PolyDissect c j -> Word
pdTag    :: {-# UNPACK #-} !Word
    -- ^ The constructor tag index within the source sum/data type.
  , forall c j. PolyDissect c j -> Int
pdCursor :: {-# UNPACK #-} !Int
    -- ^ Zero-based offset of the currently active evaluation hole.
  , forall c j. PolyDissect c j -> SmallArray Any
pdSlots  :: !(SmallArray Any)
    -- ^ Array of slots partitioned by 'pdCursor' into Clowns and Jokers.
  }

-- | Functor mapping over the unevaluated Jokers to the right of 'pdCursor'.
instance Functor (PolyDissect c) where
  fmap :: forall a b. (a -> b) -> PolyDissect c a -> PolyDissect c b
fmap a -> b
g (PolyDissect Word
tag Int
cur SmallArray Any
arr) =
    let !n :: Int
n = SmallArray Any -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray Any
arr
        !arr' :: SmallArray Any
arr' = (forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any
forall a. (forall s. ST s (SmallMutableArray s a)) -> SmallArray a
runSmallArray ((forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any)
-> (forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any
forall a b. (a -> b) -> a -> b
$ do
          m <- SmallArray Any
-> Int -> Int -> ST s (SmallMutableArray (PrimState (ST s)) Any)
forall (m :: * -> *) a.
PrimMonad m =>
SmallArray a -> Int -> Int -> m (SmallMutableArray (PrimState m) a)
thawSmallArray SmallArray Any
arr Int
0 Int
n
          let loop !Int
i
                | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n = SmallMutableArray s Any -> f (SmallMutableArray s Any)
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SmallMutableArray s Any
m
                | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
cur = Int -> f (SmallMutableArray s Any)
loop (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
                | Bool
otherwise = do
                    let !j :: b
j = Any -> b
forall a b. a -> b
unsafeCoerce# (SmallArray Any -> Int -> Any
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Any
arr Int
i)
                    SmallMutableArray (PrimState f) Any -> Int -> Any -> f ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState f) Any
m Int
i (b -> Any
forall a b. a -> b
unsafeCoerce# (a -> b
g a
forall {b}. b
j))
                    Int -> f (SmallMutableArray s Any)
loop (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
          loop 0
    in Word -> Int -> SmallArray Any -> PolyDissect c b
forall c j. Word -> Int -> SmallArray Any -> PolyDissect c j
PolyDissect Word
tag Int
cur SmallArray Any
arr'

-- | Bifunctor mapping over both evaluated Clowns and unevaluated Jokers.
instance Bifunctor PolyDissect where
  bimap :: forall a b c d.
(a -> b) -> (c -> d) -> PolyDissect a c -> PolyDissect b d
bimap a -> b
f c -> d
g (PolyDissect Word
tag Int
cur SmallArray Any
arr) =
    let !n :: Int
n = SmallArray Any -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray Any
arr
        !arr' :: SmallArray Any
arr' = (forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any
forall a. (forall s. ST s (SmallMutableArray s a)) -> SmallArray a
runSmallArray ((forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any)
-> (forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any
forall a b. (a -> b) -> a -> b
$ do
          m <- SmallArray Any
-> Int -> Int -> ST s (SmallMutableArray (PrimState (ST s)) Any)
forall (m :: * -> *) a.
PrimMonad m =>
SmallArray a -> Int -> Int -> m (SmallMutableArray (PrimState m) a)
thawSmallArray SmallArray Any
arr Int
0 Int
n
          let loop !Int
i
                | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n = SmallMutableArray s Any -> f (SmallMutableArray s Any)
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SmallMutableArray s Any
m
                | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
cur = do
                    let !c :: b
c = Any -> b
forall a b. a -> b
unsafeCoerce# (SmallArray Any -> Int -> Any
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Any
arr Int
i)
                    SmallMutableArray (PrimState f) Any -> Int -> Any -> f ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState f) Any
m Int
i (b -> Any
forall a b. a -> b
unsafeCoerce# (a -> b
f a
forall {b}. b
c))
                    Int -> f (SmallMutableArray s Any)
loop (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
                | Int
i Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
cur = Int -> f (SmallMutableArray s Any)
loop (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
                | Bool
otherwise = do
                    let !j :: b
j = Any -> b
forall a b. a -> b
unsafeCoerce# (SmallArray Any -> Int -> Any
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Any
arr Int
i)
                    SmallMutableArray (PrimState f) Any -> Int -> Any -> f ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState f) Any
m Int
i (d -> Any
forall a b. a -> b
unsafeCoerce# (c -> d
g c
forall {b}. b
j))
                    Int -> f (SmallMutableArray s Any)
loop (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
          loop 0
    in Word -> Int -> SmallArray Any -> PolyDissect b d
forall c j. Word -> Int -> SmallArray Any -> PolyDissect c j
PolyDissect Word
tag Int
cur SmallArray Any
arr'

-- | Step into slot 0 of a 'Polytropos.Core.Rep' syntax node in strictly O(1) time.
--
-- If the constructor has zero payload slots (e.g. nullary constructor or empty record),
-- returns 'Left' immediately with zero heap allocations. Otherwise, initializes
-- 'pdCursor' at 0 and returns 'Right' with the first child term paired with 'PolyDissect'.
{-# INLINE polyStepIn #-}
polyStepIn
  :: Rep f j
  -> Either (Rep g c) (f j, PolyDissect (g c) (f j))
polyStepIn :: forall (f :: * -> *) j (g :: * -> *) c.
Rep f j -> Either (Rep g c) (f j, PolyDissect (g c) (f j))
polyStepIn (Rep !Word
tag !SmallArray (f Any)
arr)
  | SmallArray (f Any) -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray (f Any)
arr Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 =
      Rep g c -> Either (Rep g c) (f j, PolyDissect (g c) (f j))
forall a b. a -> Either a b
Left (Word -> SmallArray (g Any) -> Rep g c
forall {k} (f :: * -> *) (a :: k).
Word -> SmallArray (f Any) -> Rep f a
Rep Word
tag (SmallArray (f Any) -> SmallArray (g Any)
forall a b. a -> b
unsafeCoerce# SmallArray (f Any)
arr))
  | Bool
otherwise =
      let !firstJoker :: b
firstJoker = f Any -> b
forall a b. a -> b
unsafeCoerce# (SmallArray (f Any) -> Int -> f Any
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray (f Any)
arr Int
0)
      in (f j, PolyDissect (g c) (f j))
-> Either (Rep g c) (f j, PolyDissect (g c) (f j))
forall a b. b -> Either a b
Right (f j
forall {b}. b
firstJoker, Word -> Int -> SmallArray Any -> PolyDissect (g c) (f j)
forall c j. Word -> Int -> SmallArray Any -> PolyDissect c j
PolyDissect Word
tag Int
0 (SmallArray (f Any) -> SmallArray Any
forall a b. a -> b
unsafeCoerce# SmallArray (f Any)
arr))

-- | Plug an evaluated Clown @g c@ into 'pdCursor' and advance to @pdCursor + 1@.
--
-- When @pdCursor + 1 == sizeofSmallArray pdSlots@, all child terms have been evaluated
-- and the complete reconstructed 'Rep' is returned in 'Left'.
-- Otherwise, returns 'Right' with the next Joker subterm and updated 'PolyDissect'.
{-# INLINE polyStepNext #-}
polyStepNext
  :: g c
  -> PolyDissect (g c) (f j)
  -> Either (Rep g c) (f j, PolyDissect (g c) (f j))
polyStepNext :: forall (g :: * -> *) c (f :: * -> *) j.
g c
-> PolyDissect (g c) (f j)
-> Either (Rep g c) (f j, PolyDissect (g c) (f j))
polyStepNext !g c
clownVal (PolyDissect !Word
tag !Int
cursor !SmallArray Any
arr) =
  let !n :: Int
n     = SmallArray Any -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray Any
arr
      !nextC :: Int
nextC = Int
cursor Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
      !arr' :: SmallArray Any
arr'  = (forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any
forall a. (forall s. ST s (SmallMutableArray s a)) -> SmallArray a
runSmallArray ((forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any)
-> (forall s. ST s (SmallMutableArray s Any)) -> SmallArray Any
forall a b. (a -> b) -> a -> b
$ do
                 m <- SmallArray Any
-> Int -> Int -> ST s (SmallMutableArray (PrimState (ST s)) Any)
forall (m :: * -> *) a.
PrimMonad m =>
SmallArray a -> Int -> Int -> m (SmallMutableArray (PrimState m) a)
thawSmallArray SmallArray Any
arr Int
0 Int
n
                 writeSmallArray m cursor (unsafeCoerce# clownVal)
                 pure m
  in if Int
nextC Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n
       then Rep g c -> Either (Rep g c) (f j, PolyDissect (g c) (f j))
forall a b. a -> Either a b
Left (Word -> SmallArray (g Any) -> Rep g c
forall {k} (f :: * -> *) (a :: k).
Word -> SmallArray (f Any) -> Rep f a
Rep Word
tag (SmallArray Any -> SmallArray (g Any)
forall a b. a -> b
unsafeCoerce# SmallArray Any
arr'))
       else let !nextJoker :: b
nextJoker = Any -> b
forall a b. a -> b
unsafeCoerce# (SmallArray Any -> Int -> Any
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Any
arr Int
nextC)
            in (f j, PolyDissect (g c) (f j))
-> Either (Rep g c) (f j, PolyDissect (g c) (f j))
forall a b. b -> Either a b
Right (f j
forall {b}. b
nextJoker, Word -> Int -> SmallArray Any -> PolyDissect (g c) (f j)
forall c j. Word -> Int -> SmallArray Any -> PolyDissect c j
PolyDissect Word
tag Int
nextC SmallArray Any
arr')