Skip to main content

vihaco_stdlib/
loadable.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! An independently owned image paired with its mutable execution machine.
5
6use vihaco_abi::{traits::Reset, word::Word};
7use vihaco_module::module::LocalModule;
8use vihaco_runtime::{Composite, Dispatch, HasProgram};
9
10use crate::{ExecutionState, Image, execution_state};
11
12/// A program image and the composite that executes its borrowed instructions.
13///
14/// Construct the image explicitly before pairing it with a machine. Only
15/// [`Image`] is supported; the image remains unchanged throughout an invocation.
16/// Ordinary outer structs can own several loadables with different instruction
17/// sets. Section selection and image construction remain caller responsibilities.
18#[derive(Debug)]
19pub struct Loadable<I, M: Composite> {
20    image: I,
21    machine: M,
22}
23
24impl<Inst, V, Ty, Info, M: Composite> Loadable<Image<Inst, V, Ty, Info>, M> {
25    /// Inspect the paired image without changing an invocation's program data.
26    pub fn image(&self) -> &Image<Inst, V, Ty, Info> {
27        &self.image
28    }
29
30    /// Inspect the execution machine and its devices.
31    pub fn machine(&self) -> &M {
32        &self.machine
33    }
34
35    /// Configure the execution machine or its devices.
36    ///
37    /// Direct changes to execution state can affect whether an invocation can
38    /// resume. The caller is responsible for keeping those changes consistent
39    /// with the paired image.
40    pub fn machine_mut(&mut self) -> &mut M {
41        &mut self.machine
42    }
43
44    /// Borrow the image and mutably borrow the machine for custom runners.
45    ///
46    /// Within [`execution_state::run`], pass `&image.module` and the machine
47    /// to [`execution_state::execute_instruction`] to drive a step. Keep any
48    /// direct changes to invocation state consistent with the paired image.
49    pub fn parts_mut(&mut self) -> (&Image<Inst, V, Ty, Info>, &mut M) {
50        (&self.image, &mut self.machine)
51    }
52
53    pub(crate) fn breakpoint_parts_mut(&mut self) -> (&mut Image<Inst, V, Ty, Info>, &mut M) {
54        (&mut self.image, &mut self.machine)
55    }
56
57    /// Consume the owner, returning its image and machine without resetting them.
58    pub fn into_parts(self) -> (Image<Inst, V, Ty, Info>, M) {
59        (self.image, self.machine)
60    }
61}
62
63impl<Inst, V, Ty, Info, M, S> Loadable<Image<Inst, V, Ty, Info>, M>
64where
65    M: Composite + HasProgram<Program = ExecutionState<S>>,
66{
67    /// Pair an image with a machine, resetting its previous invocation state.
68    ///
69    /// Device state is retained. No parsing, lowering, or image validation is
70    /// performed here; construction of a valid image is the caller's job.
71    ///
72    /// When reusing a machine with a different image, call
73    /// [`Debugger::forget_breakpoints`](crate::debugger::Debugger::forget_breakpoints)
74    /// on each debugger before using it with the new image. Saved instructions
75    /// belong to the discarded image; retaining them can overwrite new code
76    /// when a breakpoint is cleared. To keep the old image usable, restore its
77    /// instructions with [`Debugger::clear_all`](crate::debugger::Debugger::clear_all)
78    /// before separating it from the machine instead.
79    pub fn new(image: Image<Inst, V, Ty, Info>, mut machine: M) -> Self {
80        machine.program_mut().reset();
81        Self { image, machine }
82    }
83
84    /// Install an already constructed image and reset execution state.
85    ///
86    /// Device state is retained. Image construction happens before this call;
87    /// mutations made by the caller while constructing it are not rolled back.
88    ///
89    /// After replacement succeeds, call
90    /// [`Debugger::forget_breakpoints`](crate::debugger::Debugger::forget_breakpoints)
91    /// on each debugger before using it again. This discards instructions saved
92    /// from the old image, which must never be restored into the replacement.
93    /// Do not forget them before this call: if replacement is rejected, the old
94    /// image still needs those instructions to clear or resume its breakpoints.
95    /// Invocation-only [`Self::reset`] calls retain the image and its breakpoints.
96    /// See the `debugger` Cargo example for the replacement and reuse sequence.
97    ///
98    /// # Errors
99    ///
100    /// Rejects replacement while an invocation is active, including one that
101    /// could resume after an execution error. Call [`Self::reset`] to abandon
102    /// that invocation first. Rejection leaves the current image and execution
103    /// state unchanged.
104    pub fn replace_image(&mut self, image: Image<Inst, V, Ty, Info>) -> eyre::Result<()> {
105        eyre::ensure!(
106            self.machine.program().is_halted(),
107            "cannot replace an active program"
108        );
109        self.image = image;
110        self.reset();
111        Ok(())
112    }
113
114    /// Initialize an invocation without executing instructions.
115    pub fn start(&mut self, arguments: &[Word]) -> eyre::Result<()> {
116        self.machine
117            .program_mut()
118            .start(&self.image.module, arguments)
119    }
120
121    /// Abandon the invocation, retaining the image and all device state.
122    pub fn reset(&mut self) {
123        self.machine.program_mut().reset();
124    }
125}
126
127impl<Inst, V, Ty, Info, M, S> Loadable<Image<Inst, V, Ty, Info>, M>
128where
129    M: HasProgram<Program = ExecutionState<S>>
130        + Dispatch<LocalModule<Inst, V, Ty, Info>, Instruction = Inst>,
131{
132    /// Start at the program entrypoint with the supplied arguments.
133    ///
134    /// Instructions and metadata borrow the image while dispatch mutates the
135    /// separate machine. No instruction cloning is required.
136    ///
137    /// # Errors
138    ///
139    /// Returns the runner's entry or execution errors. Earlier machine mutations
140    /// are retained; reset or resume according to the invocation's state.
141    pub fn execute(&mut self, arguments: &[Word]) -> eyre::Result<()> {
142        execution_state::execute(&self.image.module, &mut self.machine, arguments)
143    }
144
145    /// Continue the existing invocation against the same paired image.
146    ///
147    /// # Errors
148    ///
149    /// Returns the runner's state, instruction-fetch, or dispatch errors without
150    /// rolling back machine mutations. A halted invocation remains halted.
151    /// A suspended invocation also remains suspended; use
152    /// [`Self::resume_with_breaks`] to continue from a debugger breakpoint.
153    pub fn resume(&mut self) -> eyre::Result<()> {
154        execution_state::resume(&self.image.module, &mut self.machine)
155    }
156}