vihaco_stdlib/execution_state.rs
1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Checked invocation state and execution of an independently owned module.
5//!
6//! The host owns program data. `ExecutionState` owns frames, locals, operands,
7//! the private PC, and execution flags. A runner borrows both the module and the
8//! machine; instructions borrow the module while authored Steps mutate devices.
9//! Component authors choose messages/effects, without implementing stack logic.
10//! Custom drivers can wrap [`run`] and [`execute_instruction`] to change
11//! initialization, instruction selection, and when control returns to the host.
12//!
13//! ```
14//! use vihaco_abi::{Type, Value};
15//! use vihaco_module::module::{LocalModule, FunctionInfo, Signature};
16//! use vihaco_runtime::{composite, field, Apply, BuildMessage, ReusableMessageRecipe, Execute, HasInstructionSet, Step};
17//! use vihaco_stdlib::{ExecutionState, Image, execution_state::execute, program::program};
18//! use vihaco_cpu::{CPU, cpu};
19//!
20//! #[composite]
21//! struct Machine {
22//! #[device(0)] #[program] execution: vihaco_stdlib::ExecutionState,
23//! #[device(1)] cpu: vihaco_cpu::CPU,
24//! }
25//! type Instruction = <Machine as HasInstructionSet>::Runtime;
26//! type Program = LocalModule<Instruction, Value, Type>;
27//!
28//! impl<I, M> BuildMessage<field!(Machine::execution), I, Program, M> for Machine
29//! where
30//! ExecutionState: Execute<I, Message = M>,
31//! M: ReusableMessageRecipe<Self, field!(Machine::execution), I, Program>,
32//! {
33//! fn build_message(&mut self, instruction: &I, context: &Program) -> eyre::Result<M> {
34//! <M as ReusableMessageRecipe<Self, field!(Machine::execution), I, Program>>::prepare(
35//! self, instruction, context,
36//! )
37//! }
38//! }
39//!
40//! impl<I, M> BuildMessage<field!(Machine::cpu), I, Program, M> for Machine
41//! where
42//! CPU: Execute<I, Message = M>,
43//! M: ReusableMessageRecipe<Self, field!(Machine::cpu), I, Program>,
44//! {
45//! fn build_message(&mut self, instruction: &I, context: &Program) -> eyre::Result<M> {
46//! <M as ReusableMessageRecipe<Self, field!(Machine::cpu), I, Program>>::prepare(
47//! self, instruction, context,
48//! )
49//! }
50//! }
51//!
52//! impl<I> Step<field!(Machine::execution), I, Program> for Machine
53//! where
54//! ExecutionState: Execute<I, Effect = (), Error = eyre::Report>,
55//! Self: BuildMessage<field!(Machine::execution), I, Program>,
56//! {
57//! fn step(&mut self, instruction: &I, module: &Program) -> eyre::Result<()> {
58//! let message = <Self as BuildMessage<field!(Machine::execution), I, Program>>
59//! ::build_message(self, instruction, module)?;
60//! self.execution.execute(instruction, message)
61//! }
62//! }
63//! impl<I> Step<field!(Machine::cpu), I, Program> for Machine
64//! where
65//! CPU: Execute<I, Error = eyre::Report>,
66//! Self: BuildMessage<field!(Machine::cpu), I, Program>,
67//! ExecutionState: Apply<<CPU as Execute<I>>::Effect>,
68//! {
69//! fn step(&mut self, instruction: &I, module: &Program) -> eyre::Result<()> {
70//! let message = <Self as BuildMessage<field!(Machine::cpu), I, Program>>
71//! ::build_message(self, instruction, module)?;
72//! let effect = self.cpu.execute(instruction, message)?;
73//! self.execution.apply(effect);
74//! Ok(())
75//! }
76//! }
77//!
78//! let module: Program = LocalModule {
79//! code: vec![
80//! Instruction::V_execution__program__ConstU64(program::ConstU64(20)),
81//! Instruction::V_execution__program__ConstU64(program::ConstU64(22)),
82//! Instruction::V_cpu__cpu__AddU64(cpu::AddU64),
83//! Instruction::V_execution__program__Return(program::Return(1)),
84//! ],
85//! main_function: Some(0),
86//! functions: vec![FunctionInfo {
87//! name: 0, signature: Signature { params: vec![], ret: vec![Type::U64] },
88//! local_count: 0, start_address: 0, end_address: 4, file: 0,
89//! }],
90//! ..Default::default()
91//! };
92//! // An ordinary outer owner keeps immutable program data beside its machine.
93//! struct Loaded {
94//! image: Image<Instruction>,
95//! machine: Machine,
96//! }
97//! impl Loaded {
98//! fn run(&mut self) -> eyre::Result<()> {
99//! execute(&self.image.module, &mut self.machine, &[])
100//! }
101//! }
102//! let mut loaded = Loaded {
103//! image: Image::new(module),
104//! machine: Machine { execution: ExecutionState::new(), cpu: CPU::default() },
105//! };
106//! loaded.run()?;
107//! assert_eq!(loaded.machine.execution.stack(), &[42]);
108//! # Ok::<(), eyre::Report>(())
109//! ```
110use crate::program::program;
111use vihaco_abi::{frame::Frame, word::Word};
112use vihaco_module::module::LocalModule;
113
114mod execution;
115mod messages;
116pub(crate) mod runner;
117mod storage;
118
119pub use runner::{execute, execute_instruction, resume, run};
120
121/// No custom execution state is available. By using this for the
122/// default in [`RunState`], we can get exhaustive pattern matching
123/// for `Runnable` and `Halted` by default.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum NoCustomState {}
126
127/// Whether an invocation can execute its next instruction.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum RunState<S = NoCustomState> {
130 Runnable,
131 Halted,
132 Other(S),
133}
134
135#[vihaco_runtime::component]
136#[instructions { program }]
137/// Frames, locals, operands, and private execution state for one invocation.
138///
139/// The module is supplied by reference at entry and is never stored here.
140#[derive(Debug)]
141pub struct ExecutionState<S = NoCustomState> {
142 stack: Vec<Word>,
143 frames: Vec<Frame>,
144 pc: u32,
145 run_state: RunState<S>,
146 executing: bool,
147}
148
149impl<S> Default for ExecutionState<S> {
150 fn default() -> Self {
151 Self {
152 stack: Vec::new(),
153 frames: Vec::new(),
154 pc: 0,
155 run_state: RunState::Halted,
156 executing: false,
157 }
158 }
159}
160
161impl ExecutionState {
162 pub fn new() -> Self {
163 Self::default()
164 }
165}
166
167impl<S: Clone> Clone for ExecutionState<S> {
168 fn clone(&self) -> Self {
169 Self {
170 stack: self.stack.clone(),
171 frames: self.frames.clone(),
172 pc: self.pc,
173 run_state: self.run_state.clone(),
174 executing: false,
175 }
176 }
177}
178
179#[cold]
180#[inline(never)]
181fn instruction_out_of_bounds(pc: u32, len: usize) -> eyre::Report {
182 eyre::eyre!("instruction index out of bounds: {} (max {})", pc, len)
183}
184
185fn function_entry<I, V, Ty, Info>(
186 module: &LocalModule<I, V, Ty, Info>,
187 index: usize,
188) -> eyre::Result<(usize, usize, u32)> {
189 let function = module
190 .functions
191 .get(index)
192 .ok_or_else(|| unknown_function(index))?;
193 if (function.local_count as usize) < function.signature.params.len() {
194 return Err(invalid_local_count());
195 }
196 if (function.start_address as usize) >= module.code.len() {
197 return Err(invalid_call_target());
198 }
199 Ok((
200 function.signature.params.len(),
201 function.local_count as usize,
202 function.start_address,
203 ))
204}
205
206#[cold]
207#[inline(never)]
208fn unknown_function(index: usize) -> eyre::Report {
209 eyre::eyre!("unknown function reference {index}")
210}
211
212#[cold]
213#[inline(never)]
214fn invalid_local_count() -> eyre::Report {
215 eyre::eyre!("local count must be at least arity")
216}
217
218#[cold]
219#[inline(never)]
220fn invalid_call_target() -> eyre::Report {
221 eyre::eyre!("call target out of bounds")
222}