Skip to main content

miden_processor/
lib.rs

1#![no_std]
2// Trace tests intentionally use index-based `for i in a..b` over column slices; clippy's iterator
3// suggestion is noisier than helpful there.
4#![cfg_attr(test, allow(clippy::needless_range_loop))]
5
6#[macro_use]
7extern crate alloc;
8
9#[cfg(feature = "std")]
10extern crate std;
11
12use alloc::vec::Vec;
13use core::{
14    fmt::{self, Display, LowerHex},
15    ops::ControlFlow,
16};
17
18use miden_mast_package::debug_info::DebugSourceNodeId;
19
20mod continuation_stack;
21mod errors;
22mod execution;
23mod execution_options;
24mod executor;
25mod fast;
26mod host;
27mod processor;
28mod tracer;
29
30use miden_core::{
31    deferred::{Digest, Node, PrecompileError},
32    mast::ExecutableMastForest,
33    serde::{Deserializable, Serializable},
34};
35
36use crate::{
37    advice::{AdviceInputs, AdviceProvider},
38    continuation_stack::ContinuationStack,
39    errors::MapExecErr,
40    processor::{Processor, SystemInterface},
41    trace::RowIndex,
42};
43
44#[cfg(any(test, feature = "testing"))]
45mod test_utils;
46#[cfg(any(test, feature = "testing"))]
47pub use test_utils::{ProcessorStateSnapshot, TestHost};
48
49#[cfg(test)]
50mod tests;
51
52// RE-EXPORTS
53// ================================================================================================
54
55pub use continuation_stack::{Continuation, SourceInlineCallContext};
56pub use errors::{
57    AceError, ExecutionError, HostError, MemoryError, PackageSourceDebugContext,
58    advice_error_with_package_source_context, event_error_with_package_source_context,
59    procedure_not_found_with_package_source_context,
60};
61pub use execution_options::{ExecutionOptions, ExecutionOptionsError};
62pub use executor::ProgramExecutor;
63pub(crate) use fast::BreakReason;
64pub use fast::{
65    DebugCallFrame, DebugCallFrameResolver, DebugFrameOrigin, ExecutionOutput, FastProcessor,
66    ResumeContext,
67};
68pub use host::{
69    BaseHost, FutureMaybeSend, Host, LoadedMastForest, MastForestStore, MemMastForestStore,
70    SyncHost,
71    debug::{StdoutWriter, format_value, write_interval, write_stack},
72    default::{DefaultHost, HostLibrary},
73};
74pub use miden_core::{
75    EMPTY_WORD, Felt, ONE, WORD_SIZE, Word, ZERO, crypto, field, mast,
76    program::{
77        ExecutionClaim, InputError, KernelDescriptor, MIN_STACK_DEPTH, Program, ProgramInfo,
78        StackInputs, StackOutputs,
79    },
80    serde, utils,
81};
82pub use trace::{ExecutionWitness, PrecompileWitness, VmWitness};
83
84pub mod advice {
85    pub use miden_core::advice::{AdviceInputs, AdviceMap, AdviceStack};
86
87    pub use super::host::{
88        AdviceMutation,
89        advice::{AdviceError, AdviceProvider},
90    };
91}
92
93pub mod event {
94    pub use miden_core::events::*;
95
96    pub use crate::host::handlers::{
97        EventError, EventHandler, EventHandlerRegistry, NoopEventHandler, TraceError, TraceHandler,
98        TraceHandlerRegistry,
99    };
100}
101
102pub mod operation {
103    pub use miden_core::operations::*;
104
105    pub use crate::errors::{BinaryValueErrorContext, OperationError};
106}
107
108pub mod trace;
109
110// PROCESSOR STATE
111// ===============================================================================================
112
113/// A view into the current state of the processor.
114///
115/// This struct provides read access to the processor's state, including the stack, memory,
116/// advice provider, and execution context information.
117#[derive(Debug)]
118pub struct ProcessorState<'a> {
119    processor: &'a FastProcessor,
120}
121
122impl<'a> ProcessorState<'a> {
123    /// Returns a reference to the advice provider.
124    #[inline(always)]
125    pub fn advice_provider(&self) -> &AdviceProvider {
126        self.processor.advice_provider()
127    }
128
129    /// Returns the execution options.
130    #[inline(always)]
131    pub fn execution_options(&self) -> &ExecutionOptions {
132        self.processor.execution_options()
133    }
134
135    /// Returns the current clock cycle of a process.
136    #[inline(always)]
137    pub fn clock(&self) -> RowIndex {
138        self.processor.clock()
139    }
140
141    /// Returns the current execution context ID.
142    #[inline(always)]
143    pub fn ctx(&self) -> ContextId {
144        self.processor.ctx()
145    }
146
147    /// Returns the value located at the specified position on the stack at the current clock cycle.
148    ///
149    /// This method can access elements beyond the top 16 positions by using the overflow table.
150    #[inline(always)]
151    pub fn get_stack_item(&self, pos: usize) -> Felt {
152        self.processor.stack_get_safe(pos)
153    }
154
155    /// Returns a word starting at the specified element index on the stack.
156    ///
157    /// The word is formed by taking 4 consecutive elements starting from the specified index.
158    /// For example, start_idx=0 creates a word from stack elements 0-3, start_idx=1 creates
159    /// a word from elements 1-4, etc.
160    ///
161    /// Stack element N will be at position 0 of the word, N+1 at position 1, N+2 at position 2,
162    /// and N+3 at position 3. `word[0]` corresponds to the top of the stack.
163    ///
164    /// This method can access elements beyond the top 16 positions by using the overflow table.
165    /// Creating a word does not change the state of the stack.
166    #[inline(always)]
167    pub fn get_stack_word(&self, start_idx: usize) -> Word {
168        self.processor.stack_get_word_safe(start_idx)
169    }
170
171    /// Returns stack state at the current clock cycle. This includes the top 16 items of the
172    /// stack + overflow entries.
173    #[inline(always)]
174    pub fn get_stack_state(&self) -> Vec<Felt> {
175        self.processor.stack().iter().rev().copied().collect()
176    }
177
178    /// Returns the current depth of the stack, including overflow entries.
179    #[inline(always)]
180    pub fn stack_depth(&self) -> u32 {
181        self.processor.stack_depth()
182    }
183
184    /// Returns the element located at the specified context/address, or None if the address hasn't
185    /// been accessed previously.
186    #[inline(always)]
187    pub fn get_mem_value(&self, ctx: ContextId, addr: u32) -> Option<Felt> {
188        self.processor.memory().read_element_impl(ctx, addr)
189    }
190
191    /// Returns the batch of elements starting at the specified context/address.
192    ///
193    /// # Errors
194    /// - If the address is not word aligned.
195    #[inline(always)]
196    pub fn get_mem_word(&self, ctx: ContextId, addr: u32) -> Result<Option<Word>, MemoryError> {
197        self.processor.memory().read_word_impl(ctx, addr)
198    }
199
200    /// Reads (start_addr, end_addr) tuple from the specified elements of the operand stack (
201    /// without modifying the state of the stack), and verifies that memory range is valid.
202    ///
203    /// The range is half-open `[start, end)`; both `start` and `end` must be `<= u32::MAX`.
204    pub fn get_mem_addr_range(
205        &self,
206        start_idx: usize,
207        end_idx: usize,
208    ) -> Result<core::ops::Range<u32>, MemoryError> {
209        let start_addr = self.get_stack_item(start_idx).as_canonical_u64();
210        let end_addr = self.get_stack_item(end_idx).as_canonical_u64();
211
212        if start_addr > u32::MAX as u64 {
213            return Err(MemoryError::AddressOutOfBounds { addr: start_addr });
214        }
215        if end_addr > u32::MAX as u64 {
216            return Err(MemoryError::AddressOutOfBounds { addr: end_addr });
217        }
218
219        if start_addr > end_addr {
220            return Err(MemoryError::InvalidMemoryRange { start_addr, end_addr });
221        }
222
223        Ok(start_addr as u32..end_addr as u32)
224    }
225
226    /// Returns the entire memory state for the specified execution context at the current clock
227    /// cycle.
228    ///
229    /// The state is returned as a vector of (address, value) tuples, and includes addresses which
230    /// have been accessed at least once.
231    #[inline(always)]
232    pub fn get_mem_state(&self, ctx: ContextId) -> Vec<(MemoryAddress, Felt)> {
233        self.processor.memory().get_memory_state(ctx)
234    }
235
236    /// Returns the already-memoized canonical deferred digest for `digest`, if present.
237    ///
238    /// This is a read-only lookup: it does not evaluate `digest`, register helper nodes, or mutate
239    /// deferred state.
240    #[inline(always)]
241    pub fn get_canonical_deferred_digest(&self, digest: Digest) -> Option<Digest> {
242        self.processor.deferred_state().get_canonical_digest(digest)
243    }
244
245    /// Returns the already-memoized canonical deferred node for `digest`, if present.
246    ///
247    /// This is a read-only lookup and returns only canonical results that were already memoized in
248    /// deferred state; it never evaluates or mutates deferred state.
249    #[inline(always)]
250    pub fn get_canonical_deferred_node(&self, digest: Digest) -> Option<(Digest, &Node)> {
251        self.processor.deferred_state().get_canonical_node(digest)
252    }
253
254    /// Returns the already-memoized canonical deferred node for `digest`.
255    ///
256    /// This is a read-only lookup and never evaluates or mutates deferred state.
257    ///
258    /// # Errors
259    /// Returns [`PrecompileError::MissingNode`] if no memoized canonical node is available.
260    #[inline(always)]
261    pub fn require_canonical_deferred_node(
262        &self,
263        digest: Digest,
264    ) -> Result<(Digest, &Node), PrecompileError> {
265        self.processor.deferred_state().require_canonical_node(digest)
266    }
267}
268
269// STOPPER
270// ===============================================================================================
271
272/// A trait for types that determine whether execution should be stopped after each clock cycle.
273///
274/// This allows for flexible control over the execution process, enabling features such as stepping
275/// through execution (see [`crate::FastProcessor::step`]) or limiting execution to a certain number
276/// of clock cycles (used in parallel trace generation to fill the trace for a predetermined trace
277/// fragment).
278pub(crate) trait Stopper {
279    type Processor;
280
281    /// The forest representation used by the executor this stopper is paired with.
282    ///
283    /// For live execution this is `Arc<MastForest>`; for replay it is `Arc<SparseMastForest>`.
284    type Forest: ExecutableMastForest + Clone;
285
286    /// Determines whether execution should be stopped at the end of each clock cycle.
287    ///
288    /// This method is guaranteed to be called at the end of each clock cycle, *after* the processor
289    /// state has been updated to reflect the effects of the operations executed during that cycle
290    /// (*including* the processor clock). Hence, a processor clock of `N` indicates that clock
291    /// cycle `N - 1` has just completed.
292    ///
293    /// The `continuation_after_stop` is provided in cases where simply resuming execution from the
294    /// top of the continuation stack is not sufficient to continue execution correctly. For
295    /// example, when stopping execution in the middle of a basic block, we need to provide a
296    /// `ResumeBasicBlock` continuation to ensure that execution resumes at the correct operation
297    /// within the basic block (i.e. the operation right after the one that was last executed before
298    /// being stopped). No continuation is provided in case of error, since it is expected that
299    /// execution will not be resumed.
300    fn should_stop(
301        &self,
302        processor: &Self::Processor,
303        continuation_stack: &ContinuationStack<Self::Forest>,
304        continuation_after_stop: impl FnOnce() -> Option<(
305            Continuation<Self::Forest>,
306            Option<DebugSourceNodeId>,
307        )>,
308    ) -> ControlFlow<BreakReason<Self::Forest>>;
309}
310
311// EXECUTION CONTEXT
312// ================================================================================================
313
314/// Represents the ID of an execution context
315#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
316#[cfg_attr(
317    all(feature = "arbitrary", test),
318    miden_test_serialization_macros::serialization_test
319)]
320pub struct ContextId(u32);
321
322impl ContextId {
323    /// Returns the root context ID
324    pub fn root() -> Self {
325        Self(0)
326    }
327
328    /// Returns true if the context ID represents the root context
329    pub fn is_root(&self) -> bool {
330        self.0 == 0
331    }
332}
333
334impl From<RowIndex> for ContextId {
335    fn from(value: RowIndex) -> Self {
336        Self(value.as_u32())
337    }
338}
339
340impl From<u32> for ContextId {
341    fn from(value: u32) -> Self {
342        Self(value)
343    }
344}
345
346impl From<ContextId> for u32 {
347    fn from(context_id: ContextId) -> Self {
348        context_id.0
349    }
350}
351
352impl From<ContextId> for u64 {
353    fn from(context_id: ContextId) -> Self {
354        context_id.0.into()
355    }
356}
357
358impl From<ContextId> for Felt {
359    fn from(context_id: ContextId) -> Self {
360        Felt::from_u32(context_id.0)
361    }
362}
363
364#[cfg(any(test, feature = "arbitrary"))]
365mod context_id_arbitrary {
366    use proptest::prelude::*;
367
368    use super::ContextId;
369
370    impl Arbitrary for ContextId {
371        type Parameters = ();
372        type Strategy = BoxedStrategy<Self>;
373
374        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
375            // Plain u32 newtype; edge-biased to the 0 and u32::MAX bounds.
376            prop_oneof![Just(0u32), Just(u32::MAX), any::<u32>()].prop_map(Self).boxed()
377        }
378    }
379}
380
381impl Serializable for ContextId {
382    fn write_into<W: serde::ByteWriter>(&self, target: &mut W) {
383        Serializable::write_into(&self.0, target);
384    }
385}
386
387impl Deserializable for ContextId {
388    fn read_from<R: serde::ByteReader>(
389        source: &mut R,
390    ) -> Result<Self, serde::DeserializationError> {
391        Ok(Self(<u32 as Deserializable>::read_from(source)?))
392    }
393
394    fn min_serialized_size() -> usize {
395        <u32 as Deserializable>::min_serialized_size()
396    }
397}
398
399impl Display for ContextId {
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        write!(f, "{}", self.0)
402    }
403}
404
405// MEMORY ADDRESS
406// ================================================================================================
407
408#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
409pub struct MemoryAddress(u32);
410
411impl From<u32> for MemoryAddress {
412    fn from(addr: u32) -> Self {
413        MemoryAddress(addr)
414    }
415}
416
417impl From<MemoryAddress> for u32 {
418    fn from(value: MemoryAddress) -> Self {
419        value.0
420    }
421}
422
423impl Display for MemoryAddress {
424    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425        Display::fmt(&self.0, f)
426    }
427}
428
429impl LowerHex for MemoryAddress {
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        LowerHex::fmt(&self.0, f)
432    }
433}
434
435impl core::ops::Add<MemoryAddress> for MemoryAddress {
436    type Output = Self;
437
438    fn add(self, rhs: MemoryAddress) -> Self::Output {
439        MemoryAddress(self.0 + rhs.0)
440    }
441}
442
443impl core::ops::Add<u32> for MemoryAddress {
444    type Output = Self;
445
446    fn add(self, rhs: u32) -> Self::Output {
447        MemoryAddress(self.0 + rhs)
448    }
449}
450
451// HELPERS
452// ===============================================================================================
453
454/// Lifts an [`Option<T>`] into a [`ControlFlow`] suitable for the execution loop, mapping `None`
455/// to a break carrying an [`ExecutionError::Internal`] with `err_msg`.
456///
457/// Intended for use with `?` at sites where a `None` represents a violated internal invariant —
458/// most commonly a missing node returned by
459/// [`ExecutableMastForest::get_node_by_id`](miden_core::mast::ExecutableMastForest::get_node_by_id).
460/// For functions returning `ControlFlow<InternalBreakReason<F>>`, chain
461/// `.map_break(InternalBreakReason::from)` before `?`.
462#[track_caller]
463fn option_map_break_reason<F, T>(
464    opt: Option<T>,
465    err_msg: &'static str,
466) -> ControlFlow<BreakReason<F>, T> {
467    match opt {
468        Some(value) => ControlFlow::Continue(value),
469        None => ControlFlow::Break(BreakReason::Err(ExecutionError::Internal(err_msg))),
470    }
471}