{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}

{- |
Module      : Cek.Core
Description : Foundational Felleisen-Friedman Control-Environment-Continuation (CEK) abstract machine
Copyright   : (c) Nadia Yvette Chambers, 2026
License     : EUPL-1.2
Maintainer  : Nadia Chambers <nadia.yvette.chambers@ik.me>
Stability   : experimental
Portability : non-portable (GHC extensions)

Implements the classical Felleisen-Friedman (1986/1987) Control-Environment-Continuation (CEK)
abstract machine for call-by-value evaluation of functional expressions.

= Architectural Context

Per Note [Felleisen-Friedman CEK Abstract Machine] [ref:note-core-architecture],
this module models evaluation state transitions as an explicit 3-tuple \(\langle C, E, K \rangle\):
1. __Control (\(C\)):__ The active term undergoing reduction ('Term').
2. __Environment (\(E\)):__ Lexical scope mapping free variables to values ('Env').
3. __Continuation (\(K\)):__ Explicit evaluation context frames eliminating host stack recursion ('Cont').

= Transitions

* __Variable:__ \(\langle x, E, K \rangle \Longrightarrow \text{applyCont}(K, E(x))\)
* __Abstraction:__ \(\langle \lambda x. e, E, K \rangle \Longrightarrow \text{applyCont}(K, \text{Closure}(x, e, E))\)
* __Application:__ \(\langle e_1 \; e_2, E, K \rangle \Longrightarrow \langle e_1, E, \text{FrameArg}(e_2, E) : K \rangle\)
* __Argument Evaluated:__ \(\text{applyCont}(\text{FrameArg}(e_2, E) : K, v_1) \Longrightarrow \langle e_2, E, \text{FrameFun}(v_1) : K \rangle\)
* __Function Applied:__ \(\text{applyCont}(\text{FrameFun}(\text{Closure}(x, e, E')) : K, v_2) \Longrightarrow \langle e, E'[x \mapsto v_2], K \rangle\)
-}
module Cek.Core
  ( -- * Abstract Syntax
    Term(..)
  , Literal(..)
    -- * Value Domain & Environment
  , Value(..)
  , Env(..)
  , emptyEnv
  , extendEnv
  , lookupEnv
    -- * Continuation Frames
  , Frame(..)
  , Cont
  , emptyCont
    -- * Machine State & Execution
  , CEKState(..)
  , stepCEK
  , evalCEK
  , runCEKWithFuel
  ) where

import Data.Text (Text)
import Data.Word (Word64)
import GHC.Generics (Generic)

-- | Primitive literal values supported by the base CEK machine.
data Literal
  = LitNat !Word64        -- ^ Natural numbers
  | LitInt !Integer       -- ^ Arbitrary-precision integers
  | LitBool !Bool         -- ^ Boolean values
  | LitText !Text         -- ^ Text literals
  deriving stock (Literal -> Literal -> Bool
(Literal -> Literal -> Bool)
-> (Literal -> Literal -> Bool) -> Eq Literal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Literal -> Literal -> Bool
== :: Literal -> Literal -> Bool
$c/= :: Literal -> Literal -> Bool
/= :: Literal -> Literal -> Bool
Eq, Int -> Literal -> ShowS
[Literal] -> ShowS
Literal -> String
(Int -> Literal -> ShowS)
-> (Literal -> String) -> ([Literal] -> ShowS) -> Show Literal
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Literal -> ShowS
showsPrec :: Int -> Literal -> ShowS
$cshow :: Literal -> String
show :: Literal -> String
$cshowList :: [Literal] -> ShowS
showList :: [Literal] -> ShowS
Show, (forall x. Literal -> Rep Literal x)
-> (forall x. Rep Literal x -> Literal) -> Generic Literal
forall x. Rep Literal x -> Literal
forall x. Literal -> Rep Literal x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Literal -> Rep Literal x
from :: forall x. Literal -> Rep Literal x
$cto :: forall x. Rep Literal x -> Literal
to :: forall x. Rep Literal x -> Literal
Generic)

-- | Core functional term syntax.
data Term
  = Var !Text             -- ^ Variable identifier
  | Lam !Text !Term       -- ^ Anonymous lambda abstraction (\(\lambda x. e\))
  | App !Term !Term       -- ^ Function application (\(e_1 \; e_2\))
  | Lit !Literal          -- ^ Embedded literal constant
  | Let !Text !Term !Term -- ^ Let-binding (@let x = e1 in e2@)
  deriving stock (Term -> Term -> Bool
(Term -> Term -> Bool) -> (Term -> Term -> Bool) -> Eq Term
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Term -> Term -> Bool
== :: Term -> Term -> Bool
$c/= :: Term -> Term -> Bool
/= :: Term -> Term -> Bool
Eq, Int -> Term -> ShowS
[Term] -> ShowS
Term -> String
(Int -> Term -> ShowS)
-> (Term -> String) -> ([Term] -> ShowS) -> Show Term
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Term -> ShowS
showsPrec :: Int -> Term -> ShowS
$cshow :: Term -> String
show :: Term -> String
$cshowList :: [Term] -> ShowS
showList :: [Term] -> ShowS
Show, (forall x. Term -> Rep Term x)
-> (forall x. Rep Term x -> Term) -> Generic Term
forall x. Rep Term x -> Term
forall x. Term -> Rep Term x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Term -> Rep Term x
from :: forall x. Term -> Rep Term x
$cto :: forall x. Rep Term x -> Term
to :: forall x. Rep Term x -> Term
Generic)

-- | Evaluated runtime values.
data Value
  = VClosure !Text !Term !Env -- ^ Lexical closure \(\langle x, e, E \rangle\)
  | VLit !Literal             -- ^ Primitive literal value
  deriving stock (Value -> Value -> Bool
(Value -> Value -> Bool) -> (Value -> Value -> Bool) -> Eq Value
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Value -> Value -> Bool
== :: Value -> Value -> Bool
$c/= :: Value -> Value -> Bool
/= :: Value -> Value -> Bool
Eq, Int -> Value -> ShowS
[Value] -> ShowS
Value -> String
(Int -> Value -> ShowS)
-> (Value -> String) -> ([Value] -> ShowS) -> Show Value
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Value -> ShowS
showsPrec :: Int -> Value -> ShowS
$cshow :: Value -> String
show :: Value -> String
$cshowList :: [Value] -> ShowS
showList :: [Value] -> ShowS
Show, (forall x. Value -> Rep Value x)
-> (forall x. Rep Value x -> Value) -> Generic Value
forall x. Rep Value x -> Value
forall x. Value -> Rep Value x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Value -> Rep Value x
from :: forall x. Value -> Rep Value x
$cto :: forall x. Rep Value x -> Value
to :: forall x. Rep Value x -> Value
Generic)

-- | Lexical variable environment mapping identifiers to values.
newtype Env = Env { Env -> [(Text, Value)]
unEnv :: [(Text, Value)] }
  deriving stock (Env -> Env -> Bool
(Env -> Env -> Bool) -> (Env -> Env -> Bool) -> Eq Env
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Env -> Env -> Bool
== :: Env -> Env -> Bool
$c/= :: Env -> Env -> Bool
/= :: Env -> Env -> Bool
Eq, Int -> Env -> ShowS
[Env] -> ShowS
Env -> String
(Int -> Env -> ShowS)
-> (Env -> String) -> ([Env] -> ShowS) -> Show Env
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Env -> ShowS
showsPrec :: Int -> Env -> ShowS
$cshow :: Env -> String
show :: Env -> String
$cshowList :: [Env] -> ShowS
showList :: [Env] -> ShowS
Show, (forall x. Env -> Rep Env x)
-> (forall x. Rep Env x -> Env) -> Generic Env
forall x. Rep Env x -> Env
forall x. Env -> Rep Env x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Env -> Rep Env x
from :: forall x. Env -> Rep Env x
$cto :: forall x. Rep Env x -> Env
to :: forall x. Rep Env x -> Env
Generic)

-- | Construct an empty lexical environment.
emptyEnv :: Env
emptyEnv :: Env
emptyEnv = [(Text, Value)] -> Env
Env []

-- | Extend an environment with a new variable-to-value binding.
extendEnv :: Text -> Value -> Env -> Env
extendEnv :: Text -> Value -> Env -> Env
extendEnv !Text
var !Value
val (Env [(Text, Value)]
bindings) = [(Text, Value)] -> Env
Env ((Text
var, Value
val) (Text, Value) -> [(Text, Value)] -> [(Text, Value)]
forall a. a -> [a] -> [a]
: [(Text, Value)]
bindings)

-- | Look up a variable in the environment.
lookupEnv :: Text -> Env -> Maybe Value
lookupEnv :: Text -> Env -> Maybe Value
lookupEnv !Text
var (Env [(Text, Value)]
bindings) = Text -> [(Text, Value)] -> Maybe Value
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
var [(Text, Value)]
bindings

-- | Individual continuation frame representing pending reduction context.
data Frame
  = FrameArg !Term !Env       -- ^ Waiting for function argument to evaluate
  | FrameFun !Value           -- ^ Waiting for function body to apply after argument value is ready
  | FrameLet !Text !Term !Env -- ^ Waiting for let-bound variable computation
  deriving stock (Frame -> Frame -> Bool
(Frame -> Frame -> Bool) -> (Frame -> Frame -> Bool) -> Eq Frame
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Frame -> Frame -> Bool
== :: Frame -> Frame -> Bool
$c/= :: Frame -> Frame -> Bool
/= :: Frame -> Frame -> Bool
Eq, Int -> Frame -> ShowS
[Frame] -> ShowS
Frame -> String
(Int -> Frame -> ShowS)
-> (Frame -> String) -> ([Frame] -> ShowS) -> Show Frame
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Frame -> ShowS
showsPrec :: Int -> Frame -> ShowS
$cshow :: Frame -> String
show :: Frame -> String
$cshowList :: [Frame] -> ShowS
showList :: [Frame] -> ShowS
Show, (forall x. Frame -> Rep Frame x)
-> (forall x. Rep Frame x -> Frame) -> Generic Frame
forall x. Rep Frame x -> Frame
forall x. Frame -> Rep Frame x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Frame -> Rep Frame x
from :: forall x. Frame -> Rep Frame x
$cto :: forall x. Rep Frame x -> Frame
to :: forall x. Rep Frame x -> Frame
Generic)

-- | Evaluation continuation stack.
type Cont = [Frame]

-- | Construct an initial empty continuation stack.
emptyCont :: Cont
emptyCont :: [Frame]
emptyCont = []

-- | Active state of the CEK abstract machine.
data CEKState
  = StateEval !Term !Env !Cont  -- ^ Evaluation state: active control term \(C\), environment \(E\), continuation \(K\)
  | StateReturn !Value !Cont    -- ^ Return state: value \(V\) being passed into continuation stack \(K\)
  deriving stock (CEKState -> CEKState -> Bool
(CEKState -> CEKState -> Bool)
-> (CEKState -> CEKState -> Bool) -> Eq CEKState
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CEKState -> CEKState -> Bool
== :: CEKState -> CEKState -> Bool
$c/= :: CEKState -> CEKState -> Bool
/= :: CEKState -> CEKState -> Bool
Eq, Int -> CEKState -> ShowS
[CEKState] -> ShowS
CEKState -> String
(Int -> CEKState -> ShowS)
-> (CEKState -> String) -> ([CEKState] -> ShowS) -> Show CEKState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CEKState -> ShowS
showsPrec :: Int -> CEKState -> ShowS
$cshow :: CEKState -> String
show :: CEKState -> String
$cshowList :: [CEKState] -> ShowS
showList :: [CEKState] -> ShowS
Show, (forall x. CEKState -> Rep CEKState x)
-> (forall x. Rep CEKState x -> CEKState) -> Generic CEKState
forall x. Rep CEKState x -> CEKState
forall x. CEKState -> Rep CEKState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. CEKState -> Rep CEKState x
from :: forall x. CEKState -> Rep CEKState x
$cto :: forall x. Rep CEKState x -> CEKState
to :: forall x. Rep CEKState x -> CEKState
Generic)

-- | Perform a single deterministic step of the CEK abstract machine.
--
-- Returns:
-- * 'Right (Just nextState)' on successful transition.
-- * 'Right Nothing' when execution terminates in a final value.
-- * 'Left err' when a runtime error (e.g. unbound variable, type mismatch) occurs.
stepCEK :: CEKState -> Either Text (Maybe CEKState)
stepCEK :: CEKState -> Either Text (Maybe CEKState)
stepCEK (StateEval Term
term Env
env [Frame]
cont) = case Term
term of
  Var Text
x -> case Text -> Env -> Maybe Value
lookupEnv Text
x Env
env of
    Just Value
val -> Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Value -> [Frame] -> CEKState
StateReturn Value
val [Frame]
cont))
    Maybe Value
Nothing  -> Text -> Either Text (Maybe CEKState)
forall a b. a -> Either a b
Left (Text
"Unbound variable in CEK environment: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
x)
  Lam Text
x Term
body ->
    Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Value -> [Frame] -> CEKState
StateReturn (Text -> Term -> Env -> Value
VClosure Text
x Term
body Env
env) [Frame]
cont))
  Lit Literal
lit ->
    Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Value -> [Frame] -> CEKState
StateReturn (Literal -> Value
VLit Literal
lit) [Frame]
cont))
  App Term
e1 Term
e2 ->
    Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Term -> Env -> [Frame] -> CEKState
StateEval Term
e1 Env
env (Term -> Env -> Frame
FrameArg Term
e2 Env
env Frame -> [Frame] -> [Frame]
forall a. a -> [a] -> [a]
: [Frame]
cont)))
  Let Text
x Term
e1 Term
e2 ->
    Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Term -> Env -> [Frame] -> CEKState
StateEval Term
e1 Env
env (Text -> Term -> Env -> Frame
FrameLet Text
x Term
e2 Env
env Frame -> [Frame] -> [Frame]
forall a. a -> [a] -> [a]
: [Frame]
cont)))

stepCEK (StateReturn Value
val [Frame]
cont) = case [Frame]
cont of
  [] -> Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe CEKState
forall a. Maybe a
Nothing -- Terminal state: computation returned final value
  (FrameArg Term
e2 Env
env : [Frame]
restCont) ->
    Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Term -> Env -> [Frame] -> CEKState
StateEval Term
e2 Env
env (Value -> Frame
FrameFun Value
val Frame -> [Frame] -> [Frame]
forall a. a -> [a] -> [a]
: [Frame]
restCont)))
  (FrameFun Value
funVal : [Frame]
restCont) -> case Value
funVal of
    VClosure Text
x Term
body Env
closureEnv ->
      let !newEnv :: Env
newEnv = Text -> Value -> Env -> Env
extendEnv Text
x Value
val Env
closureEnv
      in Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Term -> Env -> [Frame] -> CEKState
StateEval Term
body Env
newEnv [Frame]
restCont))
    VLit Literal
_ ->
      Text -> Either Text (Maybe CEKState)
forall a b. a -> Either a b
Left Text
"Type error: Attempted to apply non-function literal value"
  (FrameLet Text
x Term
e2 Env
env : [Frame]
restCont) ->
    let !newEnv :: Env
newEnv = Text -> Value -> Env -> Env
extendEnv Text
x Value
val Env
env
    in Maybe CEKState -> Either Text (Maybe CEKState)
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CEKState -> Maybe CEKState
forall a. a -> Maybe a
Just (Term -> Env -> [Frame] -> CEKState
StateEval Term
e2 Env
newEnv [Frame]
restCont))

-- | Evaluate a 'Term' to a final 'Value' under an empty environment and continuation.
evalCEK :: Term -> Either Text Value
evalCEK :: Term -> Either Text Value
evalCEK Term
term = CEKState -> Either Text Value
go (Term -> Env -> [Frame] -> CEKState
StateEval Term
term Env
emptyEnv [Frame]
emptyCont)
  where
    go :: CEKState -> Either Text Value
go CEKState
st = case CEKState -> Either Text (Maybe CEKState)
stepCEK CEKState
st of
      Left Text
err -> Text -> Either Text Value
forall a b. a -> Either a b
Left Text
err
      Right Maybe CEKState
Nothing -> case CEKState
st of
        StateReturn Value
v [] -> Value -> Either Text Value
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Value
v
        CEKState
_                -> Text -> Either Text Value
forall a b. a -> Either a b
Left Text
"Internal CEK invariant violation: Terminal state without return value"
      Right (Just CEKState
nextSt) -> CEKState -> Either Text Value
go CEKState
nextSt

-- | Fuel-bounded execution of a 'Term', returning either the computed value or fuel exhaustion.
runCEKWithFuel :: Word64 -> Term -> (Either Text Value, Word64)
runCEKWithFuel :: Word64 -> Term -> (Either Text Value, Word64)
runCEKWithFuel Word64
fuel Term
term = Word64 -> CEKState -> (Either Text Value, Word64)
forall {t}.
(Eq t, Num t) =>
t -> CEKState -> (Either Text Value, t)
go Word64
fuel (Term -> Env -> [Frame] -> CEKState
StateEval Term
term Env
emptyEnv [Frame]
emptyCont)
  where
    go :: t -> CEKState -> (Either Text Value, t)
go t
0 CEKState
_ = (Text -> Either Text Value
forall a b. a -> Either a b
Left Text
"OutOfFuel: Execution budget exhausted", t
0)
    go !t
remFuel CEKState
st = case CEKState -> Either Text (Maybe CEKState)
stepCEK CEKState
st of
      Left Text
err -> (Text -> Either Text Value
forall a b. a -> Either a b
Left Text
err, t
remFuel)
      Right Maybe CEKState
Nothing -> case CEKState
st of
        StateReturn Value
v [] -> (Value -> Either Text Value
forall a. a -> Either Text a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Value
v, t
remFuel)
        CEKState
_                -> (Text -> Either Text Value
forall a b. a -> Either a b
Left Text
"Internal CEK invariant violation", t
remFuel)
      Right (Just CEKState
nextSt) -> t -> CEKState -> (Either Text Value, t)
go (t
remFuel t -> t -> t
forall a. Num a => a -> a -> a
- t
1) CEKState
nextSt