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

-- |
-- Module      : Cek.Examples.OneML
-- Description : Rossberg 1ML first-class module evaluator with MergeMorph3 existential sealing.
--
-- Models 1ML structures and signatures as flat 'SchemaId'-indexed arrays of lazy
-- 'SoAStore' addresses, using 'MergeMorph3' for module @include@ ('OpPreferR')
-- and existential sealing @Mod :> Sig@ ('OpRestrict').
--
-- === Background: Rossberg's 1ML
--
-- Andreas Rossberg's /"1ML — Core and the Modules in the Same Language"/ (ICFP 2015)
-- showed that the traditional stratified distinction between ML core expressions
-- and ML modules (structures, signatures, functors) can be completely dissolved.
-- Modules become first-class records, functors become ordinary functions, and
-- signatures become first-class record types with existential components.
--
-- === Efficient Interpretation with MergeMorph3
--
-- Traditional implementations of 1ML require heavy elaborators that translate
-- module constructs into System \(F_\omega\) terms with dynamic dictionary passing.
-- This CEK machine implementation executes 1ML directly on flat unboxed structures:
--
--   1. Structures and signatures are flat arrays of lazy cells indexed by 'FieldId'
--      and mapped to structural 'SchemaId' identifiers in 'Pykinos.Schema.HiddenClass'.
--   2. Module extension (@include M@) compiles into a single $O(N_1 + N_2)$ linear
--      merge plan ('OpPreferR') via 'synthesizeMergeMorph3'.
--   3. Existential sealing (@Mod :> Sig@) computes a domain restriction ('OpRestrict')
--      in $O(|Sig|)$ time. For every abstract type field ('SpecAbstract'), the evaluator
--      mints a fresh, globally unique skolem constant ('CT_WNeu') in 'SoAStore',
--      hiding the concrete implementation without dynamic wrapper closures.
--
-- > **Demonstrative Reference Implementation**: This package is an educational
-- > and demonstrative reference implementation showcasing Andreas Rossberg's 1ML
-- > first-class module system over the CEK abstract machine with MergeMorph3
-- > existential sealing and Pykinos hidden classes. It is provided primarily as an
-- > executable architectural example within the @cek@ ecosystem documentation.
--
module Cek.OneML
  ( -- * Type Specifications
    TypeSpec(..)

    -- * 1ML Syntax
  , OneMLTerm(..)

    -- * Values and Weak-Head Normal Forms
  , OneMLWHNF(..)

    -- * Continuation Frame Tags
  , pattern FT_1ML_App
  , pattern FT_1ML_Proj
  , pattern FT_1ML_IncludeL
  , pattern FT_1ML_IncludeR
  , pattern FT_1ML_SealSig
  , pattern FT_1ML_SealMod

    -- * Sealing and Evaluation
  , stepOneMLSealing
  , evalOneML
  ) 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.PrimArray
  ( PrimArray
  , indexPrimArray
  , sizeofPrimArray
  )
import Data.Primitive.SmallArray
  ( SmallArray
  , indexSmallArray
  , readSmallArray
  , sizeofSmallArray
  , smallArrayFromList
  , writeSmallArray
  )
import Data.Word (Word32)
import GHC.Exts (unsafeCoerce#)

import Cek.Pykinos.Kont
  ( FrameTag(..)
  , KontStack
  , newKontStack
  , pattern FT_UpdateWHNF
  , popFrameSoA
  , pushFrameSoA
  )
import Cek.Pykinos.Store
  ( CellTag(..)
  , SoAStore(..)
  , StoreChunk(..)
  , acquireSlot
  , allocThunkSoA
  , allocWLitSoA
  , allocWNeuSoA
  , newSoAStore
  , pattern CT_Thunk
  , pattern CT_WBinder
  , pattern CT_WLit
  , pattern CT_WNeu
  , pattern CT_WRecord
  , readCellPhaseSoA
  , unCellTag
  )
import Pykinos.Schema.HiddenClass
  ( FieldId(..)
  , MergeMorph3(..)
  , RecordOp(..)
  , SchemaId(..)
  , decodeMergeCode3
  , findFieldSlot
  , synthesizeMergeMorph3
  )

-- | Frame tag for evaluating a functor argument cell.
pattern FT_1ML_App      :: FrameTag
pattern $bFT_1ML_App :: FrameTag
$mFT_1ML_App :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_1ML_App      = FrameTag 30

-- | Frame tag for projecting a field from an evaluated module structure.
pattern FT_1ML_Proj     :: FrameTag
pattern $bFT_1ML_Proj :: FrameTag
$mFT_1ML_Proj :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_1ML_Proj     = FrameTag 31

-- | Frame tag for evaluating the left-hand module in an @include@ (@//@) expression.
pattern FT_1ML_IncludeL :: FrameTag
pattern $bFT_1ML_IncludeL :: FrameTag
$mFT_1ML_IncludeL :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_1ML_IncludeL = FrameTag 32

-- | Frame tag for evaluating the right-hand module in an @include@ (@//@) expression.
pattern FT_1ML_IncludeR :: FrameTag
pattern $bFT_1ML_IncludeR :: FrameTag
$mFT_1ML_IncludeR :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_1ML_IncludeR = FrameTag 33

-- | Frame tag for evaluating the signature expression in existential sealing.
pattern FT_1ML_SealSig  :: FrameTag
pattern $bFT_1ML_SealSig :: FrameTag
$mFT_1ML_SealSig :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_1ML_SealSig  = FrameTag 34

-- | Frame tag for applying signature restriction and skolemization to the module structure.
pattern FT_1ML_SealMod  :: FrameTag
pattern $bFT_1ML_SealMod :: FrameTag
$mFT_1ML_SealMod :: forall {r}. FrameTag -> ((# #) -> r) -> ((# #) -> r) -> r
FT_1ML_SealMod  = FrameTag 35

-- | Type specifications inside a 1ML signature structure.
data TypeSpec
  = SpecAbstract
    -- ^ Opaque abstract type field (@type t@): generates a fresh skolem 'CT_WNeu'.
  | SpecManifest !OneMLTerm
    -- ^ Transparent type alias (@type t = tau@): preserves the underlying type cell.
  | SpecVal      !OneMLTerm
    -- ^ Value field specification (@val x : tau@): preserves the lazy value thunk.
  deriving (TypeSpec -> TypeSpec -> Bool
(TypeSpec -> TypeSpec -> Bool)
-> (TypeSpec -> TypeSpec -> Bool) -> Eq TypeSpec
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: TypeSpec -> TypeSpec -> Bool
== :: TypeSpec -> TypeSpec -> Bool
$c/= :: TypeSpec -> TypeSpec -> Bool
/= :: TypeSpec -> TypeSpec -> Bool
Eq, Int -> TypeSpec -> ShowS
[TypeSpec] -> ShowS
TypeSpec -> String
(Int -> TypeSpec -> ShowS)
-> (TypeSpec -> String) -> ([TypeSpec] -> ShowS) -> Show TypeSpec
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TypeSpec -> ShowS
showsPrec :: Int -> TypeSpec -> ShowS
$cshow :: TypeSpec -> String
show :: TypeSpec -> String
$cshowList :: [TypeSpec] -> ShowS
showList :: [TypeSpec] -> ShowS
Show)

-- | Unified 1ML Core and Module AST.
data OneMLTerm
  = MVar     !Int
    -- ^ Variable reference resolved via De Bruijn indexing into the environment.
  | MLit     !Int32
    -- ^ 32-bit signed integer literal value.
  | MReified !TypeSpec
    -- ^ Reified first-class type specification treated as a value.
  | MFunctor !OneMLTerm !OneMLTerm
    -- ^ First-class functor / function abstraction taking a domain signature and body.
  | MApp     !OneMLTerm !OneMLTerm
    -- ^ Application of a functor to a module argument.
  | MLet     !OneMLTerm !OneMLTerm
    -- ^ Lexical let binding introducing a local module or value definition.
  | MStruct  !SchemaId !(SmallArray OneMLTerm)
    -- ^ First-class module structure pairing an interned 'SchemaId' with component terms.
  | MProj    !OneMLTerm !FieldId
    -- ^ Structure projection @M.x@ retrieving the field labeled by 'FieldId'.
  | MInclude !OneMLTerm !OneMLTerm
    -- ^ Asymmetric module inclusion / union @include M1 in M2@ using 'OpPreferR'.
  | MSeal    !OneMLTerm !OneMLTerm
    -- ^ Existential signature sealing @M :> S@ using 'OpRestrict' and skolem generation.
  deriving (OneMLTerm -> OneMLTerm -> Bool
(OneMLTerm -> OneMLTerm -> Bool)
-> (OneMLTerm -> OneMLTerm -> Bool) -> Eq OneMLTerm
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: OneMLTerm -> OneMLTerm -> Bool
== :: OneMLTerm -> OneMLTerm -> Bool
$c/= :: OneMLTerm -> OneMLTerm -> Bool
/= :: OneMLTerm -> OneMLTerm -> Bool
Eq, Int -> OneMLTerm -> ShowS
[OneMLTerm] -> ShowS
OneMLTerm -> String
(Int -> OneMLTerm -> ShowS)
-> (OneMLTerm -> String)
-> ([OneMLTerm] -> ShowS)
-> Show OneMLTerm
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> OneMLTerm -> ShowS
showsPrec :: Int -> OneMLTerm -> ShowS
$cshow :: OneMLTerm -> String
show :: OneMLTerm -> String
$cshowList :: [OneMLTerm] -> ShowS
showList :: [OneMLTerm] -> ShowS
Show)

-- | Weak-Head Normal Form representation for 1ML values and modules.
data OneMLWHNF
  = V1Lit          !Int32
    -- ^ Unboxed integer literal value.
  | V1Spec         !TypeSpec ![Int32]
    -- ^ Evaluated type specification closure.
  | V1Functor      !Int32 !OneMLTerm ![Int32]
    -- ^ Evaluated functor closure capturing parameter domain address, body, and env.
  | V1Struct       !SchemaId !(SmallArray Int32)
    -- ^ Evaluated structure pairing a 'SchemaId' with an array of lazy store addresses.
  | V1AbstractType !Int32
    -- ^ Opaque existential skolem type constant generated during signature sealing.
  deriving (OneMLWHNF -> OneMLWHNF -> Bool
(OneMLWHNF -> OneMLWHNF -> Bool)
-> (OneMLWHNF -> OneMLWHNF -> Bool) -> Eq OneMLWHNF
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: OneMLWHNF -> OneMLWHNF -> Bool
== :: OneMLWHNF -> OneMLWHNF -> Bool
$c/= :: OneMLWHNF -> OneMLWHNF -> Bool
/= :: OneMLWHNF -> OneMLWHNF -> Bool
Eq, Int -> OneMLWHNF -> ShowS
[OneMLWHNF] -> ShowS
OneMLWHNF -> String
(Int -> OneMLWHNF -> ShowS)
-> (OneMLWHNF -> String)
-> ([OneMLWHNF] -> ShowS)
-> Show OneMLWHNF
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> OneMLWHNF -> ShowS
showsPrec :: Int -> OneMLWHNF -> ShowS
$cshow :: OneMLWHNF -> String
show :: OneMLWHNF -> String
$cshowList :: [OneMLWHNF] -> ShowS
showList :: [OneMLWHNF] -> ShowS
Show)

-- | Execute 1ML existential sealing (@Mod :> Sig@) in O(|Sig|) using 'MergeMorph3'
--   with 'OpRestrict'. Private fields omitted from 'Sig' are never forced, while
--   'SpecAbstract' fields mint fresh skolem symbols in 'SoAStore'.
stepOneMLSealing
  :: SoAStore s
  -> MutableByteArray s
  -> MergeMorph3
  -> SchemaId
  -> SmallArray Int32
  -> SmallArray Int32
  -> ST s OneMLWHNF
stepOneMLSealing :: forall s.
SoAStore s
-> MutableByteArray s
-> MergeMorph3
-> SchemaId
-> SmallArray Int32
-> SmallArray Int32
-> ST s OneMLWHNF
stepOneMLSealing SoAStore s
store MutableByteArray s
symCounter (MergeMorph3 !PrimArray Int64
restrictPlan) !SchemaId
sigSchema !SmallArray Int32
modAddrs !SmallArray Int32
sigAddrs = do
  let !nOut :: Int
nOut = PrimArray Int64 -> Int
forall a. Prim a => PrimArray a -> Int
sizeofPrimArray PrimArray Int64
restrictPlan
  sealedAddrs <- (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 -> do
    let !code :: Int64
code = PrimArray Int64 -> Int -> Int64
forall a. Prim a => PrimArray a -> Int -> a
indexPrimArray PrimArray Int64
restrictPlan Int
i
        !modSlot :: Int
modSlot = case Int64 -> Either (Either Int Int) (Int, Int)
decodeMergeCode3 Int64
code of
          Left (Left Int
idx1) -> Int
idx1
          Either (Either Int Int) (Int, Int)
_                -> String -> Int
forall a. HasCallStack => String -> a
error String
"OneML: invalid OpRestrict code"
        !modAddr :: Int32
modAddr = SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
modAddrs Int
modSlot
        !sigAddr :: Int32
sigAddr = SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
sigAddrs Int
i
    (!sigTag, !_aux, !sigChk, !sigSlot) <- 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
sigAddr
    if sigTag == CT_WBinder
      then do
        spec :: TypeSpec <- unsafeCoerce# <$> readSmallArray (scPtrA sigChk) sigSlot
        case spec of
          TypeSpec
SpecAbstract -> do
            sym :: 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))
symCounter Int
0
            writeByteArray symCounter 0 (sym + 1)
            allocWNeuSoA store sym
          SpecManifest OneMLTerm
_ -> Int32 -> ST s Int32
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Int32
modAddr
          SpecVal OneMLTerm
_      -> Int32 -> ST s Int32
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Int32
modAddr
      else pure modAddr
    ) [Int
0 .. Int
nOut Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
  pure (V1Struct sigSchema (smallArrayFromList sealedAddrs))

-- | Store a computed 'OneMLWHNF' into an existing 'SoAStore' cell address.
writeOneMLWHNF :: SoAStore s -> Int32 -> OneMLWHNF -> ST s ()
writeOneMLWHNF :: forall s. SoAStore s -> Int32 -> OneMLWHNF -> ST s ()
writeOneMLWHNF SoAStore{MutableByteArray s
SmallMutableArray s (StoreChunk s)
ssChunks :: SmallMutableArray s (StoreChunk s)
ssState :: MutableByteArray s
ssChunks :: forall s. SoAStore s -> SmallMutableArray s (StoreChunk s)
ssState :: forall s. SoAStore s -> MutableByteArray s
..} !Int32
addr !OneMLWHNF
whnf = do
  let !ix :: Int
ix   = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
addr :: 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 SmallMutableArray s (StoreChunk s)
SmallMutableArray (PrimState (ST s)) (StoreChunk s)
ssChunks (Int
ix Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`shiftR` Int
12)
  case whnf of
    V1Lit Int32
n -> do
      MutableByteArray (PrimState (ST s)) -> Int -> Word8 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
scUnboxed Int
slot (CellTag -> Word8
unCellTag CellTag
CT_WLit)
      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))
scUnboxed (Int
5120 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slot) Int32
n
    V1AbstractType Int32
sym -> do
      MutableByteArray (PrimState (ST s)) -> Int -> Word8 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
scUnboxed Int
slot (CellTag -> Word8
unCellTag CellTag
CT_WNeu)
      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))
scUnboxed (Int
5120 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slot) Int32
sym
    V1Spec TypeSpec
spec [Int32]
env -> do
      MutableByteArray (PrimState (ST s)) -> Int -> Word8 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
scUnboxed Int
slot (CellTag -> Word8
unCellTag CellTag
CT_WBinder)
      SmallMutableArray (PrimState (ST s)) Any -> Int -> Any -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState (ST s)) Any
scPtrA Int
slot (TypeSpec -> Any
forall a b. a -> b
unsafeCoerce# TypeSpec
spec)
      SmallMutableArray (PrimState (ST s)) Any -> Int -> Any -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState (ST s)) Any
scPtrB Int
slot ([Int32] -> Any
forall a b. a -> b
unsafeCoerce# [Int32]
env)
    V1Functor Int32
domAddr OneMLTerm
body [Int32]
env -> do
      MutableByteArray (PrimState (ST s)) -> Int -> Word8 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
scUnboxed Int
slot (CellTag -> Word8
unCellTag CellTag
CT_WBinder)
      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))
scUnboxed (Int
5120 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slot) Int32
domAddr
      SmallMutableArray (PrimState (ST s)) Any -> Int -> Any -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState (ST s)) Any
scPtrA Int
slot (OneMLTerm -> Any
forall a b. a -> b
unsafeCoerce# OneMLTerm
body)
      SmallMutableArray (PrimState (ST s)) Any -> Int -> Any -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState (ST s)) Any
scPtrB Int
slot ([Int32] -> Any
forall a b. a -> b
unsafeCoerce# [Int32]
env)
    V1Struct (SchemaId Word32
sid) SmallArray Int32
addrs -> do
      MutableByteArray (PrimState (ST s)) -> Int -> Word8 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
scUnboxed Int
slot (CellTag -> Word8
unCellTag CellTag
CT_WRecord)
      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))
scUnboxed (Int
5120 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slot) (Word32 -> Int32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
sid :: Int32)
      SmallMutableArray (PrimState (ST s)) Any -> Int -> Any -> ST s ()
forall (m :: * -> *) a.
PrimMonad m =>
SmallMutableArray (PrimState m) a -> Int -> a -> m ()
writeSmallArray SmallMutableArray s Any
SmallMutableArray (PrimState (ST s)) Any
scPtrA Int
slot (SmallArray Int32 -> Any
forall a b. a -> b
unsafeCoerce# SmallArray Int32
addrs)

-- | Evaluate a closed 1ML expression given a schema lookup table mapping
--   'SchemaId' to its sorted 'PrimArray Word32' field descriptor.
evalOneML
  :: (SchemaId -> PrimArray Word32)
  -> (PrimArray Word32 -> SchemaId)
  -> OneMLTerm
  -> OneMLWHNF
evalOneML :: (SchemaId -> PrimArray Word32)
-> (PrimArray Word32 -> SchemaId) -> OneMLTerm -> OneMLWHNF
evalOneML SchemaId -> PrimArray Word32
lookupSchema PrimArray Word32 -> SchemaId
internSchema OneMLTerm
rootTerm = (forall s. ST s OneMLWHNF) -> OneMLWHNF
forall a. (forall s. ST s a) -> a
runST ((forall s. ST s OneMLWHNF) -> OneMLWHNF)
-> (forall s. ST s OneMLWHNF) -> OneMLWHNF
forall a b. (a -> b) -> a -> b
$ do
  store      <- ST s (SoAStore s)
forall s. ST s (SoAStore s)
newSoAStore
  kont       <- newKontStack
  symCounter <- newByteArray 4
  writeByteArray symCounter 0 (0 :: Int32)

  let evalTerm !OneMLTerm
term ![Int32]
env = case OneMLTerm
term of
        MVar Int
ix -> Int32 -> ST s OneMLWHNF
evalAddr ([Int32]
env [Int32] -> Int -> Int32
forall a. HasCallStack => [a] -> Int -> a
!! Int
ix)
        MLit Int32
n  -> OneMLWHNF -> ST s OneMLWHNF
applyWHNF (Int32 -> OneMLWHNF
V1Lit Int32
n)
        MReified TypeSpec
spec -> OneMLWHNF -> ST s OneMLWHNF
applyWHNF (TypeSpec -> [Int32] -> OneMLWHNF
V1Spec TypeSpec
spec [Int32]
env)
        MFunctor OneMLTerm
dom OneMLTerm
body -> do
          domAddr <- SoAStore s -> OneMLTerm -> [Int32] -> ST s Int32
forall s a b. SoAStore s -> a -> b -> ST s Int32
allocThunkSoA SoAStore s
store OneMLTerm
dom [Int32]
env
          applyWHNF (V1Functor domAddr body env)
        MLet OneMLTerm
e1 OneMLTerm
e2 -> do
          a1 <- SoAStore s -> OneMLTerm -> [Int32] -> ST s Int32
forall s a b. SoAStore s -> a -> b -> ST s Int32
allocThunkSoA SoAStore s
store OneMLTerm
e1 [Int32]
env
          evalTerm e2 (a1 : env)
        MApp OneMLTerm
fn OneMLTerm
arg -> do
          argAddr <- SoAStore s -> OneMLTerm -> [Int32] -> ST s Int32
forall s a b. SoAStore s -> a -> b -> ST s Int32
allocThunkSoA SoAStore s
store OneMLTerm
arg [Int32]
env
          pushFrameSoA kont FT_1ML_App argAddr 0 (unsafeCoerce# ()) (unsafeCoerce# ())
          evalTerm fn env
        MStruct SchemaId
sid SmallArray OneMLTerm
terms -> do
          let !n :: Int
n = SmallArray OneMLTerm -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray OneMLTerm
terms
          addrs <- (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 -> SoAStore s -> OneMLTerm -> [Int32] -> ST s Int32
forall s a b. SoAStore s -> a -> b -> ST s Int32
allocThunkSoA SoAStore s
store (SmallArray OneMLTerm -> Int -> OneMLTerm
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray OneMLTerm
terms Int
i) [Int32]
env) [Int
0 .. Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
          applyWHNF (V1Struct sid (smallArrayFromList addrs))
        MProj OneMLTerm
modT (FieldId Word32
fid) -> do
          KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
forall s.
KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
pushFrameSoA KontStack s
kont FrameTag
FT_1ML_Proj (Word32 -> Int32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
fid) Int32
0 (() -> Any
forall a b. a -> b
unsafeCoerce# ()) (() -> Any
forall a b. a -> b
unsafeCoerce# ())
          OneMLTerm -> [Int32] -> ST s OneMLWHNF
evalTerm OneMLTerm
modT [Int32]
env
        MInclude OneMLTerm
m1 OneMLTerm
m2 -> do
          a1 <- SoAStore s -> OneMLTerm -> [Int32] -> ST s Int32
forall s a b. SoAStore s -> a -> b -> ST s Int32
allocThunkSoA SoAStore s
store OneMLTerm
m1 [Int32]
env
          pushFrameSoA kont FT_1ML_IncludeL a1 0 (unsafeCoerce# ()) (unsafeCoerce# ())
          evalTerm m2 env
        MSeal OneMLTerm
modT OneMLTerm
sigT -> do
          modAddr <- SoAStore s -> OneMLTerm -> [Int32] -> ST s Int32
forall s a b. SoAStore s -> a -> b -> ST s Int32
allocThunkSoA SoAStore s
store OneMLTerm
modT [Int32]
env
          pushFrameSoA kont FT_1ML_SealSig modAddr 0 (unsafeCoerce# ()) (unsafeCoerce# ())
          evalTerm sigT env

      evalAddr !Int32
addr = do
        (!tag, !aux, !chk, !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
        case tag of
          CellTag
CT_Thunk -> do
            t   :: OneMLTerm <- Any -> OneMLTerm
forall a b. a -> b
unsafeCoerce# (Any -> OneMLTerm) -> ST s Any -> ST s OneMLTerm
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
chk) Int
slot
            env :: [Int32]   <- unsafeCoerce# <$> readSmallArray (scPtrB chk) slot
            pushFrameSoA kont FT_UpdateWHNF addr 0 (unsafeCoerce# ()) (unsafeCoerce# ())
            evalTerm t env
          CellTag
CT_WLit -> OneMLWHNF -> ST s OneMLWHNF
applyWHNF (Int32 -> OneMLWHNF
V1Lit Int32
aux)
          CellTag
CT_WNeu -> OneMLWHNF -> ST s OneMLWHNF
applyWHNF (Int32 -> OneMLWHNF
V1AbstractType Int32
aux)
          CellTag
CT_WRecord -> do
            addrs :: 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
chk) Int
slot
            applyWHNF (V1Struct (SchemaId (fromIntegral aux)) addrs)
          CellTag
CT_WBinder -> do
            pA <- 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
chk) Int
slot
            pB <- readSmallArray (scPtrB chk) slot
            if aux == 0
              then applyWHNF (V1Spec (unsafeCoerce# pA) (unsafeCoerce# pB))
              else applyWHNF (V1Functor aux (unsafeCoerce# pA) (unsafeCoerce# pB))
          CellTag
_ -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: invalid cell phase"

      applyWHNF !OneMLWHNF
whnf = 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
kont
        case mbFrame of
          Maybe (FrameTag, Int32, Int32, Any, Any)
Nothing -> OneMLWHNF -> ST s OneMLWHNF
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure OneMLWHNF
whnf
          Just (FrameTag
ft, Int32
intA, Int32
_intB, Any
ptrA, Any
_ptrB)
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_UpdateWHNF -> do
                SoAStore s -> Int32 -> OneMLWHNF -> ST s ()
forall s. SoAStore s -> Int32 -> OneMLWHNF -> ST s ()
writeOneMLWHNF SoAStore s
store Int32
intA OneMLWHNF
whnf
                OneMLWHNF -> ST s OneMLWHNF
applyWHNF OneMLWHNF
whnf
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_1ML_App -> case OneMLWHNF
whnf of
                V1Functor Int32
_dom OneMLTerm
body [Int32]
env ->
                  OneMLTerm -> [Int32] -> ST s OneMLWHNF
evalTerm OneMLTerm
body (Int32
intA Int32 -> [Int32] -> [Int32]
forall a. a -> [a] -> [a]
: [Int32]
env)
                OneMLWHNF
_ -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: non-functor in MApp"
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_1ML_Proj -> case OneMLWHNF
whnf of
                V1Struct SchemaId
sid SmallArray Int32
addrs ->
                  let !fids :: PrimArray Word32
fids = SchemaId -> PrimArray Word32
lookupSchema SchemaId
sid
                      !fid :: FieldId
fid  = Word32 -> FieldId
FieldId (Int32 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
intA)
                  in case PrimArray Word32 -> FieldId -> Maybe Int
findFieldSlot PrimArray Word32
fids FieldId
fid of
                       Just Int
slotIx -> Int32 -> ST s OneMLWHNF
evalAddr (SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
addrs Int
slotIx)
                       Maybe Int
Nothing     -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: missing field in MProj"
                OneMLWHNF
_ -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: non-struct in MProj"
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_1ML_IncludeL -> do
                KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
forall s.
KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
pushFrameSoA KontStack s
kont FrameTag
FT_1ML_IncludeR Int32
0 Int32
0 (OneMLWHNF -> Any
forall a b. a -> b
unsafeCoerce# OneMLWHNF
whnf) (() -> Any
forall a b. a -> b
unsafeCoerce# ())
                Int32 -> ST s OneMLWHNF
evalAddr Int32
intA
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_1ML_IncludeR -> do
                let !rhsWHNF :: OneMLWHNF
rhsWHNF = Any -> OneMLWHNF
forall a b. a -> b
unsafeCoerce# Any
ptrA :: OneMLWHNF
                case (OneMLWHNF
whnf, OneMLWHNF
rhsWHNF) of
                  (V1Struct SchemaId
sid1 SmallArray Int32
addrs1, V1Struct SchemaId
sid2 SmallArray Int32
addrs2) -> do
                    let (!PrimArray Word32
fOut, MergeMorph3 !PrimArray Int64
plan) =
                          RecordOp
-> PrimArray Word32
-> PrimArray Word32
-> (PrimArray Word32, MergeMorph3)
synthesizeMergeMorph3 RecordOp
OpPreferR (SchemaId -> PrimArray Word32
lookupSchema SchemaId
sid1) (SchemaId -> PrimArray Word32
lookupSchema SchemaId
sid2)
                        !sidOut :: SchemaId
sidOut = PrimArray Word32 -> SchemaId
internSchema PrimArray Word32
fOut
                        !nOut :: Int
nOut   = PrimArray Int64 -> Int
forall a. Prim a => PrimArray a -> Int
sizeofPrimArray PrimArray Int64
plan
                        !outArr :: SmallArray Int32
outArr = [Int32] -> SmallArray Int32
forall a. [a] -> SmallArray a
smallArrayFromList
                          [ case Int64 -> Either (Either Int Int) (Int, Int)
decodeMergeCode3 (PrimArray Int64 -> Int -> Int64
forall a. Prim a => PrimArray a -> Int -> a
indexPrimArray PrimArray Int64
plan Int
i) of
                              Left (Left Int
idx1)  -> SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
addrs1 Int
idx1
                              Left (Right Int
idx2) -> SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
addrs2 Int
idx2
                              Either (Either Int Int) (Int, Int)
_                 -> String -> Int32
forall a. HasCallStack => String -> a
error String
"OneML: impossible collision in OpPreferR"
                          | Int
i <- [Int
0 .. Int
nOut Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
                          ]
                    OneMLWHNF -> ST s OneMLWHNF
applyWHNF (SchemaId -> SmallArray Int32 -> OneMLWHNF
V1Struct SchemaId
sidOut SmallArray Int32
outArr)
                  (OneMLWHNF, OneMLWHNF)
_ -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: non-struct in MInclude"
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_1ML_SealSig -> case OneMLWHNF
whnf of
                V1Struct (SchemaId Word32
sigSid) SmallArray Int32
sigAddrs -> do
                  -- Evaluate the signature's TypeSpec cells to WHNF so stepOneMLSealing can inspect them:
                  let forceSpecs :: Int -> ST s ()
forceSpecs !Int
i
                        | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= SmallArray Int32 -> Int
forall a. SmallArray a -> Int
sizeofSmallArray SmallArray Int32
sigAddrs = () -> ST s ()
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
                        | Bool
otherwise = do
                            let !sAddr :: Int32
sAddr = SmallArray Int32 -> Int -> Int32
forall a. SmallArray a -> Int -> a
indexSmallArray SmallArray Int32
sigAddrs Int
i
                            (!sTag, _, !sChk, !sSlot) <- 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
sAddr
                            when (sTag == CT_Thunk) $ do
                              sTerm :: OneMLTerm <- unsafeCoerce# <$> readSmallArray (scPtrA sChk) sSlot
                              sEnv  :: [Int32]   <- unsafeCoerce# <$> readSmallArray (scPtrB sChk) sSlot
                              case sTerm of
                                MReified TypeSpec
sp -> SoAStore s -> Int32 -> OneMLWHNF -> ST s ()
forall s. SoAStore s -> Int32 -> OneMLWHNF -> ST s ()
writeOneMLWHNF SoAStore s
store Int32
sAddr (TypeSpec -> [Int32] -> OneMLWHNF
V1Spec TypeSpec
sp [Int32]
sEnv)
                                OneMLTerm
_           -> () -> ST s ()
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
                            forceSpecs (i + 1)
                  Int -> ST s ()
forceSpecs Int
0
                  KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
forall s.
KontStack s -> FrameTag -> Int32 -> Int32 -> Any -> Any -> ST s ()
pushFrameSoA KontStack s
kont FrameTag
FT_1ML_SealMod (Word32 -> Int32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
sigSid) Int32
0
                    (SmallArray Int32 -> Any
forall a b. a -> b
unsafeCoerce# SmallArray Int32
sigAddrs) (() -> Any
forall a b. a -> b
unsafeCoerce# ())
                  Int32 -> ST s OneMLWHNF
evalAddr Int32
intA
                OneMLWHNF
_ -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: non-signature struct in MSeal"
            | FrameTag
ft FrameTag -> FrameTag -> Bool
forall a. Eq a => a -> a -> Bool
== FrameTag
FT_1ML_SealMod -> case OneMLWHNF
whnf of
                V1Struct SchemaId
modSchema SmallArray Int32
modAddrs -> do
                  let !sigSchema :: SchemaId
sigSchema = Word32 -> SchemaId
SchemaId (Int32 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
intA)
                      !sigAddrs :: SmallArray Int32
sigAddrs  = Any -> SmallArray Int32
forall a b. a -> b
unsafeCoerce# Any
ptrA :: SmallArray Int32
                      (!PrimArray Word32
_fOut, !MergeMorph3
restrictMorph) =
                        RecordOp
-> PrimArray Word32
-> PrimArray Word32
-> (PrimArray Word32, MergeMorph3)
synthesizeMergeMorph3 RecordOp
OpRestrict (SchemaId -> PrimArray Word32
lookupSchema SchemaId
modSchema) (SchemaId -> PrimArray Word32
lookupSchema SchemaId
sigSchema)
                  sealed <- SoAStore s
-> MutableByteArray s
-> MergeMorph3
-> SchemaId
-> SmallArray Int32
-> SmallArray Int32
-> ST s OneMLWHNF
forall s.
SoAStore s
-> MutableByteArray s
-> MergeMorph3
-> SchemaId
-> SmallArray Int32
-> SmallArray Int32
-> ST s OneMLWHNF
stepOneMLSealing SoAStore s
store MutableByteArray s
symCounter MergeMorph3
restrictMorph SchemaId
sigSchema SmallArray Int32
modAddrs SmallArray Int32
sigAddrs
                  applyWHNF sealed
                OneMLWHNF
_ -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: non-module struct in MSeal"
            | Bool
otherwise -> String -> ST s OneMLWHNF
forall a. HasCallStack => String -> a
error String
"OneML: unknown continuation frame"

  evalTerm rootTerm []