Skip to main content

vihaco_runtime/
stack.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Framework stack preparation and effect-application protocols.
5
6use crate::{
7    Composite, Execute, Field, Message, PopStack, PushStack, ReusableMessageRecipe, StackValue,
8};
9
10/// Copied operands prepared for an instruction, distinct from its payload.
11///
12/// Tuple builders support arities 0–16. Fields retain their declared order,
13/// while extraction proceeds right to left: `(lhs, rhs)` pops `rhs` first.
14/// Successful pops remain consumed if a later pop or CPU execution fails.
15/// The empty tuple consumes nothing and does not access the stack capability.
16/// Tuple construction requires no allocation or stack borrow. Homogeneous
17/// [`crate::StackBatch`] inputs use [`StackInputCount`] and inline storage with
18/// heap fallback; their owned message likewise retains no stack borrow.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct PopFromStack<Values>(pub Values);
21
22impl<Values: 'static> Message for PopFromStack<Values> {}
23
24/// Results to insert during the framework's effect-application phase.
25///
26/// [`Apply`] supports tuples of arity 0–16 (including heterogeneous items) and
27/// homogeneous arrays of any length. Values are inserted left to right, so the
28/// last value becomes the top. Empty tuples/arrays insert nothing. The wrapper
29/// owns values, not storage references, and does not apply itself automatically.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct PushToStack<Values>(pub Values);
32
33/// Framework wiring from composite instruction preparation to operand storage.
34///
35/// A composite with a `#[program]` device supplies this connection automatically.
36/// Ordinary component/composite authors select `PopFromStack` and `PushToStack`
37/// types; they do not implement stack storage or transfer logic.
38///
39/// This capability lets stack message recipes access operands. A composite's
40/// [`crate::BuildMessage`] implementation explicitly calls the selected recipe;
41/// providing this capability does not supply a builder. A field name or merely
42/// containing an ExecutionState does not establish the capability.
43///
44/// No canonical-Boolean validation policy is needed: [`StackValue`] Boolean
45/// extraction interprets every nonzero word as true.
46pub trait HasOperandStack<I> {
47    /// The checked operand source used for this instruction.
48    type Source;
49
50    /// Borrow the operand source for the supplied operand count.
51    ///
52    /// The arity allows a later cached implementation to prepare storage once.
53    /// This accessor must not consume operands, bulk-precheck their availability,
54    /// or otherwise change the sequential partial-consumption semantics.
55    /// Empty tuple and immediate empty batch builders do not invoke it.
56    fn operand_stack(&mut self, arity: usize) -> &mut Self::Source;
57}
58
59/// Framework hook to apply one effect during [`crate::Step`].
60///
61/// Authors can apply `PushToStack` effects to their program inside authored Steps.
62/// The framework does not impose effect handling. Implementations are
63/// extension plumbing for storage/effects, not required component boilerplate.
64///
65/// Stack output implementations use direct typed insertion. This trait neither
66/// executes instructions nor supplies a Step or observer callbacks. The caller
67/// handles [`crate::Effects`] in order, applying each effect after execution.
68/// Applied values are not
69/// rolled back if later work fails. Custom fallible effect handling remains in
70/// Step; stack insertion follows [`PushStack`]'s ordinary
71/// allocation behavior.
72pub trait Apply<E> {
73    /// Apply a single effect to this destination.
74    fn apply(&mut self, effect: E);
75}
76
77impl<C, F, I, Context: ?Sized> ReusableMessageRecipe<C, F, I, Context> for PopFromStack<()>
78where
79    C: Composite + Field<F> + HasOperandStack<I>,
80    C::Child: Execute<I, Message = PopFromStack<()>>,
81{
82    #[inline]
83    fn prepare(_: &mut C, _: &I, _: &Context) -> eyre::Result<Self> {
84        Ok(PopFromStack(()))
85    }
86}
87
88impl<D> Apply<PushToStack<()>> for D {
89    #[inline]
90    fn apply(&mut self, _: PushToStack<()>) {}
91}
92
93impl<D, T: StackValue, const N: usize> Apply<PushToStack<[T; N]>> for D
94where
95    D: PushStack<T::Storage>,
96{
97    #[inline]
98    fn apply(&mut self, effect: PushToStack<[T; N]>) {
99        for value in effect.0 {
100            value.push_to(self);
101        }
102    }
103}
104
105// Expand once here into message-owned per-arity recipes, never per instruction
106// or composite. Composite builders choose whether to delegate to these recipes.
107macro_rules! stack_tuple {
108    (@pop $source:ident;) => {};
109    (@pop $source:ident; $ty:ident:$value:ident $(, $rest:ident:$other:ident)*) => {
110        stack_tuple!(@pop $source; $($rest:$other),*);
111        let $value = $ty::pop_from($source)?;
112    };
113    ($($ty:ident:$value:ident),+) => {
114        impl<Parent, Route, Inst, Context: ?Sized, $($ty: StackValue),+>
115            ReusableMessageRecipe<Parent, Route, Inst, Context> for PopFromStack<($($ty,)+)>
116        where
117            Parent: Composite + Field<Route> + HasOperandStack<Inst>,
118            Parent::Child: Execute<Inst, Message = PopFromStack<($($ty,)+)>>,
119            Parent::Source: $(PopStack<$ty::Storage> +)+ Sized,
120        {
121            #[inline]
122            fn prepare(parent: &mut Parent, _: &Inst, _: &Context) -> eyre::Result<Self> {
123                let source = parent.operand_stack([$(stringify!($ty)),+].len());
124                stack_tuple!(@pop source; $($ty:$value),+);
125                Ok(PopFromStack(($($value,)+)))
126            }
127        }
128
129        impl<Destination, $($ty: StackValue),+>
130            Apply<PushToStack<($($ty,)+)>> for Destination
131        where
132            Destination: $(PushStack<$ty::Storage> +)+ Sized,
133        {
134            #[inline]
135            fn apply(&mut self, effect: PushToStack<($($ty,)+)>) {
136                let ($($value,)+) = effect.0;
137                $($value.push_to(self);)+
138            }
139        }
140    };
141}
142
143stack_tuple!(A:a);
144
145stack_tuple!(A:a, B:b);
146
147stack_tuple!(A:a, B:b, C:c);
148
149stack_tuple!(A:a, B:b, C:c, D:d);
150
151stack_tuple!(A:a, B:b, C:c, D:d, E:e);
152
153stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f);
154
155stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g);
156
157stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h);
158
159stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i);
160
161stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i, J:j);
162
163stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i, J:j, K:k);
164
165stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i, J:j, K:k, L:l);
166
167stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i, J:j, K:k, L:l, M:m);
168
169stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i, J:j, K:k, L:l, M:m, N:n);
170
171stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i, J:j, K:k, L:l, M:m, N:n, O:o);
172
173stack_tuple!(A:a, B:b, C:c, D:d, E:e, F:f, G:g, H:h, I:i, J:j, K:k, L:l, M:m, N:n, O:o, P:p);
174
175/// Where a homogeneous batch's operand count is obtained.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub enum InputCount {
178    /// A count computed from the current instruction's payload.
179    Immediate(usize),
180    /// Pop a word count above the batch, checking that it fits `usize`.
181    FromStack,
182}
183
184/// Count metadata for a component/instruction pair using [`crate::StackBatch`].
185///
186/// Components describe the count source; vihaco performs all stack operations.
187/// This belongs to the component so external instruction vocabularies are usable.
188pub trait StackInputCount<I> {
189    fn input_count(instruction: &I) -> eyre::Result<InputCount>;
190}
191
192impl<C, F, I, T, Context: ?Sized> ReusableMessageRecipe<C, F, I, Context>
193    for PopFromStack<crate::StackBatch<T>>
194where
195    C: Composite + Field<F> + HasOperandStack<I>,
196    C::Child: Execute<I, Message = PopFromStack<crate::StackBatch<T>>> + StackInputCount<I>,
197    T: StackValue + 'static,
198    C::Source: PopStack<T::Storage> + PopStack<vihaco_abi::word::Word>,
199{
200    fn prepare(parent: &mut C, instruction: &I, _: &Context) -> eyre::Result<Self> {
201        let count = match C::Child::input_count(instruction)? {
202            InputCount::Immediate(count) => count,
203            InputCount::FromStack => {
204                let word = PopStack::<vihaco_abi::word::Word>::pop(parent.operand_stack(1))?;
205                usize::try_from(word)?
206            }
207        };
208        let mut values = smallvec::SmallVec::new();
209        // Reserve before value consumption. A count popped above remains consumed
210        // if reservation fails, just as earlier tuple pops remain consumed.
211        values
212            .try_reserve_exact(count)
213            .map_err(|error| eyre::eyre!("cannot reserve operand batch: {error:?}"))?;
214        if count != 0 {
215            let source = parent.operand_stack(count);
216            for _ in 0..count {
217                values.push(T::pop_from(source)?);
218            }
219            values.reverse();
220        }
221        Ok(PopFromStack(crate::StackBatch { values }))
222    }
223}
224
225// Selecting a program device also selects its operand storage. This connection
226// supplies no Step or effect policy.
227impl<C: crate::HasProgram, I> HasOperandStack<I> for C {
228    type Source = C::Program;
229    #[inline]
230    fn operand_stack(&mut self, _: usize) -> &mut Self::Source {
231        self.program_mut()
232    }
233}