miden_processor/
lib.rs

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
94// RE-EXPORTS
95// ================================================================================================
96
97pub 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// TYPE ALIASES
114// ================================================================================================
115
116#[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// EXECUTORS
181// ================================================================================================
182
183/// Returns an execution trace resulting from executing the provided program against the provided
184/// inputs.
185///
186/// The `host` parameter is used to provide the external environment to the program being executed,
187/// such as access to the advice provider and libraries that the program depends on.
188#[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
203/// Returns an iterator which allows callers to step through the execution and inspect VM state at
204/// each execution step.
205pub 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// PROCESS
224// ================================================================================================
225
226/// A [Process] is the underlying execution engine for a Miden [Program].
227///
228/// Typically, you do not need to worry about, or use [Process] directly, instead you should prefer
229/// to use either [execute] or [execute_iter], which also handle setting up the process state,
230/// inputs, as well as compute the [ExecutionTrace] for the program.
231///
232/// However, for situations in which you want finer-grained control over those steps, you will need
233/// to construct an instance of [Process] using [Process::new], invoke [Process::execute], and then
234/// get the execution trace using [ExecutionTrace::new] using the outputs produced by execution.
235#[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    /// Precompile transcript state (sponge capacity) used by `log_precompile`.
246    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    /// Precompile transcript state (sponge capacity) used by `log_precompile`.
260    pub pc_transcript_state: PrecompileTranscriptState,
261}
262
263impl Process {
264    // CONSTRUCTORS
265    // --------------------------------------------------------------------------------------------
266    /// Creates a new process with the provided inputs.
267    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    /// Creates a new process with provided inputs and debug options enabled.
277    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    // PROGRAM EXECUTOR
312    // --------------------------------------------------------------------------------------------
313
314    /// Executes the provided [`Program`] in this process.
315    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    // NODE EXECUTORS
334    // --------------------------------------------------------------------------------------------
335
336    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    /// Executes the specified [JoinNode].
384    #[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        // execute first and then second child of the join block
394        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    /// Executes the specified [SplitNode].
401    #[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        // start the SPLIT block; this also pops the stack and returns the popped element
409        let condition = self.start_split_node(node, program, host)?;
410
411        // execute either the true or the false branch of the split block based on the condition
412        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    /// Executes the specified [LoopNode].
425    #[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        // start the LOOP block; this also pops the stack and returns the popped element
433        let condition = self.start_loop_node(node, program, host)?;
434
435        // if the top of the stack is ONE, execute the loop body; otherwise skip the loop body
436        if condition == ONE {
437            // execute the loop body at least once
438            self.execute_mast_node(node.body(), program, host)?;
439
440            // keep executing the loop body until the condition on the top of the stack is no
441            // longer ONE; each iteration of the loop is preceded by executing REPEAT operation
442            // which drops the condition from the stack
443            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            // end the LOOP block and drop the condition from the stack
455            self.end_loop_node(node, true, program, host)
456        } else if condition == ZERO {
457            // end the LOOP block, but don't drop the condition from the stack because it was
458            // already dropped when we started the LOOP block
459            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    /// Executes the specified [CallNode].
467    #[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 this is a syscall, make sure the call target exists in the kernel
475        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    /// Executes the specified [miden_core::mast::DynNode].
490    ///
491    /// The MAST root of the callee is assumed to be at the top of the stack, and the callee is
492    /// expected to be either in the current `program` or in the host.
493    #[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        // if the callee is not in the program's MAST forest, try to find a MAST forest for it in
509        // the host (corresponding to an external library loaded in the host); if none are
510        // found, return an error.
511        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                // We limit the parts of the program that can be called externally to procedure
519                // roots, even though MAST doesn't have that restriction.
520                let root_id = mast_forest
521                    .find_procedure_root(callee_hash)
522                    .ok_or(ExecutionError::malfored_mast_forest_in_host(callee_hash, &()))?;
523
524                // Merge the advice map of this forest into the advice provider.
525                // Note that the map may be merged multiple times if a different procedure from the
526                // same forest is called.
527                // For now, only compiled libraries contain non-empty advice maps, so for most
528                // cases, this call will be cheap.
529                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    /// Executes the specified [BasicBlockNode].
545    ///
546    /// # Arguments
547    /// * `node_id` - The ID of this basic block node in the `program` MAST forest. This should
548    ///   match the ID in `basic_block.decorators` when it's `Linked`.
549    #[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        // execute the first operation batch
562        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        // if the span contains more operation batches, execute them. each additional batch is
566        // preceded by a RESPAN operation; executing RESPAN operation does not change the state
567        // of the stack
568        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        // execute any decorators which have not been executed during span ops execution; this
578        // can happen for decorators appearing after all operations in a block. these decorators
579        // are executed after BASIC BLOCK is closed to make sure the VM clock cycle advances beyond
580        // the last clock cycle of the BASIC BLOCK ops.
581        // For the linked case, check for decorators at an operation index beyond the last operation
582        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    /// Executes all operations in an [OpBatch]. This also ensures that all alignment rules are
591    /// satisfied by executing NOOPs as needed. Specifically:
592    /// - If an operation group ends with an operation carrying an immediate value, a NOOP is
593    ///   executed after it.
594    /// - If the number of groups in a batch is not a power of 2, NOOPs are executed (one per group)
595    ///   to bring it up to the next power of two (e.g., 3 -> 4, 5 -> 8).
596    #[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        // round up the number of groups to be processed to the next power of two; we do this
611        // because the processor requires the number of groups to be either 1, 2, 4, or 8; if
612        // the actual number of groups is smaller, we'll pad the batch with NOOPs at the end
613        let num_batch_groups = batch.num_groups().next_power_of_two();
614
615        // Get the node ID once since it doesn't change within the loop
616        let node_id = basic_block
617            .linked_id()
618            .expect("basic block node should be linked when executing operations");
619
620        // execute operations in the batch one by one
621        for (i, &op) in batch.ops().iter().enumerate() {
622            // Use the forest's decorator storage to get decorators for this operation
623            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            // decode and execute the operation
629            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            // if the operation carries an immediate value, the value is stored at the next group
634            // pointer; so, we advance the pointer to the following group
635            let has_imm = op.imm_value().is_some();
636            if has_imm {
637                next_group_idx += 1;
638            }
639
640            // determine if we've executed all non-decorator operations in a group
641            if i + 1 == end_indices[group_idx] {
642                // move to the next group and reset operation index
643                group_idx = next_group_idx;
644                next_group_idx += 1;
645                op_idx = 0;
646
647                // if we haven't reached the end of the batch yet, set up the decoder for
648                // decoding the next operation group
649                if group_idx < num_batch_groups {
650                    self.decoder.start_op_group(batch.groups()[group_idx]);
651                }
652            } else {
653                // if we are not at the end of the group, just increment the operation index
654                op_idx += 1;
655            }
656        }
657
658        Ok(())
659    }
660
661    /// Executes the specified decorator
662    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    /// Resolves an external node reference to a procedure root using the [`MastForest`] store in
695    /// the provided host.
696    ///
697    /// The [`MastForest`] for the procedure is cached to avoid additional queries to the host.
698    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        // We limit the parts of the program that can be called externally to procedure
710        // roots, even though MAST doesn't have that restriction.
711        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 the node that we got by looking up an external reference is also an External
716        // node, we are about to enter into an infinite loop - so, return an error
717        if mast_forest[root_id].is_external() {
718            return Err(ExecutionError::CircularExternalNode(node_digest));
719        }
720
721        // Merge the advice map of this forest into the advice provider.
722        // Note that the map may be merged multiple times if a different procedure from the same
723        // forest is called.
724        // For now, only compiled libraries contain non-empty advice maps, so for most cases,
725        // this call will be cheap.
726        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    // PUBLIC ACCESSORS
734    // ================================================================================================
735
736    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// PROCESS STATE
763// ================================================================================================
764
765#[derive(Debug)]
766pub enum ProcessState<'a> {
767    Slow(SlowProcessState<'a>),
768    Fast(FastProcessState<'a>),
769    /// A process state that does nothing. Calling any of its methods results in a panic. It is
770    /// expected to be used in conjunction with the `NoopHost`.
771    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    /// Returns a reference to the advice provider.
788    #[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    /// Returns a mutable reference to the advice provider.
798    #[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    /// Returns the current clock cycle of a process.
808    #[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    /// Returns the current execution context ID.
818    #[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    /// Returns the value located at the specified position on the stack at the current clock cycle.
828    ///
829    /// This method can access elements beyond the top 16 positions by using the overflow table.
830    #[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    /// Returns a word starting at the specified element index on the stack in big-endian
840    /// (reversed) order.
841    ///
842    /// The word is formed by taking 4 consecutive elements starting from the specified index.
843    /// For example, start_idx=0 creates a word from stack elements 0-3, start_idx=1 creates
844    /// a word from elements 1-4, etc.
845    ///
846    /// In big-endian order, stack element N+3 will be at position 0 of the word, N+2 at
847    /// position 1, N+1 at position 2, and N at position 3. This matches the behavior of
848    /// `mem_loadw_be` where `mem[a+3]` ends up on top of the stack.
849    ///
850    /// This method can access elements beyond the top 16 positions by using the overflow table.
851    /// Creating a word does not change the state of the stack.
852    #[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    /// Returns a word starting at the specified element index on the stack in little-endian
862    /// (memory) order.
863    ///
864    /// The word is formed by taking 4 consecutive elements starting from the specified index.
865    /// For example, start_idx=0 creates a word from stack elements 0-3, start_idx=1 creates
866    /// a word from elements 1-4, etc.
867    ///
868    /// In little-endian order, stack element N will be at position 0 of the word, N+1 at
869    /// position 1, N+2 at position 2, and N+3 at position 3. This matches the behavior of
870    /// `mem_loadw_le` where `mem[a]` ends up on top of the stack.
871    ///
872    /// This method can access elements beyond the top 16 positions by using the overflow table.
873    /// Creating a word does not change the state of the stack.
874    #[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    /// Returns a word starting at the specified element index on the stack.
882    ///
883    /// This is an alias for [`Self::get_stack_word_be`] for backward compatibility. For new code,
884    /// prefer using the explicit `get_stack_word_be()` or `get_stack_word_le()` to make the
885    /// ordering expectations clear.
886    ///
887    /// See [`Self::get_stack_word_be`] for detailed documentation.
888    #[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    /// Returns stack state at the current clock cycle. This includes the top 16 items of the
898    /// stack + overflow entries.
899    #[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    /// Returns the element located at the specified context/address, or None if the address hasn't
909    /// been accessed previously.
910    #[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    /// Returns the batch of elements starting at the specified context/address.
920    ///
921    /// # Errors
922    /// - If the address is not word aligned.
923    #[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    /// Reads (start_addr, end_addr) tuple from the specified elements of the operand stack (
935    /// without modifying the state of the stack), and verifies that memory range is valid.
936    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    /// Returns the entire memory state for the specified execution context at the current clock
959    /// cycle.
960    ///
961    /// The state is returned as a vector of (address, value) tuples, and includes addresses which
962    /// have been accessed at least once.
963    #[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
981// HELPERS
982// ================================================================================================
983
984/// For errors generated from processing an `ExternalNode`, returns the same error except with
985/// proper error context.
986pub(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        // Add context information to any errors coming from executing an `ExternalNode`
993        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                    // If the source span was already populated, just return the error as-is. This
1002                    // would occur when a call deeper down the call stack was responsible for the
1003                    // error.
1004                    Err(err)
1005                }
1006            },
1007
1008            _ => {
1009                // do nothing
1010                Err(err)
1011            },
1012        },
1013    }
1014}