{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}

-- |
-- Module      : Pykinos.Schema.HiddenClass
-- Description : Order-preserving symbol lexicon and 3-way dynamic record MergeMorphs.
--
-- Eliminates dynamic @Map Text Expr@ trees by interning field names into
-- rank-ordered 'FieldId's and representing record shapes as interned 'SchemaId's
-- with precomputed 3-way 'MergeMorph3' gather plans.
--
-- === Architectural Rationale
--
-- Traditional AST record representations in interpreters (such as Dhall and 1ML)
-- use unbalanced search trees or associative maps. When performing record operations
-- (such as record merge @//@, deep meet @/\\@, or signature projection @:>@), every
-- operation traverses pointer-heavy tree structures, resulting in significant GC
-- pressure and branch mispredictions.
--
-- By decoupling the field names into a frozen, rank-ordered 'Lexicon' and mapping
-- field sets into contiguous sorted 'PrimArray's of 'Word32's ('SchemaId'), record
-- merge operations become pure array-to-array linear scans synthesized in $O(N_1 + N_2)$
-- time into unboxed 64-bit gather codes ('MergeMorph3').
--
-- === 3-Way Gather Code Representation
--
-- Each gather code in 'MergeMorph3' is an unboxed 'Int64':
--
--   1. Positive values (@code >= 0@): The field is copied directly from slot
--      @code@ of the left record.
--   2. Negative values with bit 62 clear (@code < 0@, @bit 62 == 0@): The field
--      is copied directly from slot @complement code@ of the right record.
--   3. Negative values with bit 62 set (@code < 0@, @bit 62 == 1@): Both records
--      contain the field. A collision has occurred that must be resolved via
--      recursive normalization (for 'OpCombineDeep'). The two source slot indices
--      @(idx1, idx2)@ are packed into bits 0..59.
module Pykinos.Schema.HiddenClass
  ( -- * Field and Schema Identifiers
    FieldId(..)
  , SchemaId(..)

    -- * Dynamic Record Operations
  , RecordOp(..)
  , MergeMorph3(..)

    -- * Symbol Lexicon
  , Lexicon(..)
  , buildLexicon
  , lookupFieldId
  , lookupFieldText

    -- * Slot Search and Gather Code Encoding
  , findFieldSlot
  , collisionBit3
  , encodeRightSlot3
  , encodeCollision3
  , decodeMergeCode3

    -- * Linear Merge Synthesis
  , synthesizeMergeMorph3
  ) where

import Data.Bits (complement, shiftL, shiftR, unsafeShiftR, (.&.), (.|.))
import Data.Int (Int64)
import qualified Data.Map.Strict as Map
import Data.Primitive.PrimArray
  ( PrimArray
  , indexPrimArray
  , primArrayFromList
  , sizeofPrimArray
  )
import Data.Primitive.SmallArray
  ( SmallArray
  , indexSmallArray
  , smallArrayFromList
  )
import qualified Data.Set as Set
import Data.Text (Text)
import Data.Word (Word32)

-- | Rank-ordered 32-bit field identifier.
--
-- Invariant: For all field identifiers @fid1@ and @fid2@,
-- @fid1 < fid2@ holds if and only if @text(fid1) < text(fid2)@ in standard
-- lexicographical UTF-8 byte order. This invariant guarantees that sorting by
-- 'FieldId' is completely isomorphic to sorting by record label 'Text'.
newtype FieldId = FieldId { FieldId -> Word32
unFieldId :: Word32 }
  deriving newtype (FieldId -> FieldId -> Bool
(FieldId -> FieldId -> Bool)
-> (FieldId -> FieldId -> Bool) -> Eq FieldId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FieldId -> FieldId -> Bool
== :: FieldId -> FieldId -> Bool
$c/= :: FieldId -> FieldId -> Bool
/= :: FieldId -> FieldId -> Bool
Eq, Eq FieldId
Eq FieldId =>
(FieldId -> FieldId -> Ordering)
-> (FieldId -> FieldId -> Bool)
-> (FieldId -> FieldId -> Bool)
-> (FieldId -> FieldId -> Bool)
-> (FieldId -> FieldId -> Bool)
-> (FieldId -> FieldId -> FieldId)
-> (FieldId -> FieldId -> FieldId)
-> Ord FieldId
FieldId -> FieldId -> Bool
FieldId -> FieldId -> Ordering
FieldId -> FieldId -> FieldId
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 :: FieldId -> FieldId -> Ordering
compare :: FieldId -> FieldId -> Ordering
$c< :: FieldId -> FieldId -> Bool
< :: FieldId -> FieldId -> Bool
$c<= :: FieldId -> FieldId -> Bool
<= :: FieldId -> FieldId -> Bool
$c> :: FieldId -> FieldId -> Bool
> :: FieldId -> FieldId -> Bool
$c>= :: FieldId -> FieldId -> Bool
>= :: FieldId -> FieldId -> Bool
$cmax :: FieldId -> FieldId -> FieldId
max :: FieldId -> FieldId -> FieldId
$cmin :: FieldId -> FieldId -> FieldId
min :: FieldId -> FieldId -> FieldId
Ord, Int -> FieldId -> ShowS
[FieldId] -> ShowS
FieldId -> String
(Int -> FieldId -> ShowS)
-> (FieldId -> String) -> ([FieldId] -> ShowS) -> Show FieldId
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FieldId -> ShowS
showsPrec :: Int -> FieldId -> ShowS
$cshow :: FieldId -> String
show :: FieldId -> String
$cshowList :: [FieldId] -> ShowS
showList :: [FieldId] -> ShowS
Show)

-- | Interned 32-bit identifier for a sorted 'PrimArray' of 'FieldId's.
--
-- A 'SchemaId' represents the immutable structural type of a record. Two records
-- share the same 'SchemaId' if and only if they possess identical field sets in
-- identical order.
newtype SchemaId = SchemaId { SchemaId -> Word32
unSchemaId :: Word32 }
  deriving newtype (SchemaId -> SchemaId -> Bool
(SchemaId -> SchemaId -> Bool)
-> (SchemaId -> SchemaId -> Bool) -> Eq SchemaId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SchemaId -> SchemaId -> Bool
== :: SchemaId -> SchemaId -> Bool
$c/= :: SchemaId -> SchemaId -> Bool
/= :: SchemaId -> SchemaId -> Bool
Eq, Eq SchemaId
Eq SchemaId =>
(SchemaId -> SchemaId -> Ordering)
-> (SchemaId -> SchemaId -> Bool)
-> (SchemaId -> SchemaId -> Bool)
-> (SchemaId -> SchemaId -> Bool)
-> (SchemaId -> SchemaId -> Bool)
-> (SchemaId -> SchemaId -> SchemaId)
-> (SchemaId -> SchemaId -> SchemaId)
-> Ord SchemaId
SchemaId -> SchemaId -> Bool
SchemaId -> SchemaId -> Ordering
SchemaId -> SchemaId -> SchemaId
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 :: SchemaId -> SchemaId -> Ordering
compare :: SchemaId -> SchemaId -> Ordering
$c< :: SchemaId -> SchemaId -> Bool
< :: SchemaId -> SchemaId -> Bool
$c<= :: SchemaId -> SchemaId -> Bool
<= :: SchemaId -> SchemaId -> Bool
$c> :: SchemaId -> SchemaId -> Bool
> :: SchemaId -> SchemaId -> Bool
$c>= :: SchemaId -> SchemaId -> Bool
>= :: SchemaId -> SchemaId -> Bool
$cmax :: SchemaId -> SchemaId -> SchemaId
max :: SchemaId -> SchemaId -> SchemaId
$cmin :: SchemaId -> SchemaId -> SchemaId
min :: SchemaId -> SchemaId -> SchemaId
Ord, Int -> SchemaId -> ShowS
[SchemaId] -> ShowS
SchemaId -> String
(Int -> SchemaId -> ShowS)
-> (SchemaId -> String) -> ([SchemaId] -> ShowS) -> Show SchemaId
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SchemaId -> ShowS
showsPrec :: Int -> SchemaId -> ShowS
$cshow :: SchemaId -> String
show :: SchemaId -> String
$cshowList :: [SchemaId] -> ShowS
showList :: [SchemaId] -> ShowS
Show)

-- | Dynamic record algebra operations supported by 'MergeMorph3'.
--
-- These correspond to the fundamental record combinators in languages with
-- first-class records and modules:
data RecordOp
  = OpPreferR
    -- ^ Right-biased override union. When a label appears in both records,
    -- the value from the right-hand record overwrites the left-hand record.
    -- Corresponds to Dhall's @//@ and 1ML structure @include@.
  | OpCombineDeep
    -- ^ Recursive deep meet. When a label appears in both records,
    -- the two values collide and must be recursively merged.
    -- Corresponds to Dhall's @/\\@ and 1ML signature sharing.
  | OpRestrict
    -- ^ Domain restriction / projection. Restricts the fields of the left
    -- record to the schema defined by the right record.
    -- Corresponds to 1ML existential sealing (@Mod :> Sig@).
  deriving (RecordOp -> RecordOp -> Bool
(RecordOp -> RecordOp -> Bool)
-> (RecordOp -> RecordOp -> Bool) -> Eq RecordOp
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RecordOp -> RecordOp -> Bool
== :: RecordOp -> RecordOp -> Bool
$c/= :: RecordOp -> RecordOp -> Bool
/= :: RecordOp -> RecordOp -> Bool
Eq, Eq RecordOp
Eq RecordOp =>
(RecordOp -> RecordOp -> Ordering)
-> (RecordOp -> RecordOp -> Bool)
-> (RecordOp -> RecordOp -> Bool)
-> (RecordOp -> RecordOp -> Bool)
-> (RecordOp -> RecordOp -> Bool)
-> (RecordOp -> RecordOp -> RecordOp)
-> (RecordOp -> RecordOp -> RecordOp)
-> Ord RecordOp
RecordOp -> RecordOp -> Bool
RecordOp -> RecordOp -> Ordering
RecordOp -> RecordOp -> RecordOp
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 :: RecordOp -> RecordOp -> Ordering
compare :: RecordOp -> RecordOp -> Ordering
$c< :: RecordOp -> RecordOp -> Bool
< :: RecordOp -> RecordOp -> Bool
$c<= :: RecordOp -> RecordOp -> Bool
<= :: RecordOp -> RecordOp -> Bool
$c> :: RecordOp -> RecordOp -> Bool
> :: RecordOp -> RecordOp -> Bool
$c>= :: RecordOp -> RecordOp -> Bool
>= :: RecordOp -> RecordOp -> Bool
$cmax :: RecordOp -> RecordOp -> RecordOp
max :: RecordOp -> RecordOp -> RecordOp
$cmin :: RecordOp -> RecordOp -> RecordOp
min :: RecordOp -> RecordOp -> RecordOp
Ord, Int -> RecordOp -> ShowS
[RecordOp] -> ShowS
RecordOp -> String
(Int -> RecordOp -> ShowS)
-> (RecordOp -> String) -> ([RecordOp] -> ShowS) -> Show RecordOp
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RecordOp -> ShowS
showsPrec :: Int -> RecordOp -> ShowS
$cshow :: RecordOp -> String
show :: RecordOp -> String
$cshowList :: [RecordOp] -> ShowS
showList :: [RecordOp] -> ShowS
Show)

-- | 3-way gather plan encoded in an unboxed 'PrimArray' of 'Int64' codes.
--
-- The array length matches the number of fields in the resulting merged record.
-- Each slot contains an instruction specifying how the target value is obtained:
--
--   * @code >= 0@              : copy slot @code@ from left record
--   * @code < 0, bit 62 == 0@  : copy slot @complement code@ from right record
--   * @code < 0, bit 62 == 1@  : lazy deep-meet collision on @(idx1, idx2)@
newtype MergeMorph3 = MergeMorph3 { MergeMorph3 -> PrimArray Int64
unMergeMorph3 :: PrimArray Int64 }
  deriving (MergeMorph3 -> MergeMorph3 -> Bool
(MergeMorph3 -> MergeMorph3 -> Bool)
-> (MergeMorph3 -> MergeMorph3 -> Bool) -> Eq MergeMorph3
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MergeMorph3 -> MergeMorph3 -> Bool
== :: MergeMorph3 -> MergeMorph3 -> Bool
$c/= :: MergeMorph3 -> MergeMorph3 -> Bool
/= :: MergeMorph3 -> MergeMorph3 -> Bool
Eq, Int -> MergeMorph3 -> ShowS
[MergeMorph3] -> ShowS
MergeMorph3 -> String
(Int -> MergeMorph3 -> ShowS)
-> (MergeMorph3 -> String)
-> ([MergeMorph3] -> ShowS)
-> Show MergeMorph3
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MergeMorph3 -> ShowS
showsPrec :: Int -> MergeMorph3 -> ShowS
$cshow :: MergeMorph3 -> String
show :: MergeMorph3 -> String
$cshowList :: [MergeMorph3] -> ShowS
showList :: [MergeMorph3] -> ShowS
Show)

-- | Frozen rank-ordered lexicon mapping 'Text' labels to 'FieldId's.
--
-- Provides bidirectional O(log L) lookup from 'Text' to 'FieldId' and
-- O(1) indexed recovery from 'FieldId' back to 'Text'.
data Lexicon = Lexicon
  { Lexicon -> Map Text FieldId
lexToId   :: !(Map.Map Text FieldId)
    -- ^ Forward index mapping unique text labels to rank-ordered field IDs.
  , Lexicon -> SmallArray Text
lexToText :: !(SmallArray Text)
    -- ^ Reverse index enabling O(1) term reconstruction during pretty-printing.
  }
  deriving (Int -> Lexicon -> ShowS
[Lexicon] -> ShowS
Lexicon -> String
(Int -> Lexicon -> ShowS)
-> (Lexicon -> String) -> ([Lexicon] -> ShowS) -> Show Lexicon
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Lexicon -> ShowS
showsPrec :: Int -> Lexicon -> ShowS
$cshow :: Lexicon -> String
show :: Lexicon -> String
$cshowList :: [Lexicon] -> ShowS
showList :: [Lexicon] -> ShowS
Show)

-- | Construct a rank-ordered 'Lexicon' from all field labels appearing in an AST.
--
-- Collects all unique labels, sorts them into strictly ascending order, and assigns
-- zero-based sequential 'Word32' identifiers.
buildLexicon :: [Text] -> Lexicon
buildLexicon :: [Text] -> Lexicon
buildLexicon [Text]
rawLabels =
  let sortedUnique :: [Text]
sortedUnique = Set Text -> [Text]
forall a. Set a -> [a]
Set.toAscList ([Text] -> Set Text
forall a. Ord a => [a] -> Set a
Set.fromList [Text]
rawLabels)
      pairs :: [(Text, FieldId)]
pairs        = [Text] -> [FieldId] -> [(Text, FieldId)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Text]
sortedUnique [Word32 -> FieldId
FieldId Word32
i | Word32
i <- [Word32
0 ..]]
  in Lexicon
       { lexToId :: Map Text FieldId
lexToId   = [(Text, FieldId)] -> Map Text FieldId
forall k a. [(k, a)] -> Map k a
Map.fromDistinctAscList [(Text, FieldId)]
pairs
       , lexToText :: SmallArray Text
lexToText = [Text] -> SmallArray Text
forall a. [a] -> SmallArray a
smallArrayFromList [Text]
sortedUnique
       }

-- | Resolve a 'Text' label to its rank-ordered 'FieldId' in O(log L) time.
{-# INLINE lookupFieldId #-}
lookupFieldId :: Lexicon -> Text -> Maybe FieldId
lookupFieldId :: Lexicon -> Text -> Maybe FieldId
lookupFieldId Lexicon{SmallArray Text
Map Text FieldId
lexToId :: Lexicon -> Map Text FieldId
lexToText :: Lexicon -> SmallArray Text
lexToId :: Map Text FieldId
lexToText :: SmallArray Text
..} !Text
txt = Text -> Map Text FieldId -> Maybe FieldId
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Text
txt Map Text FieldId
lexToId

-- | Recover the original 'Text' label from a 'FieldId' in strictly O(1) time.
{-# INLINE lookupFieldText #-}
lookupFieldText :: Lexicon -> FieldId -> Text
lookupFieldText :: Lexicon -> FieldId -> Text
lookupFieldText Lexicon{SmallArray Text
Map Text FieldId
lexToId :: Lexicon -> Map Text FieldId
lexToText :: Lexicon -> SmallArray Text
lexToId :: Map Text FieldId
lexToText :: SmallArray Text
..} (FieldId !Word32
w) =
  SmallArray Text -> Int -> Text
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Text
lexToText (Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
w)

-- | Bit 62 distinguishes a right-record slot from a two-record deep collision.
-- Bit 63 is the sign bit (1 for negative numbers). Bit 62 serves as the discriminator flag.
collisionBit3 :: Int64
collisionBit3 :: Int64
collisionBit3 = Int64
1 Int64 -> Int -> Int64
forall a. Bits a => a -> Int -> a
`shiftL` Int
62

-- | Encode a right-record slot index @idx2@ as a negative 'Int64' with bit 62 clear.
--
-- Uses bitwise complement ('Data.Bits.complement') so that @idx2 = 0@ maps to @-1@,
-- @idx2 = 1@ maps to @-2@, etc., ensuring strict negativity while keeping bit 62 zero.
{-# INLINE encodeRightSlot3 #-}
encodeRightSlot3 :: Int -> Int64
encodeRightSlot3 :: Int -> Int64
encodeRightSlot3 !Int
idx2 =
  Int64 -> Int64
forall a. Bits a => a -> a
complement (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
idx2) Int64 -> Int64 -> Int64
forall a. Bits a => a -> a -> a
.&. Int64 -> Int64
forall a. Bits a => a -> a
complement Int64
collisionBit3

-- | Encode a colliding pair of slot indices @(idx1, idx2)@ for 'OpCombineDeep'.
--
-- Packs @idx1@ into bits 30..59 and @idx2@ into bits 0..29, sets bit 62, and negates.
{-# INLINE encodeCollision3 #-}
encodeCollision3 :: Int -> Int -> Int64
encodeCollision3 :: Int -> Int -> Int64
encodeCollision3 !Int
idx1 !Int
idx2 =
  let !payload :: Int64
payload = (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
idx1 Int64 -> Int -> Int64
forall a. Bits a => a -> Int -> a
`shiftL` Int
30) Int64 -> Int64 -> Int64
forall a. Bits a => a -> a -> a
.|. Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
idx2
  in Int64 -> Int64
forall a. Bits a => a -> a
complement Int64
payload Int64 -> Int64 -> Int64
forall a. Bits a => a -> a -> a
.|. Int64
collisionBit3

-- | Decode a 'MergeMorph3' gather code into its constituent source slots:
--
--   * @Left (Left idx1)@   : Unambiguous value from slot @idx1@ of the left record.
--   * @Left (Right idx2)@  : Unambiguous value from slot @idx2@ of the right record.
--   * @Right (idx1, idx2)@ : Recursive collision between @idx1@ and @idx2@.
{-# INLINE decodeMergeCode3 #-}
decodeMergeCode3 :: Int64 -> Either (Either Int Int) (Int, Int)
decodeMergeCode3 :: Int64 -> Either (Either Int Int) (Int, Int)
decodeMergeCode3 !Int64
code
  | Int64
code Int64 -> Int64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Int64
0 = Either Int Int -> Either (Either Int Int) (Int, Int)
forall a b. a -> Either a b
Left (Int -> Either Int Int
forall a b. a -> Either a b
Left (Int64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int64
code))
  | (Int64
code Int64 -> Int64 -> Int64
forall a. Bits a => a -> a -> a
.&. Int64
collisionBit3) Int64 -> Int64 -> Bool
forall a. Eq a => a -> a -> Bool
== Int64
0 =
      Either Int Int -> Either (Either Int Int) (Int, Int)
forall a b. a -> Either a b
Left (Int -> Either Int Int
forall a b. b -> Either a b
Right (Int64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int64 -> Int64
forall a. Bits a => a -> a
complement Int64
code)))
  | Bool
otherwise =
      let !raw :: Int64
raw  = Int64 -> Int64
forall a. Bits a => a -> a
complement (Int64
code Int64 -> Int64 -> Int64
forall a. Bits a => a -> a -> a
.&. Int64 -> Int64
forall a. Bits a => a -> a
complement Int64
collisionBit3)
          !idx1 :: Int
idx1 = Int64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int64
raw Int64 -> Int -> Int64
forall a. Bits a => a -> Int -> a
`shiftR` Int
30)
          !idx2 :: Int
idx2 = Int64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int64
raw Int64 -> Int64 -> Int64
forall a. Bits a => a -> a -> a
.&. Int64
0x3FFFFFFF)
      in (Int, Int) -> Either (Either Int Int) (Int, Int)
forall a b. b -> Either a b
Right (Int
idx1, Int
idx2)

-- | Branch-minimized binary search over a sorted 'PrimArray' of 'Word32' field IDs.
--
-- Returns the slot index of the target 'FieldId' if present, or 'Nothing'.
-- Operates in $O(\log N)$ time with zero heap allocations.
{-# INLINE findFieldSlot #-}
findFieldSlot :: PrimArray Word32 -> FieldId -> Maybe Int
findFieldSlot :: PrimArray Word32 -> FieldId -> Maybe Int
findFieldSlot !PrimArray Word32
fields (FieldId !Word32
target) =
  Int -> Int -> Maybe Int
go Int
0 (PrimArray Word32 -> Int
forall a. Prim a => PrimArray a -> Int
sizeofPrimArray PrimArray Word32
fields Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)
  where
    go :: Int -> Int -> Maybe Int
go !Int
lo !Int
hi
      | Int
lo Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
hi   = Maybe Int
forall a. Maybe a
Nothing
      | Bool
otherwise =
          let !mid :: Int
mid = (Int
lo Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
hi) Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
1
              !v :: Word32
v   = PrimArray Word32 -> Int -> Word32
forall a. Prim a => PrimArray a -> Int -> a
indexPrimArray PrimArray Word32
fields Int
mid
          in case Word32 -> Word32 -> Ordering
forall a. Ord a => a -> a -> Ordering
compare Word32
v Word32
target of
               Ordering
LT -> Int -> Int -> Maybe Int
go (Int
mid Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Int
hi
               Ordering
GT -> Int -> Int -> Maybe Int
go Int
lo (Int
mid Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)
               Ordering
EQ -> Int -> Maybe Int
forall a. a -> Maybe a
Just Int
mid

-- | Two-finger linear synthesis of a 3-way 'MergeMorph3' over two sorted schemas.
--
-- Traverses the two sorted 'PrimArray's in parallel in $O(N_1 + N_2)$ time, emitting:
--
--   1. The merged schema's sorted 'PrimArray' of field IDs.
--   2. The compiled 'MergeMorph3' gather codes for instantiating the merged record values.
synthesizeMergeMorph3
  :: RecordOp
  -> PrimArray Word32
  -> PrimArray Word32
  -> (PrimArray Word32, MergeMorph3)
synthesizeMergeMorph3 :: RecordOp
-> PrimArray Word32
-> PrimArray Word32
-> (PrimArray Word32, MergeMorph3)
synthesizeMergeMorph3 !RecordOp
op !PrimArray Word32
f1 !PrimArray Word32
f2 =
  let !n1 :: Int
n1 = PrimArray Word32 -> Int
forall a. Prim a => PrimArray a -> Int
sizeofPrimArray PrimArray Word32
f1
      !n2 :: Int
n2 = PrimArray Word32 -> Int
forall a. Prim a => PrimArray a -> Int
sizeofPrimArray PrimArray Word32
f2
      -- Linear merge worker with accumulators for output fields and gather codes:
      go :: Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go !Int
i !Int
j [Word32]
accFields [Int64]
accCodes
        | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n1 Bool -> Bool -> Bool
&& Int
j Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n2 =
            -- Both inputs exhausted; finish and freeze output arrays:
            ( [Word32] -> PrimArray Word32
forall a. Prim a => [a] -> PrimArray a
primArrayFromList ([Word32] -> [Word32]
forall a. [a] -> [a]
reverse [Word32]
accFields)
            , PrimArray Int64 -> MergeMorph3
MergeMorph3 ([Int64] -> PrimArray Int64
forall a. Prim a => [a] -> PrimArray a
primArrayFromList ([Int64] -> [Int64]
forall a. [a] -> [a]
reverse [Int64]
accCodes))
            )
        | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n1 =
            -- Left input exhausted; process remaining right-hand fields:
            case RecordOp
op of
              RecordOp
OpRestrict ->
                -- OpRestrict only retains fields present in the left record:
                ( [Word32] -> PrimArray Word32
forall a. Prim a => [a] -> PrimArray a
primArrayFromList ([Word32] -> [Word32]
forall a. [a] -> [a]
reverse [Word32]
accFields)
                , PrimArray Int64 -> MergeMorph3
MergeMorph3 ([Int64] -> PrimArray Int64
forall a. Prim a => [a] -> PrimArray a
primArrayFromList ([Int64] -> [Int64]
forall a. [a] -> [a]
reverse [Int64]
accCodes))
                )
              RecordOp
_ ->
                let !k2 :: Word32
k2 = PrimArray Word32 -> Int -> Word32
forall a. Prim a => PrimArray a -> Int -> a
indexPrimArray PrimArray Word32
f2 Int
j
                in Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go Int
i (Int
j Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Word32
k2 Word32 -> [Word32] -> [Word32]
forall a. a -> [a] -> [a]
: [Word32]
accFields) (Int -> Int64
encodeRightSlot3 Int
j Int64 -> [Int64] -> [Int64]
forall a. a -> [a] -> [a]
: [Int64]
accCodes)
        | Int
j Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n2 =
            -- Right input exhausted; process remaining left-hand fields:
            case RecordOp
op of
              RecordOp
OpRestrict ->
                -- OpRestrict only retains fields present in both records:
                ( [Word32] -> PrimArray Word32
forall a. Prim a => [a] -> PrimArray a
primArrayFromList ([Word32] -> [Word32]
forall a. [a] -> [a]
reverse [Word32]
accFields)
                , PrimArray Int64 -> MergeMorph3
MergeMorph3 ([Int64] -> PrimArray Int64
forall a. Prim a => [a] -> PrimArray a
primArrayFromList ([Int64] -> [Int64]
forall a. [a] -> [a]
reverse [Int64]
accCodes))
                )
              RecordOp
_ ->
                let !k1 :: Word32
k1 = PrimArray Word32 -> Int -> Word32
forall a. Prim a => PrimArray a -> Int -> a
indexPrimArray PrimArray Word32
f1 Int
i
                in Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Int
j (Word32
k1 Word32 -> [Word32] -> [Word32]
forall a. a -> [a] -> [a]
: [Word32]
accFields) (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i Int64 -> [Int64] -> [Int64]
forall a. a -> [a] -> [a]
: [Int64]
accCodes)
        | Bool
otherwise =
            -- Both streams have remaining elements; compare field IDs:
            let !k1 :: Word32
k1 = PrimArray Word32 -> Int -> Word32
forall a. Prim a => PrimArray a -> Int -> a
indexPrimArray PrimArray Word32
f1 Int
i
                !k2 :: Word32
k2 = PrimArray Word32 -> Int -> Word32
forall a. Prim a => PrimArray a -> Int -> a
indexPrimArray PrimArray Word32
f2 Int
j
            in case Word32 -> Word32 -> Ordering
forall a. Ord a => a -> a -> Ordering
compare Word32
k1 Word32
k2 of
                 Ordering
LT -> case RecordOp
op of
                   RecordOp
OpRestrict -> Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Int
j [Word32]
accFields [Int64]
accCodes
                   RecordOp
_          -> Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Int
j (Word32
k1 Word32 -> [Word32] -> [Word32]
forall a. a -> [a] -> [a]
: [Word32]
accFields) (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i Int64 -> [Int64] -> [Int64]
forall a. a -> [a] -> [a]
: [Int64]
accCodes)
                 Ordering
GT -> case RecordOp
op of
                   RecordOp
OpRestrict -> Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go Int
i (Int
j Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) [Word32]
accFields [Int64]
accCodes
                   RecordOp
_          -> Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go Int
i (Int
j Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Word32
k2 Word32 -> [Word32] -> [Word32]
forall a. a -> [a] -> [a]
: [Word32]
accFields) (Int -> Int64
encodeRightSlot3 Int
j Int64 -> [Int64] -> [Int64]
forall a. a -> [a] -> [a]
: [Int64]
accCodes)
                 Ordering
EQ ->
                   -- Field appears in both records; determine resolution by operation:
                   let !code :: Int64
code = case RecordOp
op of
                         RecordOp
OpPreferR     -> Int -> Int64
encodeRightSlot3 Int
j
                         RecordOp
OpCombineDeep -> Int -> Int -> Int64
encodeCollision3 Int
i Int
j
                         RecordOp
OpRestrict    -> Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i
                   in Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Int
j Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Word32
k1 Word32 -> [Word32] -> [Word32]
forall a. a -> [a] -> [a]
: [Word32]
accFields) (Int64
code Int64 -> [Int64] -> [Int64]
forall a. a -> [a] -> [a]
: [Int64]
accCodes)
  in Int
-> Int -> [Word32] -> [Int64] -> (PrimArray Word32, MergeMorph3)
go Int
0 Int
0 [] []