vihaco_stdlib/execution_state/runner.rs
1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4use super::instruction_out_of_bounds;
5use super::{ExecutionState, RunState};
6use std::ops::ControlFlow;
7use vihaco_abi::word::Word;
8use vihaco_module::module::LocalModule;
9use vihaco_runtime::{Dispatch, HasProgram};
10
11/// Enter main and execute through the composite's authored Steps.
12///
13/// Devices remain in place. Instructions borrow the caller-owned module; there
14/// is no instruction clone, generated Step, or imposed effect-application policy.
15///
16/// # Errors
17/// Returns entry, checked-fetch, or authored Dispatch/Step errors. Operand and
18/// component mutations made before an error are retained.
19pub fn execute<M, I, V, Ty, Info, S>(
20 module: &LocalModule<I, V, Ty, Info>,
21 machine: &mut M,
22 arguments: &[Word],
23) -> eyre::Result<()>
24where
25 M: HasProgram<Program = ExecutionState<S>>
26 + Dispatch<LocalModule<I, V, Ty, Info>, Instruction = I>,
27{
28 machine.program_mut().start(module, arguments)?;
29 resume(module, machine)
30}
31
32/// Continue a runnable invocation until halt, root return, suspension, or error.
33///
34/// Fetch establishes the sequential continuation before the Step runs. Program
35/// instructions can replace that continuation. A fault or terminal instruction
36/// leaves its original position available through [`ExecutionState::pc()`].
37///
38/// The caller must supply the same unchanged module used to start the active
39/// invocation. This checked API validates accesses, but does not enforce module
40/// identity. After an error, earlier operand consumption and effects remain;
41/// the caller is responsible for deciding whether the invocation can resume.
42///
43/// A halted or suspended invocation returns successfully without executing any
44/// instructions. For a debugger breakpoint, use
45/// [`crate::debugger::resume_with_breaks`] to resume the suspended invocation.
46///
47/// # Errors
48/// Rejects reentrant execution, invalid running state, invalid fetches, PC
49/// overflow, or a failure returned by the authored Dispatch/Step.
50pub fn resume<M, I, V, Ty, Info, S>(
51 module: &LocalModule<I, V, Ty, Info>,
52 machine: &mut M,
53) -> eyre::Result<()>
54where
55 M: HasProgram<Program = ExecutionState<S>>
56 + Dispatch<LocalModule<I, V, Ty, Info>, Instruction = I>,
57{
58 run(
59 machine,
60 |_| Ok(()),
61 |machine, ()| {
62 execute_instruction(module, machine, None)?;
63 Ok(ControlFlow::Continue(()))
64 },
65 )
66}
67
68/// Drive an invocation with caller-defined initialization and iteration policy.
69///
70/// After rejecting reentrant execution, calls `initialize` once, including for
71/// halted or suspended invocations. The returned state is passed to `step` on
72/// each iteration while the program is [`RunState::Runnable`]. Returning
73/// [`ControlFlow::Break`] ends this call without changing the program's run
74/// state. Use [`execute_instruction`] inside `step` for checked fetch/dispatch.
75///
76/// Call [`ExecutionState::start`] before running a new invocation. Initialization
77/// can inspect a suspended invocation and call [`ExecutionState::resume_at`] to
78/// continue it. The execution guard is released on both success and returned
79/// errors; unwinding through a panic does not release it. Device mutations are
80/// retained, so the caller chooses whether an error can be retried.
81///
82/// # Errors
83/// Rejects reentrant execution and propagates initialization or step errors.
84pub fn run<M, S, State>(
85 machine: &mut M,
86 initialize: impl FnOnce(&mut M) -> eyre::Result<State>,
87 mut step: impl FnMut(&mut M, &mut State) -> eyre::Result<ControlFlow<()>>,
88) -> eyre::Result<()>
89where
90 M: HasProgram<Program = ExecutionState<S>>,
91{
92 let program = machine.program_mut();
93 eyre::ensure!(
94 !program.executing,
95 "program execution is already in progress"
96 );
97 program.executing = true;
98 let result = (|| {
99 let mut state = initialize(machine)?;
100 while matches!(machine.program().run_state, RunState::Runnable) {
101 if step(machine, &mut state)?.is_break() {
102 break;
103 }
104 }
105 Ok(())
106 })();
107 machine.program_mut().executing = false;
108 result
109}
110
111/// Fetch and dispatch one instruction with the standard PC and error semantics.
112///
113/// Requires a runnable invocation with an active frame. Fetch checks the PC
114/// against `module.code`, then advances it before calling the authored dispatch.
115/// On a dispatch error, halt, or suspension, the PC is restored to the fetched
116/// position. Other stack, frame, and device mutations are retained.
117///
118/// `instruction_override` replaces the fetched instruction for this dispatch
119/// only. The PC must still address a valid module instruction. The debugger
120/// uses this to execute a gutter breakpoint's displaced instruction without
121/// removing the installed trap. Pass `None` for ordinary instruction fetching.
122///
123/// This helper does not acquire the execution guard itself. Custom runners
124/// should call it inside [`run`] and supply the invocation's original module.
125///
126/// # Errors
127/// Rejects a non-runnable invocation, missing frame, invalid PC, or PC overflow,
128/// and propagates dispatch errors.
129pub fn execute_instruction<M, I, V, Ty, Info, S>(
130 module: &LocalModule<I, V, Ty, Info>,
131 machine: &mut M,
132 instruction_override: Option<&I>,
133) -> eyre::Result<()>
134where
135 M: HasProgram<Program = ExecutionState<S>>
136 + Dispatch<LocalModule<I, V, Ty, Info>, Instruction = I>,
137{
138 let program = machine.program_mut();
139 program.ensure_running()?;
140 let position = program.pc;
141 let fetched = module
142 .code
143 .get(position as usize)
144 .ok_or_else(|| instruction_out_of_bounds(position, module.code.len()))?;
145 let instruction = instruction_override.unwrap_or(fetched);
146 program.pc = position
147 .checked_add(1)
148 .ok_or_else(|| eyre::eyre!("program counter overflow"))?;
149 let result = machine.dispatch(instruction, module);
150 let program = machine.program_mut();
151 if result.is_err() || !matches!(program.run_state, RunState::Runnable) {
152 program.pc = position;
153 }
154 result
155}