Skip to main content

logicaffeine_tv/
symexec.rs

1//! Big-step symbolic execution of the LOGOS Verifiable Core into `VerifyExpr`.
2//!
3//! The executor walks the AST and produces a [`SymSummary`]: the ordered sequence of
4//! `Show` outputs and a sticky "an observable error occurred" condition, each expressed
5//! as a `VerifyExpr` over the program's free inputs. Two summaries can then be compared
6//! for observable equivalence by the SMT backend ([`crate::equiv`]).
7//!
8//! ## Verifiable Core (this phase)
9//!
10//! Straight-line `Int`/`Bool` programs: integer literals, booleans, `+ - *`, signed
11//! comparisons, `== !=`, `and`/`or` (logical on `Bool`, bitwise on `Int`), `not`,
12//! `Let`, `Set`, and `Show … to show`. `Int` is modeled as a 64-bit bitvector so
13//! wrapping/overflow matches the interpreter's native `i64`. Anything outside the
14//! fragment yields [`Unsupported`] — never a silent or wrong result.
15
16use std::collections::{HashMap, VecDeque};
17
18use logicaffeine_compile::ast::stmt::{BinaryOpKind, Block, Expr, Literal, SelectBranch, Stmt};
19use logicaffeine_compile::Interner;
20use logicaffeine_verify::{BitVecOp, VerifyExpr};
21
22/// The non-native functions a program defines, keyed by name → (parameter names, body).
23/// Used to inline a `Launch a task to f(args)` at its spawn point in the determinate model.
24type FuncTable<'a> = HashMap<String, (Vec<String>, Block<'a>)>;
25
26/// SplitMix64 — a byte-for-byte mirror of `logicaffeine_runtime::seed::SeededRng`, so a
27/// `Select` winner the encoder draws matches the winner the interpreter's scheduler drew at
28/// the same seed. (Kept private and re-derived here to honor invariant I6: the TV crate
29/// shares the *spec* of the choice function, not a code path linked into any binary.)
30struct SplitMix64 {
31    state: u64,
32}
33
34impl SplitMix64 {
35    fn new(seed: u64) -> Self {
36        SplitMix64 { state: seed }
37    }
38
39    fn next_u64(&mut self) -> u64 {
40        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
41        let mut z = self.state;
42        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
43        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
44        z ^ (z >> 31)
45    }
46
47    /// A uniform index in `[0, n)`. Returns 0 *without drawing* when `n <= 1` — matching the
48    /// runtime exactly, so the entropy stream stays in lockstep.
49    fn below(&mut self, n: usize) -> usize {
50        if n <= 1 {
51            return 0;
52        }
53        (self.next_u64() % n as u64) as usize
54    }
55}
56
57/// Bit width used to model LOGOS `Int` (native `i64`).
58pub const INT_WIDTH: u32 = 64;
59
60/// A symbolic LOGOS value: an integer (64-bit bitvector), a boolean, or a channel handle.
61#[derive(Debug, Clone)]
62pub enum SymValue {
63    /// An integer value, as a width-64 bitvector `VerifyExpr`.
64    Int(VerifyExpr),
65    /// A boolean value, as a `Bool`-sorted `VerifyExpr`.
66    Bool(VerifyExpr),
67    /// A channel handle — an opaque id into `State::channels`. Not an SMT value; it is
68    /// the dataflow conduit the determinate concurrency fragment threads `Send`/`Receive`
69    /// through (and passes as a task argument).
70    Chan(usize),
71}
72
73/// The observable summary of a program: the ordered `Show` outputs plus the condition
74/// under which the program raised an observable error.
75#[derive(Debug, Clone)]
76pub struct SymSummary {
77    /// Ordered `Show` emissions, in execution order.
78    pub outputs: Vec<SymValue>,
79    /// Sticky condition (a `Bool` `VerifyExpr`) that is true exactly when the program
80    /// raised an observable error (e.g. division by zero).
81    pub errored: VerifyExpr,
82}
83
84/// A construct outside the currently-supported Verifiable Core. Carries a human reason
85/// so the validator can report `Unverified(reason)` rather than ever guessing.
86#[derive(Debug, Clone)]
87pub struct Unsupported(pub String);
88
89fn unsupported<T>(reason: impl Into<String>) -> Result<T, Unsupported> {
90    Err(Unsupported(reason.into()))
91}
92
93/// Mutable symbolic-execution state threaded through a straight-line block.
94struct State {
95    env: HashMap<String, SymValue>,
96    outputs: Vec<SymValue>,
97    errored: VerifyExpr,
98    /// Channel buffers, keyed by the opaque id a [`SymValue::Chan`] carries (FIFO histories).
99    channels: HashMap<usize, VecDeque<SymValue>>,
100    /// Allocates the next channel id, so distinct `Pipe`s never alias.
101    chan_counter: usize,
102    /// Present in *seeded* mode: resolves `Select` winners from the same SplitMix64 stream
103    /// the interpreter's scheduler uses. `None` ⇒ `Select` is `Unsupported` (no entropy).
104    rng: Option<SplitMix64>,
105}
106
107impl State {
108    fn new() -> Self {
109        State {
110            env: HashMap::new(),
111            outputs: Vec::new(),
112            errored: VerifyExpr::bool(false),
113            channels: HashMap::new(),
114            chan_counter: 0,
115            rng: None,
116        }
117    }
118}
119
120/// Symbolically execute a program (a sequence of statements) into a [`SymSummary`].
121pub fn execute(stmts: &[Stmt], interner: &Interner) -> Result<SymSummary, Unsupported> {
122    let funcs = collect_funcs(stmts, interner);
123    let mut state = State::new();
124    exec_block(&mut state, stmts, interner, &funcs)?;
125    Ok(SymSummary {
126        outputs: state.outputs,
127        errored: state.errored,
128    })
129}
130
131/// Symbolically execute a *nondeterministic* program under a fixed `seed`, resolving every
132/// `Select` winner from a SplitMix64 mirror of the scheduler's choice function. The result
133/// is cross-checked per-seed against `run_treewalker_concurrent_seeded` at the same seed,
134/// so a misaligned encoding surfaces as a disagreement — never a false proof.
135pub fn execute_seeded(
136    stmts: &[Stmt],
137    interner: &Interner,
138    seed: u64,
139) -> Result<SymSummary, Unsupported> {
140    let funcs = collect_funcs(stmts, interner);
141    let mut state = State::new();
142    state.rng = Some(SplitMix64::new(seed));
143    exec_block(&mut state, stmts, interner, &funcs)?;
144    Ok(SymSummary {
145        outputs: state.outputs,
146        errored: state.errored,
147    })
148}
149
150/// Index the program's non-native function definitions for task inlining.
151fn collect_funcs<'a>(stmts: &'a [Stmt<'a>], interner: &Interner) -> FuncTable<'a> {
152    let mut table = FuncTable::new();
153    for stmt in stmts {
154        if let Stmt::FunctionDef {
155            name,
156            params,
157            body,
158            is_native: false,
159            ..
160        } = stmt
161        {
162            let param_names = params
163                .iter()
164                .map(|(p, _)| interner.resolve(*p).to_string())
165                .collect();
166            table.insert(interner.resolve(*name).to_string(), (param_names, *body));
167        }
168    }
169    table
170}
171
172fn exec_block(
173    state: &mut State,
174    stmts: &[Stmt],
175    interner: &Interner,
176    funcs: &FuncTable,
177) -> Result<(), Unsupported> {
178    for stmt in stmts {
179        exec_stmt(state, stmt, interner, funcs)?;
180    }
181    Ok(())
182}
183
184/// Resolve a pipe expression to its channel id, or report why it is not a channel.
185fn resolve_chan(state: &mut State, expr: &Expr, interner: &Interner) -> Result<usize, Unsupported> {
186    match eval(state, expr, interner)? {
187        SymValue::Chan(id) => Ok(id),
188        _ => unsupported("pipe operand is not a channel"),
189    }
190}
191
192fn exec_stmt(
193    state: &mut State,
194    stmt: &Stmt,
195    interner: &Interner,
196    funcs: &FuncTable,
197) -> Result<(), Unsupported> {
198    match stmt {
199        // Definitions are indexed up front by `collect_funcs`; nothing to execute here.
200        Stmt::FunctionDef { .. } => Ok(()),
201        // ---- Determinate concurrency fragment ----
202        Stmt::CreatePipe { var, .. } => {
203            let id = state.chan_counter;
204            state.chan_counter += 1;
205            state.channels.insert(id, VecDeque::new());
206            state
207                .env
208                .insert(interner.resolve(*var).to_string(), SymValue::Chan(id));
209            Ok(())
210        }
211        Stmt::SendPipe { value, pipe } => {
212            let v = eval(state, value, interner)?;
213            let id = resolve_chan(state, pipe, interner)?;
214            state
215                .channels
216                .get_mut(&id)
217                .expect("channel id is allocated")
218                .push_back(v);
219            Ok(())
220        }
221        Stmt::ReceivePipe { var, pipe } => {
222            let id = resolve_chan(state, pipe, interner)?;
223            let v = match state.channels.get_mut(&id).and_then(|q| q.pop_front()) {
224                Some(v) => v,
225                // A receive on an empty channel cannot be statically resolved under the
226                // single modeled schedule — bail honestly rather than guess.
227                None => {
228                    return unsupported("receive on an empty channel (not statically resolvable)")
229                }
230            };
231            state.env.insert(interner.resolve(*var).to_string(), v);
232            Ok(())
233        }
234        // A launched task runs to completion at its spawn point: in the determinate fragment
235        // the output is schedule-independent (Kahn), so this single schedule is canonical.
236        // Its `Send`s fill shared channels; a `Receive` it cannot satisfy bails Unsupported.
237        Stmt::LaunchTask { function, args } => {
238            let fname = interner.resolve(*function).to_string();
239            let (params, body) = match funcs.get(&fname) {
240                Some(f) => f.clone(),
241                None => return unsupported(format!("launch of unknown task '{fname}'")),
242            };
243            if params.len() != args.len() {
244                return unsupported(format!("task '{fname}' arity mismatch"));
245            }
246            let arg_vals = args
247                .iter()
248                .map(|a| eval(state, a, interner))
249                .collect::<Result<Vec<_>, _>>()?;
250            let saved = std::mem::take(&mut state.env);
251            for (p, v) in params.iter().zip(arg_vals) {
252                state.env.insert(p.clone(), v);
253            }
254            let r = exec_block(state, body, interner, funcs);
255            state.env = saved;
256            r
257        }
258        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
259            // Sequential in the determinate spec — each task runs without a block scope.
260            exec_block(state, tasks, interner, funcs)
261        }
262        // `Await the first of:` — nondeterministic, so only modeled in seeded mode. Ready
263        // arms are the `Receive`s whose channel already holds a value (readiness is static
264        // once prior tasks have run eagerly); the winner is `below(ready_count)` drawn from
265        // the same SplitMix64 the scheduler uses. With no ready receive, the timeout arm
266        // fires (deterministic, no draw). The per-seed cross-check is the soundness net.
267        Stmt::Select { branches } => {
268            if state.rng.is_none() {
269                return unsupported("Select requires seeded mode (nondeterministic)");
270            }
271            // Indices of receive arms whose modeled channel is non-empty.
272            let mut ready: Vec<usize> = Vec::new();
273            for (i, b) in branches.iter().enumerate() {
274                if let SelectBranch::Receive { pipe, .. } = b {
275                    let id = resolve_chan(state, pipe, interner)?;
276                    if state
277                        .channels
278                        .get(&id)
279                        .map(|q| !q.is_empty())
280                        .unwrap_or(false)
281                    {
282                        ready.push(i);
283                    }
284                }
285            }
286            let winner = if !ready.is_empty() {
287                let k = state.rng.as_mut().unwrap().below(ready.len());
288                ready[k]
289            } else {
290                // No receive ready ⇒ the timeout arm fires. Find the first one.
291                match branches
292                    .iter()
293                    .position(|b| matches!(b, SelectBranch::Timeout { .. }))
294                {
295                    Some(i) => i,
296                    None => {
297                        return unsupported("Select with no ready arm and no timeout would block")
298                    }
299                }
300            };
301            match &branches[winner] {
302                SelectBranch::Receive { var, pipe, body } => {
303                    let id = resolve_chan(state, pipe, interner)?;
304                    let v = state
305                        .channels
306                        .get_mut(&id)
307                        .and_then(|q| q.pop_front())
308                        .ok_or_else(|| Unsupported("Select winner channel empty".into()))?;
309                    state.env.insert(interner.resolve(*var).to_string(), v);
310                    exec_block(state, body, interner, funcs)
311                }
312                SelectBranch::Timeout { body, .. } => exec_block(state, body, interner, funcs),
313            }
314        }
315        Stmt::Let { var, value, .. } => {
316            let v = eval(state, value, interner)?;
317            state.env.insert(interner.resolve(*var).to_string(), v);
318            Ok(())
319        }
320        Stmt::Set { target, value } => {
321            let name = interner.resolve(*target).to_string();
322            if !state.env.contains_key(&name) {
323                return unsupported(format!("Set to variable '{name}' not in scope"));
324            }
325            let v = eval(state, value, interner)?;
326            state.env.insert(name, v);
327            Ok(())
328        }
329        Stmt::Show { object, recipient } => {
330            // Only `Show <expr> to show` (console) is in-fragment; showing to a
331            // function is an effectful call we do not model yet.
332            if let Expr::Identifier(sym) = recipient {
333                if interner.resolve(*sym) == "show" {
334                    let v = eval(state, object, interner)?;
335                    state.outputs.push(v);
336                    return Ok(());
337                }
338            }
339            unsupported("Show to a non-console recipient")
340        }
341        other => unsupported(format!("statement {}", stmt_kind(other))),
342    }
343}
344
345fn eval(state: &mut State, expr: &Expr, interner: &Interner) -> Result<SymValue, Unsupported> {
346    match expr {
347        Expr::Literal(Literal::Number(n)) => {
348            Ok(SymValue::Int(VerifyExpr::bv_const(INT_WIDTH, *n as u64)))
349        }
350        Expr::Literal(Literal::Boolean(b)) => Ok(SymValue::Bool(VerifyExpr::bool(*b))),
351        Expr::Literal(_) => unsupported("non-Int/Bool literal"),
352        Expr::Identifier(sym) => {
353            let name = interner.resolve(*sym);
354            state
355                .env
356                .get(name)
357                .cloned()
358                .ok_or_else(|| Unsupported(format!("reference to unbound variable '{name}'")))
359        }
360        Expr::BinaryOp { op, left, right } => {
361            let l = eval(state, left, interner)?;
362            let r = eval(state, right, interner)?;
363            match op {
364                // Division / modulo: by-zero is an observable error in the interpreter,
365                // so record `divisor == 0` into the sticky error condition. The result
366                // value past that point is irrelevant (observable equivalence only
367                // compares outputs when neither side errored).
368                BinaryOpKind::Divide | BinaryOpKind::Modulo => {
369                    let (a, b) = match (l, r) {
370                        (SymValue::Int(a), SymValue::Int(b)) => (a, b),
371                        _ => return unsupported("division on non-Int operands"),
372                    };
373                    let div_by_zero = VerifyExpr::bv_binary(
374                        BitVecOp::Eq,
375                        b.clone(),
376                        VerifyExpr::bv_const(INT_WIDTH, 0),
377                    );
378                    state.errored = VerifyExpr::or(state.errored.clone(), div_by_zero);
379                    let bvop = if matches!(op, BinaryOpKind::Divide) {
380                        BitVecOp::SDiv
381                    } else {
382                        BitVecOp::SRem
383                    };
384                    Ok(SymValue::Int(VerifyExpr::bv_binary(bvop, a, b)))
385                }
386                _ => apply_binop(*op, l, r),
387            }
388        }
389        Expr::Not { operand } => match eval(state, operand, interner)? {
390            SymValue::Bool(e) => Ok(SymValue::Bool(VerifyExpr::not(e))),
391            // Bitwise NOT on an i64: ~x = x XOR 0xFFFF_FFFF_FFFF_FFFF.
392            SymValue::Int(e) => Ok(SymValue::Int(VerifyExpr::bv_binary(
393                BitVecOp::Xor,
394                e,
395                VerifyExpr::bv_const(INT_WIDTH, u64::MAX),
396            ))),
397            SymValue::Chan(_) => unsupported("`not` on a channel"),
398        },
399        other => unsupported(format!("expression {}", expr_kind(other))),
400    }
401}
402
403fn apply_binop(op: BinaryOpKind, l: SymValue, r: SymValue) -> Result<SymValue, Unsupported> {
404    use BinaryOpKind::*;
405    use SymValue::{Bool, Int};
406    match (op, l, r) {
407        // ---- Integer arithmetic (wrapping, two's complement) ----
408        (Add, Int(a), Int(b)) => Ok(Int(VerifyExpr::bv_binary(BitVecOp::Add, a, b))),
409        (Subtract, Int(a), Int(b)) => Ok(Int(VerifyExpr::bv_binary(BitVecOp::Sub, a, b))),
410        (Multiply, Int(a), Int(b)) => Ok(Int(VerifyExpr::bv_binary(BitVecOp::Mul, a, b))),
411
412        // ---- Signed integer comparison ----
413        (Lt, Int(a), Int(b)) => Ok(Bool(VerifyExpr::bv_binary(BitVecOp::SLt, a, b))),
414        (Gt, Int(a), Int(b)) => Ok(Bool(VerifyExpr::bv_binary(BitVecOp::SLt, b, a))),
415        (LtEq, Int(a), Int(b)) => Ok(Bool(VerifyExpr::bv_binary(BitVecOp::SLe, a, b))),
416        (GtEq, Int(a), Int(b)) => Ok(Bool(VerifyExpr::bv_binary(BitVecOp::SLe, b, a))),
417
418        // ---- Equality (Int via bv, Bool via iff) ----
419        (Eq, Int(a), Int(b)) => Ok(Bool(VerifyExpr::bv_binary(BitVecOp::Eq, a, b))),
420        (Eq, Bool(a), Bool(b)) => Ok(Bool(VerifyExpr::iff(a, b))),
421        (NotEq, Int(a), Int(b)) => Ok(Bool(VerifyExpr::not(VerifyExpr::bv_binary(
422            BitVecOp::Eq,
423            a,
424            b,
425        )))),
426        (NotEq, Bool(a), Bool(b)) => Ok(Bool(VerifyExpr::not(VerifyExpr::iff(a, b)))),
427
428        // ---- And / Or (logical on Bool, bitwise on Int — matches the interpreter) ----
429        (And, Bool(a), Bool(b)) => Ok(Bool(VerifyExpr::and(a, b))),
430        (And, Int(a), Int(b)) => Ok(Int(VerifyExpr::bv_binary(BitVecOp::And, a, b))),
431        (Or, Bool(a), Bool(b)) => Ok(Bool(VerifyExpr::or(a, b))),
432        (Or, Int(a), Int(b)) => Ok(Int(VerifyExpr::bv_binary(BitVecOp::Or, a, b))),
433
434        (op, _, _) => unsupported(format!("operator {op:?} on these operand types")),
435    }
436}
437
438fn stmt_kind(s: &Stmt) -> &'static str {
439    match s {
440        Stmt::If { .. } => "If",
441        Stmt::While { .. } => "While",
442        Stmt::Repeat { .. } => "Repeat",
443        Stmt::Return { .. } => "Return",
444        Stmt::Inspect { .. } => "Inspect",
445        Stmt::FunctionDef { .. } => "FunctionDef",
446        Stmt::Call { .. } => "Call",
447        _ => "<other>",
448    }
449}
450
451fn expr_kind(e: &Expr) -> &'static str {
452    match e {
453        Expr::Call { .. } => "Call",
454        Expr::Index { .. } => "Index",
455        Expr::FieldAccess { .. } => "FieldAccess",
456        Expr::List(_) => "List",
457        Expr::InterpolatedString(_) => "InterpolatedString",
458        _ => "<other>",
459    }
460}