Skip to main content

vihaco_stdlib/execution_state/
storage.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Checked word backing for frame locals and typed operands.
5
6use super::{ExecutionState, RunState, function_entry};
7use vihaco_abi::{frame::Frame, traits::Reset, word::*};
8use vihaco_module::module::LocalModule;
9use vihaco_module::{PopStack, PushStack};
10
11impl<S> ExecutionState<S> {
12    /// Inspect the running state without changing it.
13    pub fn run_state(&self) -> &RunState<S> {
14        &self.run_state
15    }
16
17    /// Materialized locals and operands, or results after the outermost return.
18    pub fn stack(&self) -> &[Word] {
19        &self.stack
20    }
21
22    /// Active call frames, from main to the current function.
23    pub fn frames(&self) -> &[Frame] {
24        &self.frames
25    }
26
27    /// True before entry, after Halt, or after the outermost return.
28    pub fn is_halted(&self) -> bool {
29        matches!(self.run_state, RunState::Halted)
30    }
31
32    /// Enter main using its module metadata and host-supplied arguments.
33    ///
34    /// Entry creates the outermost frame, zeroes non-argument locals, selects
35    /// the function's first instruction, and sets the run state to runnable.
36    /// A halted invocation can be replaced while reusing allocated storage.
37    ///
38    /// # Errors
39    /// Rejects an active invocation, invalid metadata/target, a wrong argument
40    /// count, or allocation failure, preserving the preceding logical state.
41    pub fn start<I, V, Ty, Info>(
42        &mut self,
43        module: &LocalModule<I, V, Ty, Info>,
44        arguments: &[Word],
45    ) -> eyre::Result<()> {
46        eyre::ensure!(
47            matches!(self.run_state, RunState::Halted) && !self.executing,
48            "a function is already active"
49        );
50        let function = module
51            .main_function
52            .ok_or_else(|| eyre::eyre!("module has no main function"))?;
53        let (arity, locals, target) = function_entry(module, function as usize)?;
54        eyre::ensure!(arguments.len() == arity, "entry argument count mismatch");
55        self.stack
56            .try_reserve(locals.saturating_sub(self.stack.len()))?;
57        if self.frames.capacity() == 0 {
58            self.frames.try_reserve(1)?;
59        }
60        self.stack.clear();
61        self.stack.extend_from_slice(arguments);
62        self.stack.resize(locals, 0);
63        self.frames.clear();
64        self.frames.push(Frame {
65            base: 0,
66            local_count: locals,
67            // Frame's shared record retains this legacy field; this path does
68            // not track source spans or implement a Span instruction.
69            span: (0, 0, 0),
70            function: Some(function as usize),
71            ret_pc: 0,
72        });
73        self.pc = target;
74        self.run_state = RunState::Runnable;
75        Ok(())
76    }
77
78    /// Current continuation, or the fault/terminal position after execution stops.
79    pub fn pc(&self) -> u32 {
80        self.pc
81    }
82
83    /// Select a continuation and make the invocation runnable.
84    ///
85    /// Intended for custom runners resuming a suspended invocation. This does
86    /// not create a frame or validate `pc`; the caller must retain the active
87    /// invocation and choose a position in its original module. The next
88    /// [`super::execute_instruction`] call checks the frame and fetch position.
89    pub fn resume_at(&mut self, pc: u32) {
90        self.pc = pc;
91        self.run_state = RunState::Runnable;
92    }
93
94    /// Suspend the invocation with component-specific state.
95    ///
96    /// A component's effect handler can use this to stop the shared runner.
97    /// During dispatch, the runner restores the PC to the current instruction;
98    /// save any desired continuation in `state` before suspending. A custom
99    /// runner can later inspect [`Self::run_state`] and call [`Self::resume_at`].
100    pub fn suspend(&mut self, state: S) {
101        self.run_state = RunState::Other(state);
102    }
103
104    #[inline(always)]
105    pub(super) fn ensure_running(&self) -> eyre::Result<()> {
106        eyre::ensure!(
107            matches!(self.run_state, RunState::Runnable) && !self.frames.is_empty(),
108            "program is not running"
109        );
110        Ok(())
111    }
112
113    #[inline]
114    pub(super) fn require_operands(&self, count: usize) -> eyre::Result<()> {
115        self.ensure_running()?;
116        let frame = self
117            .frames
118            .last()
119            .ok_or_else(|| eyre::eyre!("no current frame"))?;
120        eyre::ensure!(
121            self.stack.len().saturating_sub(frame.operands_index()) >= count,
122            "stack underflow"
123        );
124        Ok(())
125    }
126
127    #[inline]
128    pub(super) fn peek_operand(&self) -> eyre::Result<Word> {
129        self.require_operands(1)?;
130        self.stack
131            .last()
132            .copied()
133            .ok_or_else(|| eyre::eyre!("stack underflow"))
134    }
135
136    #[inline]
137    pub(super) fn local_address(&self, index: u32) -> eyre::Result<usize> {
138        self.ensure_running()?;
139        let frame = self
140            .frames
141            .last()
142            .ok_or_else(|| eyre::eyre!("no current frame"))?;
143        eyre::ensure!(
144            (index as usize) < frame.local_count,
145            "local index out of bounds"
146        );
147        let address = frame
148            .base
149            .checked_add(index as usize)
150            .ok_or_else(|| eyre::eyre!("local address overflow"))?;
151        eyre::ensure!(address < self.stack.len(), "local index out of bounds");
152        Ok(address)
153    }
154}
155
156impl<S> Reset for ExecutionState<S> {
157    fn reset(&mut self) {
158        self.stack.clear();
159        self.frames.clear();
160        self.pc = 0;
161        self.run_state = RunState::Halted;
162    }
163}
164
165impl<S> PopStack<Word> for ExecutionState<S> {
166    #[inline]
167    fn pop(&mut self) -> eyre::Result<Word> {
168        self.require_operands(1)?;
169        self.stack
170            .pop()
171            .ok_or_else(|| eyre::eyre!("stack underflow"))
172    }
173}
174
175// Insertion is storage plumbing, not execution: it never starts an invocation
176// or changes PC. Step wiring supplies results only after successful preparation.
177impl<S> PushStack<Word> for ExecutionState<S> {
178    #[inline]
179    fn push(&mut self, value: Word) {
180        self.stack.push(value);
181    }
182}
183
184macro_rules! float_access {
185    ($ty:ty, $decode:ident, $encode:ident) => {
186        impl<S> PopStack<$ty> for ExecutionState<S> {
187            #[inline]
188            fn pop(&mut self) -> eyre::Result<$ty> {
189                <Self as PopStack<Word>>::pop(self).map($decode)
190            }
191        }
192        impl<S> PushStack<$ty> for ExecutionState<S> {
193            #[inline]
194            fn push(&mut self, value: $ty) {
195                <Self as PushStack<Word>>::push(self, $encode(value));
196            }
197        }
198    };
199}
200
201float_access!(f32, decode_f32, encode_f32);
202
203float_access!(f64, decode_f64, encode_f64);