Skip to main content

miden_processor/fast/
mod.rs

1#[cfg(test)]
2use alloc::rc::Rc;
3use alloc::{boxed::Box, sync::Arc, vec::Vec};
4#[cfg(test)]
5use core::cell::Cell;
6use core::{cmp::min, ops::ControlFlow};
7
8use miden_air::{Felt, trace::RowIndex};
9use miden_core::{
10    EMPTY_WORD, WORD_SIZE, Word, ZERO,
11    mast::{MastForest, MastNodeExt, MastNodeId},
12    operations::Decorator,
13    precompile::PrecompileTranscript,
14    program::{Kernel, MIN_STACK_DEPTH, Program, StackInputs, StackOutputs},
15    utils::range,
16};
17use tracing::instrument;
18
19use crate::{
20    AdviceInputs, AdviceProvider, ContextId, ExecutionError, ExecutionOptions, Host,
21    ProcessorState, Stopper,
22    continuation_stack::{Continuation, ContinuationStack},
23    errors::{MapExecErr, MapExecErrNoCtx, OperationError},
24    execution::{
25        InternalBreakReason, execute_impl, finish_emit_op_execution,
26        finish_load_mast_forest_from_dyn_start, finish_load_mast_forest_from_external,
27    },
28    trace::execution_tracer::{ExecutionTracer, TraceGenerationContext},
29    tracer::{OperationHelperRegisters, Tracer},
30};
31
32mod basic_block;
33mod call_and_dyn;
34mod external;
35mod memory;
36mod operation;
37mod step;
38
39pub use basic_block::SystemEventError;
40use external::maybe_use_caller_error_context;
41pub use memory::Memory;
42pub use step::{BreakReason, ResumeContext};
43use step::{NeverStopper, StepStopper};
44
45#[cfg(test)]
46mod tests;
47
48// CONSTANTS
49// ================================================================================================
50
51/// The size of the stack buffer.
52///
53/// Note: This value is much larger than it needs to be for the majority of programs. However, some
54/// existing programs need it, so we're forced to push it up (though this should be double-checked).
55/// At this high a value, we're starting to see some performance degradation on benchmarks. For
56/// example, the blake3 benchmark went from 285 MHz to 250 MHz (~10% degradation). Perhaps a better
57/// solution would be to make this value much smaller (~1000), and then fallback to a `Vec` if the
58/// stack overflows.
59const STACK_BUFFER_SIZE: usize = 6850;
60
61/// The initial position of the top of the stack in the stack buffer.
62///
63/// We place this value close to 0 because if a program hits the limit, it's much more likely to hit
64/// the upper bound than the lower bound, since hitting the lower bound only occurs when you drop
65/// 0's that were generated automatically to keep the stack depth at 16. In practice, if this
66/// occurs, it is most likely a bug.
67const INITIAL_STACK_TOP_IDX: usize = 250;
68
69// FAST PROCESSOR
70// ================================================================================================
71
72/// A fast processor which doesn't generate any trace.
73///
74/// This processor is designed to be as fast as possible. Hence, it only keeps track of the current
75/// state of the processor (i.e. the stack, current clock cycle, current memory context, and free
76/// memory pointer).
77///
78/// # Stack Management
79/// A few key points about how the stack was designed for maximum performance:
80///
81/// - The stack has a fixed buffer size defined by `STACK_BUFFER_SIZE`.
82///     - This was observed to increase performance by at least 2x compared to using a `Vec` with
83///       `push()` & `pop()`.
84///     - We track the stack top and bottom using indices `stack_top_idx` and `stack_bot_idx`,
85///       respectively.
86/// - Since we are using a fixed-size buffer, we need to ensure that stack buffer accesses are not
87///   out of bounds. Naively, we could check for this on every access. However, every operation
88///   alters the stack depth by a predetermined amount, allowing us to precisely determine the
89///   minimum number of operations required to reach a stack buffer boundary, whether at the top or
90///   bottom.
91///     - For example, if the stack top is 10 elements away from the top boundary, and the stack
92///       bottom is 15 elements away from the bottom boundary, then we can safely execute 10
93///       operations that modify the stack depth with no bounds check.
94/// - When switching contexts (e.g., during a call or syscall), all elements past the first 16 are
95///   stored in an `ExecutionContextInfo` struct, and the stack is truncated to 16 elements. This
96///   will be restored when returning from the call or syscall.
97///
98/// # Clock Cycle Management
99/// - The clock cycle (`clk`) is managed in the same way as in `Process`. That is, it is incremented
100///   by 1 for every row that `Process` adds to the main trace.
101///     - It is important to do so because the clock cycle is used to determine the context ID for
102///       new execution contexts when using `call` or `dyncall`.
103#[derive(Debug)]
104pub struct FastProcessor {
105    /// The stack is stored in reverse order, so that the last element is at the top of the stack.
106    stack: Box<[Felt; STACK_BUFFER_SIZE]>,
107    /// The index of the top of the stack.
108    stack_top_idx: usize,
109    /// The index of the bottom of the stack.
110    stack_bot_idx: usize,
111
112    /// The current clock cycle.
113    clk: RowIndex,
114
115    /// The current context ID.
116    ctx: ContextId,
117
118    /// The hash of the function that called into the current context, or `[ZERO, ZERO, ZERO,
119    /// ZERO]` if we are in the first context (i.e. when `call_stack` is empty).
120    caller_hash: Word,
121
122    /// The advice provider to be used during execution.
123    advice: AdviceProvider,
124
125    /// A map from (context_id, word_address) to the word stored starting at that memory location.
126    memory: Memory,
127
128    /// The call stack is used when starting a new execution context (from a `call`, `syscall` or
129    /// `dyncall`) to keep track of the information needed to return to the previous context upon
130    /// return. It is a stack since calls can be nested.
131    call_stack: Vec<ExecutionContextInfo>,
132
133    /// Options for execution, including but not limited to whether debug or tracing is enabled,
134    /// the size of core trace fragments during execution, etc.
135    options: ExecutionOptions,
136
137    /// Transcript used to record commitments via `log_precompile` instruction (implemented via
138    /// Poseidon2 sponge).
139    pc_transcript: PrecompileTranscript,
140
141    /// Tracks decorator retrieval calls for testing.
142    #[cfg(test)]
143    pub decorator_retrieval_count: Rc<Cell<usize>>,
144}
145
146impl FastProcessor {
147    // CONSTRUCTORS
148    // ----------------------------------------------------------------------------------------------
149
150    /// Creates a new `FastProcessor` instance with the given stack inputs.
151    ///
152    /// By default, advice inputs are empty and execution options use their defaults
153    /// (debugging and tracing disabled).
154    ///
155    /// # Example
156    /// ```ignore
157    /// use miden_processor::FastProcessor;
158    ///
159    /// let processor = FastProcessor::new(stack_inputs)
160    ///     .with_advice(advice_inputs)
161    ///     .with_debugging(true)
162    ///     .with_tracing(true);
163    /// ```
164    pub fn new(stack_inputs: StackInputs) -> Self {
165        Self::new_with_options(stack_inputs, AdviceInputs::default(), ExecutionOptions::default())
166    }
167
168    /// Sets the advice inputs for the processor.
169    pub fn with_advice(mut self, advice_inputs: AdviceInputs) -> Self {
170        self.advice = advice_inputs.into();
171        self
172    }
173
174    /// Sets the execution options for the processor.
175    ///
176    /// This will override any previously set debugging or tracing settings.
177    pub fn with_options(mut self, options: ExecutionOptions) -> Self {
178        self.options = options;
179        self
180    }
181
182    /// Enables or disables debugging mode.
183    ///
184    /// When debugging is enabled, debug decorators will be executed during program execution.
185    pub fn with_debugging(mut self, enabled: bool) -> Self {
186        self.options = self.options.with_debugging(enabled);
187        self
188    }
189
190    /// Enables or disables tracing mode.
191    ///
192    /// When tracing is enabled, trace decorators will be executed during program execution.
193    pub fn with_tracing(mut self, enabled: bool) -> Self {
194        self.options = self.options.with_tracing(enabled);
195        self
196    }
197
198    /// Constructor for creating a `FastProcessor` with all options specified at once.
199    ///
200    /// For a more fluent API, consider using `FastProcessor::new()` with builder methods.
201    pub fn new_with_options(
202        stack_inputs: StackInputs,
203        advice_inputs: AdviceInputs,
204        options: ExecutionOptions,
205    ) -> Self {
206        let stack_top_idx = INITIAL_STACK_TOP_IDX;
207        let stack = {
208            // Note: we use `Vec::into_boxed_slice()` here, since `Box::new([T; N])` first allocates
209            // the array on the stack, and then moves it to the heap. This might cause a
210            // stack overflow on some systems.
211            let mut stack: Box<[Felt; STACK_BUFFER_SIZE]> =
212                vec![ZERO; STACK_BUFFER_SIZE].into_boxed_slice().try_into().unwrap();
213
214            // Copy inputs in reverse order so first element ends up at top of stack
215            for (i, &input) in stack_inputs.iter().enumerate() {
216                stack[stack_top_idx - 1 - i] = input;
217            }
218            stack
219        };
220
221        Self {
222            advice: advice_inputs.into(),
223            stack,
224            stack_top_idx,
225            stack_bot_idx: stack_top_idx - MIN_STACK_DEPTH,
226            clk: 0_u32.into(),
227            ctx: 0_u32.into(),
228            caller_hash: EMPTY_WORD,
229            memory: Memory::new(),
230            call_stack: Vec::new(),
231            options,
232            pc_transcript: PrecompileTranscript::new(),
233            #[cfg(test)]
234            decorator_retrieval_count: Rc::new(Cell::new(0)),
235        }
236    }
237
238    /// Returns the resume context to be used with the first call to `step()`.
239    pub fn get_initial_resume_context(
240        &mut self,
241        program: &Program,
242    ) -> Result<ResumeContext, ExecutionError> {
243        self.advice
244            .extend_map(program.mast_forest().advice_map())
245            .map_exec_err_no_ctx()?;
246
247        Ok(ResumeContext {
248            current_forest: program.mast_forest().clone(),
249            continuation_stack: ContinuationStack::new(program),
250            kernel: program.kernel().clone(),
251        })
252    }
253
254    // ACCESSORS
255    // -------------------------------------------------------------------------------------------
256
257    /// Returns whether the processor is executing in debug mode.
258    #[inline(always)]
259    pub fn in_debug_mode(&self) -> bool {
260        self.options.enable_debugging()
261    }
262
263    /// Returns true if decorators should be executed.
264    ///
265    /// This corresponds to either being in debug mode (for debug decorators) or having tracing
266    /// enabled (for trace decorators).
267    #[inline(always)]
268    fn should_execute_decorators(&self) -> bool {
269        self.in_debug_mode() || self.options.enable_tracing()
270    }
271
272    #[cfg(test)]
273    #[inline(always)]
274    fn record_decorator_retrieval(&self) {
275        self.decorator_retrieval_count.set(self.decorator_retrieval_count.get() + 1);
276    }
277
278    /// Returns the size of the stack.
279    #[inline(always)]
280    fn stack_size(&self) -> usize {
281        self.stack_top_idx - self.stack_bot_idx
282    }
283
284    /// Returns the stack, such that the top of the stack is at the last index of the returned
285    /// slice.
286    pub fn stack(&self) -> &[Felt] {
287        &self.stack[self.stack_bot_idx..self.stack_top_idx]
288    }
289
290    /// Returns the top 16 elements of the stack.
291    pub fn stack_top(&self) -> &[Felt] {
292        &self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
293    }
294
295    /// Returns a mutable reference to the top 16 elements of the stack.
296    pub fn stack_top_mut(&mut self) -> &mut [Felt] {
297        &mut self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
298    }
299
300    /// Returns the element on the stack at index `idx`.
301    ///
302    /// This method is only meant to be used to access the stack top by operation handlers, and
303    /// system event handlers.
304    ///
305    /// # Preconditions
306    /// - `idx` must be less than or equal to 15.
307    #[inline(always)]
308    pub fn stack_get(&self, idx: usize) -> Felt {
309        self.stack[self.stack_top_idx - idx - 1]
310    }
311
312    /// Same as [`Self::stack_get()`], but returns [`ZERO`] if `idx` falls below index 0 in the
313    /// stack buffer.
314    ///
315    /// Use this instead of `stack_get()` when `idx` may exceed 15.
316    #[inline(always)]
317    pub fn stack_get_safe(&self, idx: usize) -> Felt {
318        if idx < self.stack_top_idx {
319            self.stack[self.stack_top_idx - idx - 1]
320        } else {
321            ZERO
322        }
323    }
324
325    /// Mutable variant of `stack_get()`.
326    ///
327    /// This method is only meant to be used to access the stack top by operation handlers, and
328    /// system event handlers.
329    ///
330    /// # Preconditions
331    /// - `idx` must be less than or equal to 15.
332    #[inline(always)]
333    pub fn stack_get_mut(&mut self, idx: usize) -> &mut Felt {
334        &mut self.stack[self.stack_top_idx - idx - 1]
335    }
336
337    /// Returns the word on the stack starting at index `start_idx` in "stack order".
338    ///
339    /// For `start_idx=0` the top element of the stack will be at position 0 in the word.
340    ///
341    /// For example, if the stack looks like this:
342    ///
343    /// top                                                       bottom
344    /// v                                                           v
345    /// a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p
346    ///
347    /// Then
348    /// - `stack_get_word(0)` returns `[a, b, c, d]`,
349    /// - `stack_get_word(1)` returns `[b, c, d, e]`,
350    /// - etc.
351    ///
352    /// This method is only meant to be used to access the stack top by operation handlers, and
353    /// system event handlers.
354    ///
355    /// # Preconditions
356    /// - `start_idx` must be less than or equal to 12.
357    #[inline(always)]
358    pub fn stack_get_word(&self, start_idx: usize) -> Word {
359        // Ensure we have enough elements to form a complete word
360        debug_assert!(
361            start_idx + WORD_SIZE <= self.stack_depth() as usize,
362            "Not enough elements on stack to read word starting at index {start_idx}"
363        );
364
365        let word_start_idx = self.stack_top_idx - start_idx - WORD_SIZE;
366        let mut result: [Felt; WORD_SIZE] =
367            self.stack[range(word_start_idx, WORD_SIZE)].try_into().unwrap();
368        // Reverse so top of stack (idx 0) goes to word[0]
369        result.reverse();
370        result.into()
371    }
372
373    /// Same as [`Self::stack_get_word()`], but returns [`ZERO`] for any element that falls below
374    /// index 0 in the stack buffer.
375    ///
376    /// Use this instead of `stack_get_word()` when `start_idx + WORD_SIZE` may exceed
377    /// `stack_top_idx`.
378    #[inline(always)]
379    pub fn stack_get_word_safe(&self, start_idx: usize) -> Word {
380        let buf_end = self.stack_top_idx.saturating_sub(start_idx);
381        let buf_start = self.stack_top_idx.saturating_sub(start_idx.saturating_add(WORD_SIZE));
382        let num_elements_to_read_from_buf = buf_end - buf_start;
383
384        let mut result = [ZERO; WORD_SIZE];
385        if num_elements_to_read_from_buf == WORD_SIZE {
386            result.copy_from_slice(&self.stack[range(buf_start, WORD_SIZE)]);
387        } else if num_elements_to_read_from_buf > 0 {
388            let offset = WORD_SIZE - num_elements_to_read_from_buf;
389            result[offset..]
390                .copy_from_slice(&self.stack[range(buf_start, num_elements_to_read_from_buf)]);
391        }
392        result.reverse();
393
394        result.into()
395    }
396
397    /// Returns the number of elements on the stack in the current context.
398    #[inline(always)]
399    pub fn stack_depth(&self) -> u32 {
400        (self.stack_top_idx - self.stack_bot_idx) as u32
401    }
402
403    /// Returns a reference to the processor's memory.
404    pub fn memory(&self) -> &Memory {
405        &self.memory
406    }
407
408    /// Returns a reference to the execution options.
409    pub fn execution_options(&self) -> &ExecutionOptions {
410        &self.options
411    }
412
413    /// Returns a narrowed interface for reading and updating the processor state.
414    #[inline(always)]
415    pub fn state(&self) -> ProcessorState<'_> {
416        ProcessorState { processor: self }
417    }
418
419    // MUTATORS
420    // -------------------------------------------------------------------------------------------
421
422    /// Writes an element to the stack at the given index.
423    #[inline(always)]
424    pub fn stack_write(&mut self, idx: usize, element: Felt) {
425        self.stack[self.stack_top_idx - idx - 1] = element
426    }
427
428    /// Writes a word to the stack starting at the given index.
429    ///
430    /// `word[0]` goes to stack position start_idx (top), `word[1]` to start_idx+1, etc.
431    #[inline(always)]
432    pub fn stack_write_word(&mut self, start_idx: usize, word: &Word) {
433        debug_assert!(start_idx <= MIN_STACK_DEPTH - WORD_SIZE);
434
435        let word_start_idx = self.stack_top_idx - start_idx - 4;
436        let mut source: [Felt; WORD_SIZE] = (*word).into();
437        // Reverse so word[0] ends up at the top of stack (highest internal index)
438        source.reverse();
439        self.stack[range(word_start_idx, WORD_SIZE)].copy_from_slice(&source)
440    }
441
442    /// Swaps the elements at the given indices on the stack.
443    #[inline(always)]
444    pub fn stack_swap(&mut self, idx1: usize, idx2: usize) {
445        let a = self.stack_get(idx1);
446        let b = self.stack_get(idx2);
447        self.stack_write(idx1, b);
448        self.stack_write(idx2, a);
449    }
450
451    // EXECUTE
452    // -------------------------------------------------------------------------------------------
453
454    /// Executes the given program and returns the stack outputs as well as the advice provider.
455    pub async fn execute(
456        self,
457        program: &Program,
458        host: &mut impl Host,
459    ) -> Result<ExecutionOutput, ExecutionError> {
460        self.execute_with_tracer(program, host, &mut NoopTracer).await
461    }
462
463    /// Executes the given program and returns the stack outputs, the advice provider, and
464    /// context necessary to build the trace.
465    #[instrument(name = "execute_for_trace", skip_all)]
466    pub async fn execute_for_trace(
467        self,
468        program: &Program,
469        host: &mut impl Host,
470    ) -> Result<(ExecutionOutput, TraceGenerationContext), ExecutionError> {
471        let mut tracer = ExecutionTracer::new(self.options.core_trace_fragment_size());
472        let execution_output = self.execute_with_tracer(program, host, &mut tracer).await?;
473
474        let context = tracer.into_trace_generation_context();
475
476        Ok((execution_output, context))
477    }
478
479    /// Executes the given program with the provided tracer and returns the stack outputs, and the
480    /// advice provider.
481    pub async fn execute_with_tracer<T>(
482        mut self,
483        program: &Program,
484        host: &mut impl Host,
485        tracer: &mut T,
486    ) -> Result<ExecutionOutput, ExecutionError>
487    where
488        T: Tracer<Processor = Self>,
489    {
490        let mut continuation_stack = ContinuationStack::new(program);
491        let mut current_forest = program.mast_forest().clone();
492
493        // Merge the program's advice map into the advice provider
494        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
495
496        match self
497            .execute_impl(
498                &mut continuation_stack,
499                &mut current_forest,
500                program.kernel(),
501                host,
502                tracer,
503                &NeverStopper,
504            )
505            .await
506        {
507            ControlFlow::Continue(stack_outputs) => Ok(ExecutionOutput {
508                stack: stack_outputs,
509                advice: self.advice,
510                memory: self.memory,
511                final_pc_transcript: self.pc_transcript,
512            }),
513            ControlFlow::Break(break_reason) => match break_reason {
514                BreakReason::Err(err) => Err(err),
515                BreakReason::Stopped(_) => {
516                    unreachable!("Execution never stops prematurely with NeverStopper")
517                },
518            },
519        }
520    }
521
522    /// Executes a single clock cycle
523    pub async fn step(
524        &mut self,
525        host: &mut impl Host,
526        resume_ctx: ResumeContext,
527    ) -> Result<Option<ResumeContext>, ExecutionError> {
528        let ResumeContext {
529            mut current_forest,
530            mut continuation_stack,
531            kernel,
532        } = resume_ctx;
533
534        match self
535            .execute_impl(
536                &mut continuation_stack,
537                &mut current_forest,
538                &kernel,
539                host,
540                &mut NoopTracer,
541                &StepStopper,
542            )
543            .await
544        {
545            ControlFlow::Continue(_) => Ok(None),
546            ControlFlow::Break(break_reason) => match break_reason {
547                BreakReason::Err(err) => Err(err),
548                BreakReason::Stopped(maybe_continuation) => {
549                    if let Some(continuation) = maybe_continuation {
550                        continuation_stack.push_continuation(continuation);
551                    }
552
553                    Ok(Some(ResumeContext {
554                        current_forest,
555                        continuation_stack,
556                        kernel,
557                    }))
558                },
559            },
560        }
561    }
562
563    /// Executes the given program with the provided tracer and returns the stack outputs.
564    ///
565    /// This function takes a `&mut self` (compared to `self` for the public execute functions) so
566    /// that the processor state may be accessed after execution. It is incorrect to execute a
567    /// second program using the same processor. This is mainly meant to be used in tests.
568    async fn execute_impl<S, T>(
569        &mut self,
570        continuation_stack: &mut ContinuationStack,
571        current_forest: &mut Arc<MastForest>,
572        kernel: &Kernel,
573        host: &mut impl Host,
574        tracer: &mut T,
575        stopper: &S,
576    ) -> ControlFlow<BreakReason, StackOutputs>
577    where
578        S: Stopper<Processor = Self>,
579        T: Tracer<Processor = Self>,
580    {
581        while let ControlFlow::Break(internal_break_reason) =
582            execute_impl(self, continuation_stack, current_forest, kernel, host, tracer, stopper)
583        {
584            match internal_break_reason {
585                InternalBreakReason::User(break_reason) => return ControlFlow::Break(break_reason),
586                InternalBreakReason::Emit {
587                    basic_block_node_id,
588                    op_idx,
589                    continuation,
590                } => {
591                    self.op_emit(host, current_forest, basic_block_node_id, op_idx).await?;
592
593                    // Call `finish_emit_op_execution()`, as per the sans-IO contract.
594                    finish_emit_op_execution(
595                        continuation,
596                        self,
597                        continuation_stack,
598                        current_forest,
599                        tracer,
600                        stopper,
601                    )?;
602                },
603                InternalBreakReason::LoadMastForestFromDyn { dyn_node_id, callee_hash } => {
604                    // load mast forest asynchronously
605                    let (root_id, new_forest) = match self
606                        .load_mast_forest(callee_hash, host, current_forest, dyn_node_id)
607                        .await
608                    {
609                        Ok(result) => result,
610                        Err(err) => return ControlFlow::Break(BreakReason::Err(err)),
611                    };
612
613                    // Finish loading the MAST forest from the Dyn node, as per the sans-IO
614                    // contract.
615                    finish_load_mast_forest_from_dyn_start(
616                        root_id,
617                        new_forest,
618                        self,
619                        current_forest,
620                        continuation_stack,
621                        tracer,
622                        stopper,
623                    )?;
624                },
625                InternalBreakReason::LoadMastForestFromExternal {
626                    external_node_id,
627                    procedure_hash,
628                } => {
629                    // load mast forest asynchronously
630                    let (root_id, new_forest) = match self
631                        .load_mast_forest(procedure_hash, host, current_forest, external_node_id)
632                        .await
633                    {
634                        Ok(result) => result,
635                        Err(err) => {
636                            let maybe_enriched_err = maybe_use_caller_error_context(
637                                err,
638                                current_forest,
639                                continuation_stack,
640                                host,
641                            );
642
643                            return ControlFlow::Break(BreakReason::Err(maybe_enriched_err));
644                        },
645                    };
646
647                    // Finish loading the MAST forest from the External node, as per the sans-IO
648                    // contract.
649                    finish_load_mast_forest_from_external(
650                        root_id,
651                        new_forest,
652                        external_node_id,
653                        current_forest,
654                        continuation_stack,
655                        host,
656                        tracer,
657                    )?;
658                },
659            }
660        }
661
662        match StackOutputs::new(
663            &self.stack[self.stack_bot_idx..self.stack_top_idx]
664                .iter()
665                .rev()
666                .copied()
667                .collect::<Vec<_>>(),
668        ) {
669            Ok(stack_outputs) => ControlFlow::Continue(stack_outputs),
670            Err(_) => ControlFlow::Break(BreakReason::Err(ExecutionError::OutputStackOverflow(
671                self.stack_top_idx - self.stack_bot_idx - MIN_STACK_DEPTH,
672            ))),
673        }
674    }
675
676    // DECORATOR EXECUTORS
677    // --------------------------------------------------------------------------------------------
678
679    /// Executes the decorators that should be executed before entering a node.
680    fn execute_before_enter_decorators(
681        &self,
682        node_id: MastNodeId,
683        current_forest: &MastForest,
684        host: &mut impl Host,
685    ) -> ControlFlow<BreakReason> {
686        if !self.should_execute_decorators() {
687            return ControlFlow::Continue(());
688        }
689
690        #[cfg(test)]
691        self.record_decorator_retrieval();
692
693        let node = current_forest
694            .get_node_by_id(node_id)
695            .expect("internal error: node id {node_id} not found in current forest");
696
697        for &decorator_id in node.before_enter(current_forest) {
698            self.execute_decorator(&current_forest[decorator_id], host)?;
699        }
700
701        ControlFlow::Continue(())
702    }
703
704    /// Executes the decorators that should be executed after exiting a node.
705    fn execute_after_exit_decorators(
706        &self,
707        node_id: MastNodeId,
708        current_forest: &MastForest,
709        host: &mut impl Host,
710    ) -> ControlFlow<BreakReason> {
711        if !self.in_debug_mode() {
712            return ControlFlow::Continue(());
713        }
714
715        #[cfg(test)]
716        self.record_decorator_retrieval();
717
718        let node = current_forest
719            .get_node_by_id(node_id)
720            .expect("internal error: node id {node_id} not found in current forest");
721
722        for &decorator_id in node.after_exit(current_forest) {
723            self.execute_decorator(&current_forest[decorator_id], host)?;
724        }
725
726        ControlFlow::Continue(())
727    }
728
729    /// Executes the specified decorator
730    fn execute_decorator(
731        &self,
732        decorator: &Decorator,
733        host: &mut impl Host,
734    ) -> ControlFlow<BreakReason> {
735        match decorator {
736            Decorator::Debug(options) => {
737                if self.in_debug_mode() {
738                    let processor_state = self.state();
739                    if let Err(err) = host.on_debug(&processor_state, options) {
740                        return ControlFlow::Break(BreakReason::Err(
741                            crate::errors::HostError::DebugHandlerError { err }.into(),
742                        ));
743                    }
744                }
745            },
746            Decorator::Trace(id) => {
747                if self.options.enable_tracing() {
748                    let processor_state = self.state();
749                    if let Err(err) = host.on_trace(&processor_state, *id) {
750                        return ControlFlow::Break(BreakReason::Err(
751                            crate::errors::HostError::TraceHandlerError { trace_id: *id, err }
752                                .into(),
753                        ));
754                    }
755                }
756            },
757        };
758        ControlFlow::Continue(())
759    }
760
761    // HELPERS
762    // ----------------------------------------------------------------------------------------------
763
764    async fn load_mast_forest(
765        &mut self,
766        node_digest: Word,
767        host: &mut impl Host,
768        current_forest: &MastForest,
769        node_id: MastNodeId,
770    ) -> Result<(MastNodeId, Arc<MastForest>), ExecutionError> {
771        let mast_forest = host.get_mast_forest(&node_digest).await.ok_or_else(|| {
772            crate::errors::procedure_not_found_with_context(
773                node_digest,
774                current_forest,
775                node_id,
776                host,
777            )
778        })?;
779
780        // We limit the parts of the program that can be called externally to procedure
781        // roots, even though MAST doesn't have that restriction.
782        let root_id = mast_forest.find_procedure_root(node_digest).ok_or_else(|| {
783            Err::<(), _>(OperationError::MalformedMastForestInHost { root_digest: node_digest })
784                .map_exec_err(current_forest, node_id, host)
785                .unwrap_err()
786        })?;
787
788        // Merge the advice map of this forest into the advice provider.
789        // Note that the map may be merged multiple times if a different procedure from the same
790        // forest is called.
791        // For now, only compiled libraries contain non-empty advice maps, so for most cases,
792        // this call will be cheap.
793        self.advice.extend_map(mast_forest.advice_map()).map_exec_err(
794            current_forest,
795            node_id,
796            host,
797        )?;
798
799        Ok((root_id, mast_forest))
800    }
801
802    /// Increments the stack top pointer by 1.
803    ///
804    /// The bottom of the stack is never affected by this operation.
805    #[inline(always)]
806    fn increment_stack_size(&mut self) {
807        self.stack_top_idx += 1;
808    }
809
810    /// Decrements the stack top pointer by 1.
811    ///
812    /// The bottom of the stack is only decremented in cases where the stack depth would become less
813    /// than 16.
814    #[inline(always)]
815    fn decrement_stack_size(&mut self) {
816        if self.stack_top_idx == MIN_STACK_DEPTH {
817            // We no longer have any room in the stack buffer to decrement the stack size (which
818            // would cause the `stack_bot_idx` to go below 0). We therefore reset the stack to its
819            // original position.
820            self.reset_stack_in_buffer(INITIAL_STACK_TOP_IDX);
821        }
822
823        self.stack_top_idx -= 1;
824        self.stack_bot_idx = min(self.stack_bot_idx, self.stack_top_idx - MIN_STACK_DEPTH);
825    }
826
827    /// Resets the stack in the buffer to a new position, preserving the top 16 elements of the
828    /// stack.
829    ///
830    /// # Preconditions
831    /// - The stack is expected to have exactly 16 elements.
832    #[inline(always)]
833    fn reset_stack_in_buffer(&mut self, new_stack_top_idx: usize) {
834        debug_assert_eq!(self.stack_depth(), MIN_STACK_DEPTH as u32);
835
836        let new_stack_bot_idx = new_stack_top_idx - MIN_STACK_DEPTH;
837
838        // Copy stack to its new position
839        self.stack
840            .copy_within(self.stack_bot_idx..self.stack_top_idx, new_stack_bot_idx);
841
842        // Zero out stack below the new new_stack_bot_idx, since this is where overflow values
843        // come from, and are guaranteed to be ZERO. We don't need to zero out above
844        // `stack_top_idx`, since values there are never read before being written.
845        self.stack[0..new_stack_bot_idx].fill(ZERO);
846
847        // Update indices.
848        self.stack_bot_idx = new_stack_bot_idx;
849        self.stack_top_idx = new_stack_top_idx;
850    }
851
852    // SYNC WRAPPERS
853    // ----------------------------------------------------------------------------------------------
854
855    /// Convenience sync wrapper to [Self::step].
856    pub fn step_sync(
857        &mut self,
858        host: &mut impl Host,
859        resume_ctx: ResumeContext,
860    ) -> Result<Option<ResumeContext>, ExecutionError> {
861        // Create a new Tokio runtime and block on the async execution
862        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
863
864        let execution_output = rt.block_on(self.step(host, resume_ctx))?;
865
866        Ok(execution_output)
867    }
868
869    /// Executes the given program step by step (calling [`Self::step`] repeatedly) and returns the
870    /// stack outputs.
871    pub fn execute_by_step_sync(
872        mut self,
873        program: &Program,
874        host: &mut impl Host,
875    ) -> Result<StackOutputs, ExecutionError> {
876        // Create a new Tokio runtime and block on the async execution
877        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
878        let mut current_resume_ctx = self.get_initial_resume_context(program).unwrap();
879
880        rt.block_on(async {
881            loop {
882                match self.step(host, current_resume_ctx).await {
883                    Ok(maybe_resume_ctx) => match maybe_resume_ctx {
884                        Some(next_resume_ctx) => {
885                            current_resume_ctx = next_resume_ctx;
886                        },
887                        None => {
888                            // End of program was reached
889                            break Ok(StackOutputs::new(
890                                &self.stack[self.stack_bot_idx..self.stack_top_idx]
891                                    .iter()
892                                    .rev()
893                                    .copied()
894                                    .collect::<Vec<_>>(),
895                            )
896                            .unwrap());
897                        },
898                    },
899                    Err(err) => {
900                        break Err(err);
901                    },
902                }
903            }
904        })
905    }
906
907    /// Convenience sync wrapper to [Self::execute].
908    ///
909    /// This method is only available on non-wasm32 targets. On wasm32, use the
910    /// async `execute()` method directly since wasm32 runs in the browser's event loop.
911    ///
912    /// # Panics
913    /// Panics if called from within an existing Tokio runtime. Use the async `execute()`
914    /// method instead in async contexts.
915    #[cfg(not(target_arch = "wasm32"))]
916    pub fn execute_sync(
917        self,
918        program: &Program,
919        host: &mut impl Host,
920    ) -> Result<ExecutionOutput, ExecutionError> {
921        match tokio::runtime::Handle::try_current() {
922            Ok(_handle) => {
923                // We're already inside a Tokio runtime - this is not supported
924                // because we cannot safely create a nested runtime or move the
925                // non-Send host reference to another thread
926                panic!(
927                    "Cannot call execute_sync from within a Tokio runtime. \
928                     Use the async execute() method instead."
929                )
930            },
931            Err(_) => {
932                // No runtime exists - create one and use it
933                let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
934                rt.block_on(self.execute(program, host))
935            },
936        }
937    }
938
939    /// Convenience sync wrapper to [Self::execute_for_trace].
940    ///
941    /// This method is only available on non-wasm32 targets. On wasm32, use the
942    /// async `execute_for_trace()` method directly since wasm32 runs in the browser's event loop.
943    ///
944    /// # Panics
945    /// Panics if called from within an existing Tokio runtime. Use the async `execute_for_trace()`
946    /// method instead in async contexts.
947    #[cfg(not(target_arch = "wasm32"))]
948    #[instrument(name = "execute_for_trace_sync", skip_all)]
949    pub fn execute_for_trace_sync(
950        self,
951        program: &Program,
952        host: &mut impl Host,
953    ) -> Result<(ExecutionOutput, TraceGenerationContext), ExecutionError> {
954        match tokio::runtime::Handle::try_current() {
955            Ok(_handle) => {
956                // We're already inside a Tokio runtime - this is not supported
957                // because we cannot safely create a nested runtime or move the
958                // non-Send host reference to another thread
959                panic!(
960                    "Cannot call execute_for_trace_sync from within a Tokio runtime. \
961                     Use the async execute_for_trace() method instead."
962                )
963            },
964            Err(_) => {
965                // No runtime exists - create one and use it
966                let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
967                rt.block_on(self.execute_for_trace(program, host))
968            },
969        }
970    }
971
972    /// Similar to [Self::execute_sync], but allows mutable access to the processor.
973    ///
974    /// This method is only available on non-wasm32 targets for testing. On wasm32, use
975    /// async execution methods directly since wasm32 runs in the browser's event loop.
976    ///
977    /// # Panics
978    /// Panics if called from within an existing Tokio runtime. Use async execution
979    /// methods instead in async contexts.
980    #[cfg(all(any(test, feature = "testing"), not(target_arch = "wasm32")))]
981    pub fn execute_sync_mut(
982        &mut self,
983        program: &Program,
984        host: &mut impl Host,
985    ) -> Result<StackOutputs, ExecutionError> {
986        let mut continuation_stack = ContinuationStack::new(program);
987        let mut current_forest = program.mast_forest().clone();
988
989        // Merge the program's advice map into the advice provider
990        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
991
992        let execute_fut = async {
993            match self
994                .execute_impl(
995                    &mut continuation_stack,
996                    &mut current_forest,
997                    program.kernel(),
998                    host,
999                    &mut NoopTracer,
1000                    &NeverStopper,
1001                )
1002                .await
1003            {
1004                ControlFlow::Continue(stack_outputs) => Ok(stack_outputs),
1005                ControlFlow::Break(break_reason) => match break_reason {
1006                    BreakReason::Err(err) => Err(err),
1007                    BreakReason::Stopped(_) => {
1008                        unreachable!("Execution never stops prematurely with NeverStopper")
1009                    },
1010                },
1011            }
1012        };
1013
1014        match tokio::runtime::Handle::try_current() {
1015            Ok(_handle) => {
1016                // We're already inside a Tokio runtime - this is not supported
1017                // because we cannot safely create a nested runtime or move the
1018                // non-Send host reference to another thread
1019                panic!(
1020                    "Cannot call execute_sync_mut from within a Tokio runtime. \
1021                     Use async execution methods instead."
1022                )
1023            },
1024            Err(_) => {
1025                // No runtime exists - create one and use it
1026                let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
1027                rt.block_on(execute_fut)
1028            },
1029        }
1030    }
1031}
1032
1033// EXECUTION OUTPUT
1034// ===============================================================================================
1035
1036/// The output of a program execution, containing the state of the stack, advice provider,
1037/// memory, and final precompile transcript at the end of execution.
1038#[derive(Debug)]
1039pub struct ExecutionOutput {
1040    pub stack: StackOutputs,
1041    pub advice: AdviceProvider,
1042    pub memory: Memory,
1043    pub final_pc_transcript: PrecompileTranscript,
1044}
1045
1046// EXECUTION CONTEXT INFO
1047// ===============================================================================================
1048
1049/// Information about the execution context.
1050///
1051/// This struct is used to keep track of the information needed to return to the previous context
1052/// upon return from a `call`, `syscall` or `dyncall`.
1053#[derive(Debug)]
1054struct ExecutionContextInfo {
1055    /// This stores all the elements on the stack at the call site, excluding the top 16 elements.
1056    /// This corresponds to the overflow table in [crate::Process].
1057    overflow_stack: Vec<Felt>,
1058    ctx: ContextId,
1059    fn_hash: Word,
1060}
1061
1062// NOOP TRACER
1063// ================================================================================================
1064
1065/// A [Tracer] that does nothing.
1066pub struct NoopTracer;
1067
1068impl Tracer for NoopTracer {
1069    type Processor = FastProcessor;
1070
1071    #[inline(always)]
1072    fn start_clock_cycle(
1073        &mut self,
1074        _processor: &FastProcessor,
1075        _continuation: Continuation,
1076        _continuation_stack: &ContinuationStack,
1077        _current_forest: &Arc<MastForest>,
1078    ) {
1079        // do nothing
1080    }
1081
1082    #[inline(always)]
1083    fn finalize_clock_cycle(
1084        &mut self,
1085        _processor: &FastProcessor,
1086        _op_helper_registers: OperationHelperRegisters,
1087        _current_forest: &Arc<MastForest>,
1088    ) {
1089        // do nothing
1090    }
1091}