1#![no_std]
2#![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
52pub 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#[derive(Debug)]
118pub struct ProcessorState<'a> {
119 processor: &'a FastProcessor,
120}
121
122impl<'a> ProcessorState<'a> {
123 #[inline(always)]
125 pub fn advice_provider(&self) -> &AdviceProvider {
126 self.processor.advice_provider()
127 }
128
129 #[inline(always)]
131 pub fn execution_options(&self) -> &ExecutionOptions {
132 self.processor.execution_options()
133 }
134
135 #[inline(always)]
137 pub fn clock(&self) -> RowIndex {
138 self.processor.clock()
139 }
140
141 #[inline(always)]
143 pub fn ctx(&self) -> ContextId {
144 self.processor.ctx()
145 }
146
147 #[inline(always)]
151 pub fn get_stack_item(&self, pos: usize) -> Felt {
152 self.processor.stack_get_safe(pos)
153 }
154
155 #[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 #[inline(always)]
174 pub fn get_stack_state(&self) -> Vec<Felt> {
175 self.processor.stack().iter().rev().copied().collect()
176 }
177
178 #[inline(always)]
180 pub fn stack_depth(&self) -> u32 {
181 self.processor.stack_depth()
182 }
183
184 #[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 #[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 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 #[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 #[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 #[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 #[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
269pub(crate) trait Stopper {
279 type Processor;
280
281 type Forest: ExecutableMastForest + Clone;
285
286 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#[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 pub fn root() -> Self {
325 Self(0)
326 }
327
328 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 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#[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#[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}