1#![no_std]
2
3#[macro_use]
4extern crate alloc;
5
6#[cfg(feature = "std")]
7extern crate std;
8
9use alloc::{sync::Arc, vec::Vec};
10use core::fmt::{Display, LowerHex};
11
12use miden_air::trace::{
13 CHIPLETS_WIDTH, DECODER_TRACE_WIDTH, MIN_TRACE_LEN, RANGE_CHECK_TRACE_WIDTH, STACK_TRACE_WIDTH,
14 SYS_TRACE_WIDTH,
15};
16pub use miden_air::{ExecutionOptions, ExecutionOptionsError, RowIndex};
17pub use miden_core::{
18 AssemblyOp, EMPTY_WORD, Felt, Kernel, ONE, Operation, Program, ProgramInfo, QuadExtension,
19 StackInputs, StackOutputs, WORD_SIZE, Word, ZERO,
20 crypto::merkle::SMT_DEPTH,
21 errors::InputError,
22 mast::{MastForest, MastNode, MastNodeExt, MastNodeId},
23 precompile::{PrecompileRequest, PrecompileTranscriptState},
24 sys_events::SystemEvent,
25 utils::DeserializationError,
26};
27use miden_core::{
28 Decorator, FieldElement,
29 mast::{
30 BasicBlockNode, CallNode, DynNode, ExternalNode, JoinNode, LoopNode, OpBatch, SplitNode,
31 },
32};
33use miden_debug_types::SourceSpan;
34pub use winter_prover::matrix::ColMatrix;
35
36pub(crate) mod continuation_stack;
37
38pub mod fast;
39use fast::FastProcessState;
40pub mod parallel;
41pub(crate) mod processor;
42
43mod operations;
44
45mod system;
46pub use system::ContextId;
47use system::System;
48
49#[cfg(test)]
50mod test_utils;
51
52pub(crate) mod decoder;
53use decoder::Decoder;
54
55mod stack;
56use stack::Stack;
57
58mod range;
59use range::RangeChecker;
60
61mod host;
62
63pub use host::{
64 AdviceMutation, AsyncHost, BaseHost, FutureMaybeSend, MastForestStore, MemMastForestStore,
65 SyncHost,
66 advice::{AdviceError, AdviceInputs, AdviceProvider},
67 debug::DefaultDebugHandler,
68 default::{DefaultHost, HostLibrary},
69 handlers::{
70 AssertError, DebugError, DebugHandler, EventError, EventHandler, EventHandlerRegistry,
71 NoopEventHandler, TraceError,
72 },
73};
74
75mod chiplets;
76use chiplets::Chiplets;
77pub use chiplets::MemoryError;
78
79mod trace;
80use trace::TraceFragment;
81pub use trace::{ChipletsLengths, ExecutionTrace, NUM_RAND_ROWS, TraceLenSummary};
82
83mod errors;
84pub use errors::{ErrorContext, ErrorContextImpl, ExecutionError};
85
86pub mod utils;
87
88#[cfg(all(test, not(feature = "no_err_ctx")))]
89mod tests;
90
91mod debug;
92pub use debug::{AsmOpInfo, VmState, VmStateIterator};
93
94pub mod math {
98 pub use miden_core::{Felt, FieldElement, StarkField};
99 pub use winter_prover::math::fft;
100}
101
102pub mod crypto {
103 pub use miden_core::crypto::{
104 hash::{Blake3_192, Blake3_256, ElementHasher, Hasher, Poseidon2, Rpo256, Rpx256},
105 merkle::{
106 MerkleError, MerklePath, MerkleStore, MerkleTree, NodeIndex, PartialMerkleTree,
107 SimpleSmt,
108 },
109 random::{RandomCoin, RpoRandomCoin, RpxRandomCoin, WinterRandomCoin},
110 };
111}
112
113#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
117pub struct MemoryAddress(u32);
118
119impl From<u32> for MemoryAddress {
120 fn from(addr: u32) -> Self {
121 MemoryAddress(addr)
122 }
123}
124
125impl From<MemoryAddress> for u32 {
126 fn from(value: MemoryAddress) -> Self {
127 value.0
128 }
129}
130
131impl Display for MemoryAddress {
132 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
133 Display::fmt(&self.0, f)
134 }
135}
136
137impl LowerHex for MemoryAddress {
138 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139 LowerHex::fmt(&self.0, f)
140 }
141}
142
143impl core::ops::Add<MemoryAddress> for MemoryAddress {
144 type Output = Self;
145
146 fn add(self, rhs: MemoryAddress) -> Self::Output {
147 MemoryAddress(self.0 + rhs.0)
148 }
149}
150
151impl core::ops::Add<u32> for MemoryAddress {
152 type Output = Self;
153
154 fn add(self, rhs: u32) -> Self::Output {
155 MemoryAddress(self.0 + rhs)
156 }
157}
158
159type SysTrace = [Vec<Felt>; SYS_TRACE_WIDTH];
160
161pub struct DecoderTrace {
162 trace: [Vec<Felt>; DECODER_TRACE_WIDTH],
163 aux_builder: decoder::AuxTraceBuilder,
164}
165
166pub struct StackTrace {
167 trace: [Vec<Felt>; STACK_TRACE_WIDTH],
168}
169
170pub struct RangeCheckTrace {
171 trace: [Vec<Felt>; RANGE_CHECK_TRACE_WIDTH],
172 aux_builder: range::AuxTraceBuilder,
173}
174
175pub struct ChipletsTrace {
176 trace: [Vec<Felt>; CHIPLETS_WIDTH],
177 aux_builder: chiplets::AuxTraceBuilder,
178}
179
180#[tracing::instrument("execute_program", skip_all)]
189pub fn execute(
190 program: &Program,
191 stack_inputs: StackInputs,
192 advice_inputs: AdviceInputs,
193 host: &mut impl SyncHost,
194 options: ExecutionOptions,
195) -> Result<ExecutionTrace, ExecutionError> {
196 let mut process = Process::new(program.kernel().clone(), stack_inputs, advice_inputs, options);
197 let stack_outputs = process.execute(program, host)?;
198 let trace = ExecutionTrace::new(process, stack_outputs);
199 assert_eq!(&program.hash(), trace.program_hash(), "inconsistent program hash");
200 Ok(trace)
201}
202
203pub fn execute_iter(
206 program: &Program,
207 stack_inputs: StackInputs,
208 advice_inputs: AdviceInputs,
209 host: &mut impl SyncHost,
210) -> VmStateIterator {
211 let mut process = Process::new_debug(program.kernel().clone(), stack_inputs, advice_inputs);
212 let result = process.execute(program, host);
213 if result.is_ok() {
214 assert_eq!(
215 program.hash(),
216 process.decoder.program_hash().into(),
217 "inconsistent program hash"
218 );
219 }
220 VmStateIterator::new(process, result)
221}
222
223#[cfg(not(any(test, feature = "testing")))]
236pub struct Process {
237 advice: AdviceProvider,
238 system: System,
239 decoder: Decoder,
240 stack: Stack,
241 range: RangeChecker,
242 chiplets: Chiplets,
243 max_cycles: u32,
244 enable_tracing: bool,
245 pc_transcript_state: PrecompileTranscriptState,
247}
248
249#[cfg(any(test, feature = "testing"))]
250pub struct Process {
251 pub advice: AdviceProvider,
252 pub system: System,
253 pub decoder: Decoder,
254 pub stack: Stack,
255 pub range: RangeChecker,
256 pub chiplets: Chiplets,
257 pub max_cycles: u32,
258 pub enable_tracing: bool,
259 pub pc_transcript_state: PrecompileTranscriptState,
261}
262
263impl Process {
264 pub fn new(
268 kernel: Kernel,
269 stack_inputs: StackInputs,
270 advice_inputs: AdviceInputs,
271 execution_options: ExecutionOptions,
272 ) -> Self {
273 Self::initialize(kernel, stack_inputs, advice_inputs, execution_options)
274 }
275
276 pub fn new_debug(
278 kernel: Kernel,
279 stack_inputs: StackInputs,
280 advice_inputs: AdviceInputs,
281 ) -> Self {
282 Self::initialize(
283 kernel,
284 stack_inputs,
285 advice_inputs,
286 ExecutionOptions::default().with_tracing().with_debugging(true),
287 )
288 }
289
290 fn initialize(
291 kernel: Kernel,
292 stack: StackInputs,
293 advice_inputs: AdviceInputs,
294 execution_options: ExecutionOptions,
295 ) -> Self {
296 let in_debug_mode =
297 execution_options.enable_debugging() || execution_options.enable_tracing();
298 Self {
299 advice: advice_inputs.into(),
300 system: System::new(execution_options.expected_cycles() as usize),
301 decoder: Decoder::new(in_debug_mode),
302 stack: Stack::new(&stack, execution_options.expected_cycles() as usize, in_debug_mode),
303 range: RangeChecker::new(),
304 chiplets: Chiplets::new(kernel),
305 max_cycles: execution_options.max_cycles(),
306 enable_tracing: execution_options.enable_tracing(),
307 pc_transcript_state: PrecompileTranscriptState::default(),
308 }
309 }
310
311 pub fn execute(
316 &mut self,
317 program: &Program,
318 host: &mut impl SyncHost,
319 ) -> Result<StackOutputs, ExecutionError> {
320 if self.system.clk() != 0 {
321 return Err(ExecutionError::ProgramAlreadyExecuted);
322 }
323
324 self.advice
325 .extend_map(program.mast_forest().advice_map())
326 .map_err(|err| ExecutionError::advice_error(err, RowIndex::from(0), &()))?;
327
328 self.execute_mast_node(program.entrypoint(), &program.mast_forest().clone(), host)?;
329
330 self.stack.build_stack_outputs()
331 }
332
333 fn execute_mast_node(
337 &mut self,
338 node_id: MastNodeId,
339 program: &MastForest,
340 host: &mut impl SyncHost,
341 ) -> Result<(), ExecutionError> {
342 let node = program
343 .get_node_by_id(node_id)
344 .ok_or(ExecutionError::MastNodeNotFoundInForest { node_id })?;
345
346 for &decorator_id in node.before_enter(program) {
347 self.execute_decorator(&program[decorator_id], host)?;
348 }
349
350 match node {
351 MastNode::Block(node) => self.execute_basic_block_node(node_id, node, program, host)?,
352 MastNode::Join(node) => self.execute_join_node(node, program, host)?,
353 MastNode::Split(node) => self.execute_split_node(node, program, host)?,
354 MastNode::Loop(node) => self.execute_loop_node(node, program, host)?,
355 MastNode::Call(node) => {
356 let err_ctx = err_ctx!(program, node, host);
357 add_error_ctx_to_external_error(
358 self.execute_call_node(node, program, host),
359 err_ctx,
360 )?
361 },
362 MastNode::Dyn(node) => {
363 let err_ctx = err_ctx!(program, node, host);
364 add_error_ctx_to_external_error(
365 self.execute_dyn_node(node, program, host),
366 err_ctx,
367 )?
368 },
369 MastNode::External(external_node) => {
370 let (root_id, mast_forest) = self.resolve_external_node(external_node, host)?;
371
372 self.execute_mast_node(root_id, &mast_forest, host)?;
373 },
374 }
375
376 for &decorator_id in node.after_exit(program) {
377 self.execute_decorator(&program[decorator_id], host)?;
378 }
379
380 Ok(())
381 }
382
383 #[inline(always)]
385 fn execute_join_node(
386 &mut self,
387 node: &JoinNode,
388 program: &MastForest,
389 host: &mut impl SyncHost,
390 ) -> Result<(), ExecutionError> {
391 self.start_join_node(node, program, host)?;
392
393 self.execute_mast_node(node.first(), program, host)?;
395 self.execute_mast_node(node.second(), program, host)?;
396
397 self.end_join_node(node, program, host)
398 }
399
400 #[inline(always)]
402 fn execute_split_node(
403 &mut self,
404 node: &SplitNode,
405 program: &MastForest,
406 host: &mut impl SyncHost,
407 ) -> Result<(), ExecutionError> {
408 let condition = self.start_split_node(node, program, host)?;
410
411 if condition == ONE {
413 self.execute_mast_node(node.on_true(), program, host)?;
414 } else if condition == ZERO {
415 self.execute_mast_node(node.on_false(), program, host)?;
416 } else {
417 let err_ctx = err_ctx!(program, node, host);
418 return Err(ExecutionError::not_binary_value_if(condition, &err_ctx));
419 }
420
421 self.end_split_node(node, program, host)
422 }
423
424 #[inline(always)]
426 fn execute_loop_node(
427 &mut self,
428 node: &LoopNode,
429 program: &MastForest,
430 host: &mut impl SyncHost,
431 ) -> Result<(), ExecutionError> {
432 let condition = self.start_loop_node(node, program, host)?;
434
435 if condition == ONE {
437 self.execute_mast_node(node.body(), program, host)?;
439
440 while self.stack.peek() == ONE {
444 self.decoder.repeat();
445 self.execute_op(Operation::Drop, program, host)?;
446 self.execute_mast_node(node.body(), program, host)?;
447 }
448
449 if self.stack.peek() != ZERO {
450 let err_ctx = err_ctx!(program, node, host);
451 return Err(ExecutionError::not_binary_value_loop(self.stack.peek(), &err_ctx));
452 }
453
454 self.end_loop_node(node, true, program, host)
456 } else if condition == ZERO {
457 self.end_loop_node(node, false, program, host)
460 } else {
461 let err_ctx = err_ctx!(program, node, host);
462 Err(ExecutionError::not_binary_value_loop(condition, &err_ctx))
463 }
464 }
465
466 #[inline(always)]
468 fn execute_call_node(
469 &mut self,
470 call_node: &CallNode,
471 program: &MastForest,
472 host: &mut impl SyncHost,
473 ) -> Result<(), ExecutionError> {
474 if call_node.is_syscall() {
476 let callee = program.get_node_by_id(call_node.callee()).ok_or_else(|| {
477 ExecutionError::MastNodeNotFoundInForest { node_id: call_node.callee() }
478 })?;
479 let err_ctx = err_ctx!(program, call_node, host);
480 self.chiplets.kernel_rom.access_proc(callee.digest(), &err_ctx)?;
481 }
482 let err_ctx = err_ctx!(program, call_node, host);
483
484 self.start_call_node(call_node, program, host, &err_ctx)?;
485 self.execute_mast_node(call_node.callee(), program, host)?;
486 self.end_call_node(call_node, program, host, &err_ctx)
487 }
488
489 #[inline(always)]
494 fn execute_dyn_node(
495 &mut self,
496 node: &DynNode,
497 program: &MastForest,
498 host: &mut impl SyncHost,
499 ) -> Result<(), ExecutionError> {
500 let err_ctx = err_ctx!(program, node, host);
501
502 let callee_hash = if node.is_dyncall() {
503 self.start_dyncall_node(node, &err_ctx)?
504 } else {
505 self.start_dyn_node(node, program, host, &err_ctx)?
506 };
507
508 match program.find_procedure_root(callee_hash) {
512 Some(callee_id) => self.execute_mast_node(callee_id, program, host)?,
513 None => {
514 let mast_forest = host
515 .get_mast_forest(&callee_hash)
516 .ok_or_else(|| ExecutionError::dynamic_node_not_found(callee_hash, &err_ctx))?;
517
518 let root_id = mast_forest
521 .find_procedure_root(callee_hash)
522 .ok_or(ExecutionError::malfored_mast_forest_in_host(callee_hash, &()))?;
523
524 self.advice
530 .extend_map(mast_forest.advice_map())
531 .map_err(|err| ExecutionError::advice_error(err, self.system.clk(), &()))?;
532
533 self.execute_mast_node(root_id, &mast_forest, host)?
534 },
535 }
536
537 if node.is_dyncall() {
538 self.end_dyncall_node(node, program, host, &err_ctx)
539 } else {
540 self.end_dyn_node(node, program, host)
541 }
542 }
543
544 #[inline(always)]
550 fn execute_basic_block_node(
551 &mut self,
552 node_id: MastNodeId,
553 basic_block: &BasicBlockNode,
554 program: &MastForest,
555 host: &mut impl SyncHost,
556 ) -> Result<(), ExecutionError> {
557 self.start_basic_block_node(basic_block, program, host)?;
558
559 let mut op_offset = 0;
560
561 self.execute_op_batch(basic_block, &basic_block.op_batches()[0], op_offset, program, host)?;
563 op_offset += basic_block.op_batches()[0].ops().len();
564
565 for op_batch in basic_block.op_batches().iter().skip(1) {
569 self.respan(op_batch);
570 self.execute_op(Operation::Noop, program, host)?;
571 self.execute_op_batch(basic_block, op_batch, op_offset, program, host)?;
572 op_offset += op_batch.ops().len();
573 }
574
575 self.end_basic_block_node(basic_block, program, host)?;
576
577 let num_ops = basic_block.num_operations() as usize;
583 for decorator in program.decorators_for_op(node_id, num_ops) {
584 self.execute_decorator(decorator, host)?;
585 }
586
587 Ok(())
588 }
589
590 #[inline(always)]
597 fn execute_op_batch(
598 &mut self,
599 basic_block: &BasicBlockNode,
600 batch: &OpBatch,
601 op_offset: usize,
602 program: &MastForest,
603 host: &mut impl SyncHost,
604 ) -> Result<(), ExecutionError> {
605 let end_indices = batch.end_indices();
606 let mut op_idx = 0;
607 let mut group_idx = 0;
608 let mut next_group_idx = 1;
609
610 let num_batch_groups = batch.num_groups().next_power_of_two();
614
615 let node_id = basic_block
617 .linked_id()
618 .expect("basic block node should be linked when executing operations");
619
620 for (i, &op) in batch.ops().iter().enumerate() {
622 let current_op_idx = i + op_offset;
624 for decorator in program.decorators_for_op(node_id, current_op_idx) {
625 self.execute_decorator(decorator, host)?;
626 }
627
628 let err_ctx = err_ctx!(program, basic_block, host, i + op_offset);
630 self.decoder.execute_user_op(op, op_idx);
631 self.execute_op_with_error_ctx(op, program, host, &err_ctx)?;
632
633 let has_imm = op.imm_value().is_some();
636 if has_imm {
637 next_group_idx += 1;
638 }
639
640 if i + 1 == end_indices[group_idx] {
642 group_idx = next_group_idx;
644 next_group_idx += 1;
645 op_idx = 0;
646
647 if group_idx < num_batch_groups {
650 self.decoder.start_op_group(batch.groups()[group_idx]);
651 }
652 } else {
653 op_idx += 1;
655 }
656 }
657
658 Ok(())
659 }
660
661 fn execute_decorator(
663 &mut self,
664 decorator: &Decorator,
665 host: &mut impl SyncHost,
666 ) -> Result<(), ExecutionError> {
667 match decorator {
668 Decorator::Debug(options) => {
669 if self.decoder.in_debug_mode() {
670 let process = &mut self.state();
671 let clk = process.clk();
672 host.on_debug(process, options)
673 .map_err(|err| ExecutionError::DebugHandlerError { clk, err })?;
674 }
675 },
676 Decorator::AsmOp(assembly_op) => {
677 if self.decoder.in_debug_mode() {
678 self.decoder.append_asmop(self.system.clk(), assembly_op.clone());
679 }
680 },
681 Decorator::Trace(id) => {
682 if self.enable_tracing {
683 let process = &mut self.state();
684 let clk = process.clk();
685 host.on_trace(process, *id).map_err(|err| {
686 ExecutionError::TraceHandlerError { clk, trace_id: *id, err }
687 })?;
688 }
689 },
690 };
691 Ok(())
692 }
693
694 fn resolve_external_node(
699 &mut self,
700 external_node: &ExternalNode,
701 host: &impl SyncHost,
702 ) -> Result<(MastNodeId, Arc<MastForest>), ExecutionError> {
703 let node_digest = external_node.digest();
704
705 let mast_forest = host
706 .get_mast_forest(&node_digest)
707 .ok_or(ExecutionError::no_mast_forest_with_procedure(node_digest, &()))?;
708
709 let root_id = mast_forest
712 .find_procedure_root(node_digest)
713 .ok_or(ExecutionError::malfored_mast_forest_in_host(node_digest, &()))?;
714
715 if mast_forest[root_id].is_external() {
718 return Err(ExecutionError::CircularExternalNode(node_digest));
719 }
720
721 self.advice
727 .extend_map(mast_forest.advice_map())
728 .map_err(|err| ExecutionError::advice_error(err, self.system.clk(), &()))?;
729
730 Ok((root_id, mast_forest))
731 }
732
733 pub const fn kernel(&self) -> &Kernel {
737 self.chiplets.kernel_rom.kernel()
738 }
739
740 pub fn into_parts(
741 self,
742 ) -> (System, Decoder, Stack, RangeChecker, Chiplets, PrecompileTranscriptState) {
743 (
744 self.system,
745 self.decoder,
746 self.stack,
747 self.range,
748 self.chiplets,
749 self.pc_transcript_state,
750 )
751 }
752}
753
754#[derive(Debug)]
755pub struct SlowProcessState<'a> {
756 advice: &'a mut AdviceProvider,
757 system: &'a System,
758 stack: &'a Stack,
759 chiplets: &'a Chiplets,
760}
761
762#[derive(Debug)]
766pub enum ProcessState<'a> {
767 Slow(SlowProcessState<'a>),
768 Fast(FastProcessState<'a>),
769 Noop(()),
772}
773
774impl Process {
775 #[inline(always)]
776 pub fn state(&mut self) -> ProcessState<'_> {
777 ProcessState::Slow(SlowProcessState {
778 advice: &mut self.advice,
779 system: &self.system,
780 stack: &self.stack,
781 chiplets: &self.chiplets,
782 })
783 }
784}
785
786impl<'a> ProcessState<'a> {
787 #[inline(always)]
789 pub fn advice_provider(&self) -> &AdviceProvider {
790 match self {
791 ProcessState::Slow(state) => state.advice,
792 ProcessState::Fast(state) => &state.processor.advice,
793 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
794 }
795 }
796
797 #[inline(always)]
799 pub fn advice_provider_mut(&mut self) -> &mut AdviceProvider {
800 match self {
801 ProcessState::Slow(state) => state.advice,
802 ProcessState::Fast(state) => &mut state.processor.advice,
803 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
804 }
805 }
806
807 #[inline(always)]
809 pub fn clk(&self) -> RowIndex {
810 match self {
811 ProcessState::Slow(state) => state.system.clk(),
812 ProcessState::Fast(state) => state.processor.clk,
813 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
814 }
815 }
816
817 #[inline(always)]
819 pub fn ctx(&self) -> ContextId {
820 match self {
821 ProcessState::Slow(state) => state.system.ctx(),
822 ProcessState::Fast(state) => state.processor.ctx,
823 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
824 }
825 }
826
827 #[inline(always)]
831 pub fn get_stack_item(&self, pos: usize) -> Felt {
832 match self {
833 ProcessState::Slow(state) => state.stack.get(pos),
834 ProcessState::Fast(state) => state.processor.stack_get(pos),
835 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
836 }
837 }
838
839 #[inline(always)]
853 pub fn get_stack_word_be(&self, start_idx: usize) -> Word {
854 match self {
855 ProcessState::Slow(state) => state.stack.get_word(start_idx),
856 ProcessState::Fast(state) => state.processor.stack_get_word(start_idx),
857 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
858 }
859 }
860
861 #[inline(always)]
875 pub fn get_stack_word_le(&self, start_idx: usize) -> Word {
876 let mut word = self.get_stack_word_be(start_idx);
877 word.reverse();
878 word
879 }
880
881 #[deprecated(
889 since = "0.19.0",
890 note = "Use `get_stack_word_be()` or `get_stack_word_le()` to make endianness explicit"
891 )]
892 #[inline(always)]
893 pub fn get_stack_word(&self, start_idx: usize) -> Word {
894 self.get_stack_word_be(start_idx)
895 }
896
897 #[inline(always)]
900 pub fn get_stack_state(&self) -> Vec<Felt> {
901 match self {
902 ProcessState::Slow(state) => state.stack.get_state_at(state.system.clk()),
903 ProcessState::Fast(state) => state.processor.stack().iter().rev().copied().collect(),
904 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
905 }
906 }
907
908 #[inline(always)]
911 pub fn get_mem_value(&self, ctx: ContextId, addr: u32) -> Option<Felt> {
912 match self {
913 ProcessState::Slow(state) => state.chiplets.memory.get_value(ctx, addr),
914 ProcessState::Fast(state) => state.processor.memory.read_element_impl(ctx, addr),
915 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
916 }
917 }
918
919 #[inline(always)]
924 pub fn get_mem_word(&self, ctx: ContextId, addr: u32) -> Result<Option<Word>, MemoryError> {
925 match self {
926 ProcessState::Slow(state) => state.chiplets.memory.get_word(ctx, addr),
927 ProcessState::Fast(state) => {
928 state.processor.memory.read_word_impl(ctx, addr, None, &())
929 },
930 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
931 }
932 }
933
934 pub fn get_mem_addr_range(
937 &self,
938 start_idx: usize,
939 end_idx: usize,
940 ) -> Result<core::ops::Range<u32>, MemoryError> {
941 let start_addr = self.get_stack_item(start_idx).as_int();
942 let end_addr = self.get_stack_item(end_idx).as_int();
943
944 if start_addr > u32::MAX as u64 {
945 return Err(MemoryError::address_out_of_bounds(start_addr, &()));
946 }
947 if end_addr > u32::MAX as u64 {
948 return Err(MemoryError::address_out_of_bounds(end_addr, &()));
949 }
950
951 if start_addr > end_addr {
952 return Err(MemoryError::InvalidMemoryRange { start_addr, end_addr });
953 }
954
955 Ok(start_addr as u32..end_addr as u32)
956 }
957
958 #[inline(always)]
964 pub fn get_mem_state(&self, ctx: ContextId) -> Vec<(MemoryAddress, Felt)> {
965 match self {
966 ProcessState::Slow(state) => {
967 state.chiplets.memory.get_state_at(ctx, state.system.clk())
968 },
969 ProcessState::Fast(state) => state.processor.memory.get_memory_state(ctx),
970 ProcessState::Noop(()) => panic!("attempted to access Noop process state"),
971 }
972 }
973}
974
975impl<'a> From<&'a mut Process> for ProcessState<'a> {
976 fn from(process: &'a mut Process) -> Self {
977 process.state()
978 }
979}
980
981pub(crate) fn add_error_ctx_to_external_error(
987 result: Result<(), ExecutionError>,
988 err_ctx: impl ErrorContext,
989) -> Result<(), ExecutionError> {
990 match result {
991 Ok(_) => Ok(()),
992 Err(err) => match err {
994 ExecutionError::NoMastForestWithProcedure { label, source_file: _, root_digest }
995 | ExecutionError::MalformedMastForestInHost { label, source_file: _, root_digest } => {
996 if label == SourceSpan::UNKNOWN {
997 let err_with_ctx =
998 ExecutionError::no_mast_forest_with_procedure(root_digest, &err_ctx);
999 Err(err_with_ctx)
1000 } else {
1001 Err(err)
1005 }
1006 },
1007
1008 _ => {
1009 Err(err)
1011 },
1012 },
1013 }
1014}