Skip to main content

miden_processor/fast/
execution_api.rs

1use alloc::{sync::Arc, vec::Vec};
2use core::ops::ControlFlow;
3
4use miden_core::{
5    Word,
6    mast::{MastForest, MastNodeId},
7    program::{KernelDescriptor, MIN_STACK_DEPTH, Program, StackInputs, StackOutputs},
8};
9use miden_mast_package::debug_info::{
10    DebugSourceGraphLookupError, DebugSourceNodeId, PackageDebugInfo,
11};
12use tracing::instrument;
13
14use super::{
15    FastProcessor, NoopTracer,
16    external::maybe_use_caller_error_context,
17    step::{BreakReason, NeverStopper, ResumeContext, StepStopper},
18};
19#[cfg(feature = "std")]
20use crate::PrecompileWitness;
21use crate::{
22    ExecutionError, ExecutionOutput, ExecutionWitness, Host, LoadedMastForest, Stopper, SyncHost,
23    advice::AdviceError,
24    continuation_stack::{Continuation, ContinuationStack, SourceInlineCallContext},
25    errors::{
26        MapExecErr, MapExecErrNoCtx, PackageSourceDebugContext, malformed_mast_forest_with_context,
27    },
28    execution::{
29        InternalBreakReason, execute_impl, finish_emit_op_execution,
30        finish_load_mast_forest_from_dyn_start, finish_load_mast_forest_from_external,
31    },
32    trace::execution_tracer::ExecutionTracer,
33    tracer::Tracer,
34};
35
36impl FastProcessor {
37    // EXECUTE
38    // -------------------------------------------------------------------------------------------
39
40    /// Executes the given program synchronously and returns the execution output.
41    pub fn execute_sync(
42        self,
43        program: &Program,
44        host: &mut impl SyncHost,
45    ) -> Result<ExecutionOutput, ExecutionError> {
46        self.execute_with_tracer_sync(program, host, &mut NoopTracer)
47    }
48
49    /// Executes the given program synchronously with package-owned source/debug context.
50    ///
51    /// This derives the entrypoint source occurrence from [`PackageDebugInfo`], so the source graph
52    /// must contain at most one root for the executable entrypoint. When the package manifest names
53    /// the exact entrypoint source occurrence, use
54    /// [`Self::execute_with_package_debug_info_at_source_node_sync`] instead.
55    pub fn execute_with_package_debug_info_sync(
56        self,
57        program: &Program,
58        package_debug_info: &PackageDebugInfo,
59        host: &mut impl SyncHost,
60    ) -> Result<ExecutionOutput, ExecutionError> {
61        self.execute_with_package_debug_info_and_tracer_sync(
62            program,
63            package_debug_info,
64            None,
65            host,
66            &mut NoopTracer,
67        )
68    }
69
70    /// Executes the given program synchronously with package-owned source/debug context rooted at
71    /// `entrypoint_source_node_id`.
72    ///
73    /// Use this when the package manifest names the exact source/debug occurrence for the
74    /// executable entrypoint. This preserves source disambiguation when multiple source roots map
75    /// to the same executable MAST node.
76    pub fn execute_with_package_debug_info_at_source_node_sync(
77        self,
78        program: &Program,
79        package_debug_info: &PackageDebugInfo,
80        entrypoint_source_node_id: DebugSourceNodeId,
81        host: &mut impl SyncHost,
82    ) -> Result<ExecutionOutput, ExecutionError> {
83        self.execute_with_package_debug_info_and_tracer_sync(
84            program,
85            package_debug_info,
86            Some(entrypoint_source_node_id),
87            host,
88            &mut NoopTracer,
89        )
90    }
91
92    /// Async variant of [`Self::execute_sync`] for hosts that need async callbacks.
93    #[inline(always)]
94    pub async fn execute(
95        self,
96        program: &Program,
97        host: &mut impl Host,
98    ) -> Result<ExecutionOutput, ExecutionError> {
99        self.execute_with_tracer(program, host, &mut NoopTracer).await
100    }
101
102    /// Async variant of [`Self::execute_with_package_debug_info_sync`].
103    ///
104    /// When the package manifest names the exact entrypoint source occurrence, use
105    /// [`Self::execute_with_package_debug_info_at_source_node`] instead.
106    #[inline(always)]
107    pub async fn execute_with_package_debug_info(
108        self,
109        program: &Program,
110        package_debug_info: &PackageDebugInfo,
111        host: &mut impl Host,
112    ) -> Result<ExecutionOutput, ExecutionError> {
113        self.execute_with_package_debug_info_and_tracer(
114            program,
115            package_debug_info,
116            None,
117            host,
118            &mut NoopTracer,
119        )
120        .await
121    }
122
123    /// Async variant of [`Self::execute_with_package_debug_info_at_source_node_sync`].
124    #[inline(always)]
125    pub async fn execute_with_package_debug_info_at_source_node(
126        self,
127        program: &Program,
128        package_debug_info: &PackageDebugInfo,
129        entrypoint_source_node_id: DebugSourceNodeId,
130        host: &mut impl Host,
131    ) -> Result<ExecutionOutput, ExecutionError> {
132        self.execute_with_package_debug_info_and_tracer(
133            program,
134            package_debug_info,
135            Some(entrypoint_source_node_id),
136            host,
137            &mut NoopTracer,
138        )
139        .await
140    }
141
142    /// Executes the program and builds its execution trace, overlapping the two when a Rayon worker
143    /// is available. The hasher chiplet — the dominant serial part of trace building — consumes a
144    /// live stream of requests while execution is still running, hiding its cost behind the
145    /// (inherently sequential) execution itself. When the caller is Rayon's only worker, this uses
146    /// compact buffered replay and builds the trace after execution.
147    ///
148    /// `max_prover_memory_bytes` bounds the trace the same way
149    /// [`crate::trace::build_trace_with_budget`] does; the streamed hasher builds ahead of that
150    /// call, so it needs its own copy of the derived row cap.
151    ///
152    /// Produces the same trace as [`Self::execute_for_proving_sync`] followed by
153    /// [`ExecutionWitness::into_parts`] and [`crate::trace::build_trace_with_budget`]. The optional
154    /// precompile witness is returned separately because [`crate::trace::VmTrace`] retains only
155    /// its authenticated root.
156    #[cfg(feature = "std")]
157    #[instrument(
158        target = "miden::vm",
159        level = "trace",
160        name = "execute_and_build_trace_sync",
161        skip_all
162    )]
163    pub fn execute_and_build_trace_sync(
164        self,
165        program: &Program,
166        host: &mut impl SyncHost,
167        max_prover_memory_bytes: u64,
168    ) -> Result<(crate::trace::VmTrace, Option<PrecompileWitness>), ExecutionError> {
169        use miden_air::{config, memory};
170
171        use crate::trace::{
172            MAX_TRACE_LEN, build_hasher_chiplet, build_trace_with_budget,
173            build_trace_with_prebuilt_hasher,
174        };
175
176        if Self::rayon_has_no_parallel_worker() {
177            let (vm_witness, precompiles_witness) =
178                self.execute_for_proving_sync(program, host)?.into_parts();
179            let trace = build_trace_with_budget(vm_witness, max_prover_memory_bytes)?;
180            return Ok((trace, precompiles_witness));
181        }
182
183        let stack_inputs = self.initial_stack_inputs();
184        let max_trace_len = MAX_TRACE_LEN.min(memory::max_any_height_for_budget(
185            max_prover_memory_bytes,
186            &config::pcs_params(),
187        ));
188        let (sender, receiver) = std::sync::mpsc::channel();
189        let mut tracer = ExecutionTracer::new_with_streamed_hasher(
190            self.options.core_trace_fragment_size(),
191            self.options.max_stack_depth(),
192            sender,
193        );
194
195        let mut hasher = None;
196        let hasher_slot = &mut hasher;
197        // Keep `tracer` owned by the scope body. If execution unwinds, dropping the body closes the
198        // stream before Rayon waits for the builder, so the builder cannot remain blocked on input.
199        let execution_output = rayon::in_place_scope(move |scope| {
200            // Execution and the host remain on the calling thread. An idle Rayon worker can steal
201            // only the builder task.
202            let span = tracing::Span::current();
203            let hasher_span =
204                tracing::trace_span!(target: "miden::vm::trace", "build_streamed_hasher");
205            scope.spawn(move |_| {
206                let _span = span.entered();
207                let _hasher_span = hasher_span.entered();
208                let result = build_hasher_chiplet(receiver.into_iter().map(Ok), max_trace_len);
209                *hasher_slot = Some(result);
210            });
211
212            let execution_output = {
213                let _span =
214                    tracing::trace_span!(target: "miden::vm::execute", "execute_program").entered();
215                self.execute_with_tracer_sync(program, host, &mut tracer)
216            };
217
218            match execution_output {
219                Ok(output) => {
220                    let (mut vm_witness, precompiles_witness) =
221                        Self::execution_witness_from_parts(program, stack_inputs, output, tracer)
222                            .into_parts();
223                    // End the stream before this scope waits for the builder.
224                    drop(vm_witness.take_hasher_replay());
225                    Ok((vm_witness, precompiles_witness))
226                },
227                Err(err) => {
228                    // Dropping the tracer closes the stream and lets the builder finish. The
229                    // execution error remains the root cause even if the partial replay also
230                    // failed.
231                    drop(tracer);
232                    Err(err)
233                },
234            }
235        });
236
237        let hasher = hasher.expect("hasher builder did not run");
238        let (vm_witness, precompiles_witness) = match execution_output {
239            Ok(output) => output,
240            Err(err) => {
241                if let Err(builder_err) = hasher {
242                    tracing::trace!(
243                        target: "miden::vm::execute",
244                        %builder_err,
245                        "hasher builder also failed"
246                    );
247                }
248                return Err(err);
249            },
250        };
251
252        let trace = build_trace_with_prebuilt_hasher(vm_witness, hasher?, max_prover_memory_bytes)?;
253        Ok((trace, precompiles_witness))
254    }
255
256    #[cfg(feature = "std")]
257    fn rayon_has_no_parallel_worker() -> bool {
258        // `current_num_threads` initializes Rayon's global fallback before the thread-index check.
259        rayon::current_num_threads() == 1 && rayon::current_thread_index().is_some()
260    }
261
262    /// Executes the given program synchronously and returns its complete post-execution witness.
263    ///
264    /// # Example
265    /// ```
266    /// use miden_assembly::Assembler;
267    /// use miden_processor::{DefaultHost, FastProcessor, StackInputs};
268    ///
269    /// let program = Assembler::default()
270    ///     .assemble_program("prg", "begin push.1 drop end")
271    ///     .unwrap()
272    ///     .unwrap_program();
273    /// let mut host = DefaultHost::default();
274    ///
275    /// let execution_witness = FastProcessor::new(StackInputs::default())
276    ///     .execute_for_proving_sync(&program, &mut host)
277    ///     .unwrap();
278    /// let (vm_witness, _) = execution_witness.into_parts();
279    /// let trace = miden_processor::trace::build_trace(vm_witness).unwrap();
280    ///
281    /// assert_eq!(*trace.program_hash(), program.hash());
282    /// ```
283    #[instrument(
284        target = "miden::vm::execute",
285        level = "trace",
286        name = "execute_for_proving_sync",
287        skip_all
288    )]
289    pub fn execute_for_proving_sync(
290        self,
291        program: &Program,
292        host: &mut impl SyncHost,
293    ) -> Result<ExecutionWitness, ExecutionError> {
294        let stack_inputs = self.initial_stack_inputs();
295        let mut tracer = ExecutionTracer::new(
296            self.options.core_trace_fragment_size(),
297            self.options.max_stack_depth(),
298        );
299        let execution_output = self.execute_with_tracer_sync(program, host, &mut tracer)?;
300        Ok(Self::execution_witness_from_parts(
301            program,
302            stack_inputs,
303            execution_output,
304            tracer,
305        ))
306    }
307
308    /// Executes the given program synchronously with package-owned source/debug context and returns
309    /// its complete post-execution witness.
310    #[instrument(
311        target = "miden::vm::execute",
312        level = "trace",
313        name = "execute_for_proving_with_package_debug_info_sync",
314        skip_all
315    )]
316    pub fn execute_for_proving_with_package_debug_info_sync(
317        self,
318        program: &Program,
319        package_debug_info: &PackageDebugInfo,
320        host: &mut impl SyncHost,
321    ) -> Result<ExecutionWitness, ExecutionError> {
322        let stack_inputs = self.initial_stack_inputs();
323        let mut tracer = ExecutionTracer::new(
324            self.options.core_trace_fragment_size(),
325            self.options.max_stack_depth(),
326        );
327        let execution_output = self.execute_with_package_debug_info_and_tracer_sync(
328            program,
329            package_debug_info,
330            None,
331            host,
332            &mut tracer,
333        )?;
334        Ok(Self::execution_witness_from_parts(
335            program,
336            stack_inputs,
337            execution_output,
338            tracer,
339        ))
340    }
341
342    /// Executes the given program synchronously with package-owned source/debug context rooted at
343    /// `entrypoint_source_node_id` and returns its complete post-execution witness.
344    #[instrument(
345        target = "miden::vm::execute",
346        level = "trace",
347        name = "execute_for_proving_with_package_debug_info_at_source_node_sync",
348        skip_all
349    )]
350    pub fn execute_for_proving_with_package_debug_info_at_source_node_sync(
351        self,
352        program: &Program,
353        package_debug_info: &PackageDebugInfo,
354        entrypoint_source_node_id: DebugSourceNodeId,
355        host: &mut impl SyncHost,
356    ) -> Result<ExecutionWitness, ExecutionError> {
357        let stack_inputs = self.initial_stack_inputs();
358        let mut tracer = ExecutionTracer::new(
359            self.options.core_trace_fragment_size(),
360            self.options.max_stack_depth(),
361        );
362        let execution_output = self.execute_with_package_debug_info_and_tracer_sync(
363            program,
364            package_debug_info,
365            Some(entrypoint_source_node_id),
366            host,
367            &mut tracer,
368        )?;
369        Ok(Self::execution_witness_from_parts(
370            program,
371            stack_inputs,
372            execution_output,
373            tracer,
374        ))
375    }
376
377    /// Async variant of [`Self::execute_for_proving_sync`] for async hosts.
378    #[inline(always)]
379    #[instrument(
380        target = "miden::vm::execute",
381        level = "trace",
382        name = "execute_for_proving",
383        skip_all
384    )]
385    pub async fn execute_for_proving(
386        self,
387        program: &Program,
388        host: &mut impl Host,
389    ) -> Result<ExecutionWitness, ExecutionError> {
390        let stack_inputs = self.initial_stack_inputs();
391        let mut tracer = ExecutionTracer::new(
392            self.options.core_trace_fragment_size(),
393            self.options.max_stack_depth(),
394        );
395        let execution_output = self.execute_with_tracer(program, host, &mut tracer).await?;
396        Ok(Self::execution_witness_from_parts(
397            program,
398            stack_inputs,
399            execution_output,
400            tracer,
401        ))
402    }
403
404    /// Async variant of [`Self::execute_for_proving_with_package_debug_info_sync`].
405    #[cfg(any(test, feature = "testing"))]
406    #[inline(always)]
407    #[instrument(
408        target = "miden::vm::execute",
409        level = "trace",
410        name = "execute_for_proving_with_package_debug_info",
411        skip_all
412    )]
413    pub async fn execute_for_proving_with_package_debug_info(
414        self,
415        program: &Program,
416        package_debug_info: &PackageDebugInfo,
417        host: &mut impl Host,
418    ) -> Result<ExecutionWitness, ExecutionError> {
419        let stack_inputs = self.initial_stack_inputs();
420        let mut tracer = ExecutionTracer::new(
421            self.options.core_trace_fragment_size(),
422            self.options.max_stack_depth(),
423        );
424        let execution_output = self
425            .execute_with_package_debug_info_and_tracer(
426                program,
427                package_debug_info,
428                None,
429                host,
430                &mut tracer,
431            )
432            .await?;
433        Ok(Self::execution_witness_from_parts(
434            program,
435            stack_inputs,
436            execution_output,
437            tracer,
438        ))
439    }
440
441    /// Async variant of
442    /// [`Self::execute_for_proving_with_package_debug_info_at_source_node_sync`].
443    #[cfg(any(test, feature = "testing"))]
444    #[inline(always)]
445    #[instrument(
446        target = "miden::vm::execute",
447        level = "trace",
448        name = "execute_for_proving_with_package_debug_info_at_source_node",
449        skip_all
450    )]
451    pub async fn execute_for_proving_with_package_debug_info_at_source_node(
452        self,
453        program: &Program,
454        package_debug_info: &PackageDebugInfo,
455        entrypoint_source_node_id: DebugSourceNodeId,
456        host: &mut impl Host,
457    ) -> Result<ExecutionWitness, ExecutionError> {
458        let stack_inputs = self.initial_stack_inputs();
459        let mut tracer = ExecutionTracer::new(
460            self.options.core_trace_fragment_size(),
461            self.options.max_stack_depth(),
462        );
463        let execution_output = self
464            .execute_with_package_debug_info_and_tracer(
465                program,
466                package_debug_info,
467                Some(entrypoint_source_node_id),
468                host,
469                &mut tracer,
470            )
471            .await?;
472        Ok(Self::execution_witness_from_parts(
473            program,
474            stack_inputs,
475            execution_output,
476            tracer,
477        ))
478    }
479
480    /// Executes the given program with the provided tracer using an async host.
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, Forest = Arc<MastForest>>,
489    {
490        let mut continuation_stack = ContinuationStack::new(program);
491        let mut current_forest = program.mast_forest().clone();
492        let mut package_debug_info = None;
493        let mut inline_call_contexts = Vec::new();
494
495        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
496        let flow = self
497            .execute_impl_async(
498                &mut continuation_stack,
499                &mut current_forest,
500                program.kernel(),
501                host,
502                tracer,
503                &NeverStopper,
504                &mut package_debug_info,
505                &mut inline_call_contexts,
506            )
507            .await;
508        Self::execution_result_from_flow(flow, self)
509    }
510
511    /// Executes the given program with package-owned source/debug context and the provided tracer
512    /// using an async host.
513    async fn execute_with_package_debug_info_and_tracer<T>(
514        mut self,
515        program: &Program,
516        package_debug_info: &PackageDebugInfo,
517        entrypoint_source_node_id: Option<DebugSourceNodeId>,
518        host: &mut impl Host,
519        tracer: &mut T,
520    ) -> Result<ExecutionOutput, ExecutionError>
521    where
522        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
523    {
524        let mut continuation_stack = Self::source_aware_continuation_stack(
525            program,
526            package_debug_info,
527            entrypoint_source_node_id,
528        )?;
529        let mut current_forest = program.mast_forest().clone();
530        let mut package_debug_info = Some(Arc::new(package_debug_info.clone()));
531        let mut inline_call_contexts = Vec::new();
532
533        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
534        let flow = self
535            .execute_impl_async(
536                &mut continuation_stack,
537                &mut current_forest,
538                program.kernel(),
539                host,
540                tracer,
541                &NeverStopper,
542                &mut package_debug_info,
543                &mut inline_call_contexts,
544            )
545            .await;
546        Self::execution_result_from_flow(flow, self)
547    }
548
549    /// Executes the given program with the provided tracer using a sync host.
550    pub fn execute_with_tracer_sync<T>(
551        mut self,
552        program: &Program,
553        host: &mut impl SyncHost,
554        tracer: &mut T,
555    ) -> Result<ExecutionOutput, ExecutionError>
556    where
557        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
558    {
559        let mut continuation_stack = ContinuationStack::new(program);
560        let mut current_forest = program.mast_forest().clone();
561        let mut package_debug_info = None;
562        let mut inline_call_contexts = Vec::new();
563
564        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
565        let flow = self.execute_impl(
566            &mut continuation_stack,
567            &mut current_forest,
568            program.kernel(),
569            host,
570            tracer,
571            &NeverStopper,
572            &mut package_debug_info,
573            &mut inline_call_contexts,
574        );
575        Self::execution_result_from_flow(flow, self)
576    }
577
578    /// Executes the given program with package-owned source/debug context and the provided tracer
579    /// using a sync host.
580    fn execute_with_package_debug_info_and_tracer_sync<T>(
581        mut self,
582        program: &Program,
583        package_debug_info: &PackageDebugInfo,
584        entrypoint_source_node_id: Option<DebugSourceNodeId>,
585        host: &mut impl SyncHost,
586        tracer: &mut T,
587    ) -> Result<ExecutionOutput, ExecutionError>
588    where
589        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
590    {
591        let mut continuation_stack = Self::source_aware_continuation_stack(
592            program,
593            package_debug_info,
594            entrypoint_source_node_id,
595        )?;
596        let mut current_forest = program.mast_forest().clone();
597        let mut package_debug_info = Some(Arc::new(package_debug_info.clone()));
598        let mut inline_call_contexts = Vec::new();
599
600        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
601        let flow = self.execute_impl(
602            &mut continuation_stack,
603            &mut current_forest,
604            program.kernel(),
605            host,
606            tracer,
607            &NeverStopper,
608            &mut package_debug_info,
609            &mut inline_call_contexts,
610        );
611        Self::execution_result_from_flow(flow, self)
612    }
613
614    /// Executes a single clock cycle synchronously.
615    pub fn step_sync(
616        &mut self,
617        host: &mut impl SyncHost,
618        resume_ctx: ResumeContext,
619    ) -> Result<Option<ResumeContext>, ExecutionError> {
620        let ResumeContext {
621            mut current_forest,
622            mut continuation_stack,
623            kernel,
624            mut package_debug_info,
625            mut inline_call_contexts,
626        } = resume_ctx;
627
628        let flow = self.execute_impl(
629            &mut continuation_stack,
630            &mut current_forest,
631            &kernel,
632            host,
633            &mut NoopTracer,
634            &StepStopper,
635            &mut package_debug_info,
636            &mut inline_call_contexts,
637        );
638        Self::resume_context_from_flow(
639            flow,
640            continuation_stack,
641            current_forest,
642            kernel,
643            package_debug_info,
644            inline_call_contexts,
645        )
646    }
647
648    /// Executes a single clock cycle synchronously with package-owned source/debug context.
649    pub fn step_with_package_debug_info_sync(
650        &mut self,
651        host: &mut impl SyncHost,
652        resume_ctx: ResumeContext,
653        package_debug_info: &PackageDebugInfo,
654    ) -> Result<Option<ResumeContext>, ExecutionError> {
655        let ResumeContext {
656            mut current_forest,
657            mut continuation_stack,
658            kernel,
659            package_debug_info: mut active_package_debug_info,
660            mut inline_call_contexts,
661        } = resume_ctx;
662        Self::ensure_source_aware_step_context(
663            &mut continuation_stack,
664            &mut active_package_debug_info,
665            package_debug_info,
666        )?;
667
668        let flow = self.execute_impl(
669            &mut continuation_stack,
670            &mut current_forest,
671            &kernel,
672            host,
673            &mut NoopTracer,
674            &StepStopper,
675            &mut active_package_debug_info,
676            &mut inline_call_contexts,
677        );
678        Self::resume_context_from_flow(
679            flow,
680            continuation_stack,
681            current_forest,
682            kernel,
683            active_package_debug_info,
684            inline_call_contexts,
685        )
686    }
687
688    /// Async variant of [`Self::step_sync`].
689    #[inline(always)]
690    pub async fn step(
691        &mut self,
692        host: &mut impl Host,
693        resume_ctx: ResumeContext,
694    ) -> Result<Option<ResumeContext>, ExecutionError> {
695        let ResumeContext {
696            mut current_forest,
697            mut continuation_stack,
698            kernel,
699            mut package_debug_info,
700            mut inline_call_contexts,
701        } = resume_ctx;
702
703        let flow = self
704            .execute_impl_async(
705                &mut continuation_stack,
706                &mut current_forest,
707                &kernel,
708                host,
709                &mut NoopTracer,
710                &StepStopper,
711                &mut package_debug_info,
712                &mut inline_call_contexts,
713            )
714            .await;
715        Self::resume_context_from_flow(
716            flow,
717            continuation_stack,
718            current_forest,
719            kernel,
720            package_debug_info,
721            inline_call_contexts,
722        )
723    }
724
725    /// Async variant of [`Self::step_with_package_debug_info_sync`].
726    #[inline(always)]
727    pub async fn step_with_package_debug_info(
728        &mut self,
729        host: &mut impl Host,
730        resume_ctx: ResumeContext,
731        package_debug_info: &PackageDebugInfo,
732    ) -> Result<Option<ResumeContext>, ExecutionError> {
733        let ResumeContext {
734            mut current_forest,
735            mut continuation_stack,
736            kernel,
737            package_debug_info: mut active_package_debug_info,
738            mut inline_call_contexts,
739        } = resume_ctx;
740        Self::ensure_source_aware_step_context(
741            &mut continuation_stack,
742            &mut active_package_debug_info,
743            package_debug_info,
744        )?;
745
746        let flow = self
747            .execute_impl_async(
748                &mut continuation_stack,
749                &mut current_forest,
750                &kernel,
751                host,
752                &mut NoopTracer,
753                &StepStopper,
754                &mut active_package_debug_info,
755                &mut inline_call_contexts,
756            )
757            .await;
758        Self::resume_context_from_flow(
759            flow,
760            continuation_stack,
761            current_forest,
762            kernel,
763            active_package_debug_info,
764            inline_call_contexts,
765        )
766    }
767
768    /// Pairs execution output with the initial inputs and replay witness captured during execution.
769    #[inline(always)]
770    fn execution_witness_from_parts(
771        program: &Program,
772        stack_inputs: StackInputs,
773        execution_output: ExecutionOutput,
774        tracer: ExecutionTracer,
775    ) -> ExecutionWitness {
776        ExecutionWitness::from_execution(
777            program.to_info(),
778            stack_inputs,
779            execution_output,
780            tracer.into_trace_replay(),
781        )
782    }
783
784    /// Returns the current top 16 stack elements in public input order.
785    #[inline(always)]
786    fn initial_stack_inputs(&self) -> StackInputs {
787        core::array::from_fn(|idx| self.stack_get(idx)).into()
788    }
789
790    pub(super) fn source_aware_continuation_stack(
791        program: &Program,
792        package_debug_info: &PackageDebugInfo,
793        entrypoint_source_node_id: Option<DebugSourceNodeId>,
794    ) -> Result<ContinuationStack<Arc<MastForest>>, ExecutionError> {
795        if let Some(source_node_id) = entrypoint_source_node_id {
796            let Some(source_node) = package_debug_info.source_node(source_node_id) else {
797                return Err(ExecutionError::Internal(
798                    "package debug source graph is missing the entrypoint source node",
799                ));
800            };
801            if source_node.exec_node != program.entrypoint() {
802                return Err(ExecutionError::Internal(
803                    "package debug entrypoint source node does not match the program entrypoint",
804                ));
805            }
806
807            return Ok(ContinuationStack::new_with_source_node_id(program, source_node_id));
808        }
809
810        let Some(source_node_id) = package_debug_info
811            .unique_source_root_for_exec_node(program.entrypoint())
812            .map_err(|_| {
813                ExecutionError::Internal(
814                    "package debug source graph has ambiguous or malformed entrypoint roots",
815                )
816            })?
817        else {
818            return Ok(ContinuationStack::new_with_optional_source_node_id(program, None));
819        };
820
821        Ok(ContinuationStack::new_with_source_node_id(program, source_node_id))
822    }
823
824    #[cfg(any(test, feature = "testing"))]
825    fn source_aware_resume_context(
826        &mut self,
827        program: &Program,
828        package_debug_info: &PackageDebugInfo,
829        entrypoint_source_node_id: Option<DebugSourceNodeId>,
830    ) -> Result<ResumeContext, ExecutionError> {
831        self.advice
832            .extend_map(program.mast_forest().advice_map())
833            .map_exec_err_no_ctx()?;
834
835        Ok(ResumeContext {
836            current_forest: program.mast_forest().clone(),
837            continuation_stack: Self::source_aware_continuation_stack(
838                program,
839                package_debug_info,
840                entrypoint_source_node_id,
841            )?,
842            kernel: program.kernel().clone(),
843            package_debug_info: Some(Arc::new(package_debug_info.clone())),
844            inline_call_contexts: Vec::new(),
845        })
846    }
847
848    fn ensure_source_aware_step_context(
849        continuation_stack: &mut ContinuationStack<Arc<MastForest>>,
850        package_debug_info: &mut Option<Arc<PackageDebugInfo>>,
851        supplied_package_debug_info: &PackageDebugInfo,
852    ) -> Result<(), ExecutionError> {
853        if package_debug_info.is_none() {
854            *package_debug_info = Some(Arc::new(supplied_package_debug_info.clone()));
855        }
856
857        if !continuation_stack.tracks_source_nodes() {
858            let source_node_id = Self::source_root_for_next_continuation(
859                continuation_stack,
860                package_debug_info.as_deref().expect("package debug info was just initialized"),
861            )?;
862            continuation_stack.start_tracking_source_nodes(source_node_id);
863        }
864
865        Ok(())
866    }
867
868    fn source_root_for_next_continuation(
869        continuation_stack: &ContinuationStack<Arc<MastForest>>,
870        package_debug_info: &PackageDebugInfo,
871    ) -> Result<Option<DebugSourceNodeId>, ExecutionError> {
872        let Some((continuation, _)) = continuation_stack.peek_continuation_with_source_node_id()
873        else {
874            return Ok(None);
875        };
876
877        let Some(exec_node) = continuation.exec_node() else {
878            return Ok(None);
879        };
880
881        package_debug_info.unique_source_root_for_exec_node(exec_node).map_err(|_| {
882            ExecutionError::Internal(
883                "package debug source graph has ambiguous or malformed continuation roots",
884            )
885        })
886    }
887
888    /// Converts a step-wise execution result into the next resume context, if execution stopped.
889    #[inline(always)]
890    fn resume_context_from_flow(
891        flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
892        mut continuation_stack: ContinuationStack<Arc<MastForest>>,
893        mut current_forest: Arc<MastForest>,
894        kernel: KernelDescriptor,
895        mut package_debug_info: Option<Arc<PackageDebugInfo>>,
896        mut inline_call_contexts: Vec<Option<SourceInlineCallContext>>,
897    ) -> Result<Option<ResumeContext>, ExecutionError> {
898        match flow {
899            ControlFlow::Continue(_) => Ok(None),
900            ControlFlow::Break(break_reason) => match break_reason {
901                BreakReason::Err(err) => Err(err),
902                BreakReason::Stopped(maybe_continuation) => {
903                    if let Some((continuation, source_node_id)) = maybe_continuation {
904                        continuation_stack
905                            .push_resumed_with_source_node_id(continuation, source_node_id);
906                    }
907
908                    while matches!(
909                        continuation_stack.peek_continuation(),
910                        Some(Continuation::EnterForest { .. })
911                    ) {
912                        let Some((
913                            Continuation::EnterForest {
914                                forest,
915                                package_debug_info: restored_debug_info,
916                                inline_context_depth,
917                            },
918                            _,
919                        )) = continuation_stack.pop_continuation_with_source_node_id()
920                        else {
921                            unreachable!("peeked continuation must still be EnterForest")
922                        };
923                        current_forest = forest;
924                        package_debug_info = restored_debug_info;
925                        inline_call_contexts.truncate(inline_context_depth);
926                    }
927
928                    Ok(Some(ResumeContext {
929                        current_forest,
930                        continuation_stack,
931                        kernel,
932                        package_debug_info,
933                        inline_call_contexts,
934                    }))
935                },
936            },
937        }
938    }
939
940    /// Materializes the current stack as public outputs without consuming the processor.
941    #[inline(always)]
942    fn current_stack_outputs(&self) -> StackOutputs {
943        StackOutputs::new(
944            &self.stack[self.stack_bot_idx..self.stack_top_idx]
945                .iter()
946                .rev()
947                .copied()
948                .collect::<Vec<_>>(),
949        )
950        .unwrap()
951    }
952
953    /// Executes the given program with the provided tracer and returns the stack outputs.
954    ///
955    /// This function takes a `&mut self` (compared to `self` for the public sync execution
956    /// methods) so that the processor state may be accessed after execution. Reusing the same
957    /// processor for a second program is incorrect. This is mainly meant to be used in tests.
958    fn execute_impl<S, T>(
959        &mut self,
960        continuation_stack: &mut ContinuationStack<Arc<MastForest>>,
961        current_forest: &mut Arc<MastForest>,
962        kernel: &KernelDescriptor,
963        host: &mut impl SyncHost,
964        tracer: &mut T,
965        stopper: &S,
966        package_debug_info: &mut Option<Arc<PackageDebugInfo>>,
967        inline_call_contexts: &mut Vec<Option<SourceInlineCallContext>>,
968    ) -> ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>
969    where
970        S: Stopper<Processor = Self, Forest = Arc<MastForest>>,
971        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
972    {
973        while let ControlFlow::Break(internal_break_reason) = execute_impl(
974            self,
975            continuation_stack,
976            current_forest,
977            kernel,
978            host,
979            tracer,
980            stopper,
981            package_debug_info,
982            inline_call_contexts,
983        ) {
984            let current_package_debug_info = package_debug_info.as_deref();
985            let source_aware_execution =
986                current_package_debug_info.is_some() || continuation_stack.tracks_source_nodes();
987            match internal_break_reason {
988                InternalBreakReason::User(break_reason) => return ControlFlow::Break(break_reason),
989                InternalBreakReason::Emit { op_idx, continuation, source_node_id } => {
990                    self.op_emit_sync(host, op_idx, current_package_debug_info, source_node_id)?;
991
992                    finish_emit_op_execution(
993                        continuation,
994                        source_node_id,
995                        self,
996                        continuation_stack,
997                        current_forest,
998                        tracer,
999                        stopper,
1000                    )?;
1001                },
1002                InternalBreakReason::LoadMastForestFromDyn { callee_hash, source_node_id } => {
1003                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1004                        match self.load_mast_forest_sync(
1005                            callee_hash,
1006                            host,
1007                            current_package_debug_info,
1008                            source_node_id,
1009                            source_aware_execution,
1010                        ) {
1011                            Ok(result) => result,
1012                            Err(err) => return ControlFlow::Break(BreakReason::Err(err)),
1013                        };
1014
1015                    finish_load_mast_forest_from_dyn_start(
1016                        root_id,
1017                        new_forest,
1018                        new_package_debug_info,
1019                        new_source_node_id,
1020                        self,
1021                        current_forest,
1022                        package_debug_info,
1023                        inline_call_contexts.as_slice(),
1024                        continuation_stack,
1025                        tracer,
1026                        stopper,
1027                    )?;
1028                },
1029                InternalBreakReason::LoadMastForestFromExternal {
1030                    external_node_id,
1031                    procedure_hash,
1032                    source_node_id,
1033                } => {
1034                    let inline_call_context = package_debug_info.clone().and_then(|debug_info| {
1035                        SourceInlineCallContext::for_source_boundary(debug_info, source_node_id)
1036                    });
1037                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1038                        match self.load_mast_forest_sync(
1039                            procedure_hash,
1040                            host,
1041                            current_package_debug_info,
1042                            source_node_id,
1043                            source_aware_execution,
1044                        ) {
1045                            Ok(result) => result,
1046                            Err(err) => {
1047                                let maybe_enriched_err = maybe_use_caller_error_context(
1048                                    err,
1049                                    continuation_stack,
1050                                    current_package_debug_info,
1051                                    host,
1052                                );
1053                                return ControlFlow::Break(BreakReason::Err(maybe_enriched_err));
1054                            },
1055                        };
1056
1057                    finish_load_mast_forest_from_external(
1058                        root_id,
1059                        new_forest,
1060                        new_package_debug_info,
1061                        new_source_node_id,
1062                        inline_call_context,
1063                        (external_node_id, source_node_id),
1064                        current_forest,
1065                        package_debug_info,
1066                        inline_call_contexts,
1067                        continuation_stack,
1068                        tracer,
1069                    )?;
1070                },
1071            }
1072        }
1073
1074        match StackOutputs::new(
1075            &self.stack[self.stack_bot_idx..self.stack_top_idx]
1076                .iter()
1077                .rev()
1078                .copied()
1079                .collect::<Vec<_>>(),
1080        ) {
1081            Ok(stack_outputs) => ControlFlow::Continue(stack_outputs),
1082            Err(_) => ControlFlow::Break(BreakReason::Err(ExecutionError::OutputStackOverflow(
1083                self.stack_top_idx - self.stack_bot_idx - MIN_STACK_DEPTH,
1084            ))),
1085        }
1086    }
1087
1088    async fn execute_impl_async<S, T>(
1089        &mut self,
1090        continuation_stack: &mut ContinuationStack<Arc<MastForest>>,
1091        current_forest: &mut Arc<MastForest>,
1092        kernel: &KernelDescriptor,
1093        host: &mut impl Host,
1094        tracer: &mut T,
1095        stopper: &S,
1096        package_debug_info: &mut Option<Arc<PackageDebugInfo>>,
1097        inline_call_contexts: &mut Vec<Option<SourceInlineCallContext>>,
1098    ) -> ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>
1099    where
1100        S: Stopper<Processor = Self, Forest = Arc<MastForest>>,
1101        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
1102    {
1103        while let ControlFlow::Break(internal_break_reason) = execute_impl(
1104            self,
1105            continuation_stack,
1106            current_forest,
1107            kernel,
1108            host,
1109            tracer,
1110            stopper,
1111            package_debug_info,
1112            inline_call_contexts,
1113        ) {
1114            let current_package_debug_info = package_debug_info.as_deref();
1115            let source_aware_execution =
1116                current_package_debug_info.is_some() || continuation_stack.tracks_source_nodes();
1117            match internal_break_reason {
1118                InternalBreakReason::User(break_reason) => return ControlFlow::Break(break_reason),
1119                InternalBreakReason::Emit { op_idx, continuation, source_node_id } => {
1120                    self.op_emit(host, op_idx, current_package_debug_info, source_node_id).await?;
1121
1122                    finish_emit_op_execution(
1123                        continuation,
1124                        source_node_id,
1125                        self,
1126                        continuation_stack,
1127                        current_forest,
1128                        tracer,
1129                        stopper,
1130                    )?;
1131                },
1132                InternalBreakReason::LoadMastForestFromDyn { callee_hash, source_node_id } => {
1133                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1134                        match self
1135                            .load_mast_forest(
1136                                callee_hash,
1137                                host,
1138                                current_package_debug_info,
1139                                source_node_id,
1140                                source_aware_execution,
1141                            )
1142                            .await
1143                        {
1144                            Ok(result) => result,
1145                            Err(err) => return ControlFlow::Break(BreakReason::Err(err)),
1146                        };
1147
1148                    finish_load_mast_forest_from_dyn_start(
1149                        root_id,
1150                        new_forest,
1151                        new_package_debug_info,
1152                        new_source_node_id,
1153                        self,
1154                        current_forest,
1155                        package_debug_info,
1156                        inline_call_contexts.as_slice(),
1157                        continuation_stack,
1158                        tracer,
1159                        stopper,
1160                    )?;
1161                },
1162                InternalBreakReason::LoadMastForestFromExternal {
1163                    external_node_id,
1164                    procedure_hash,
1165                    source_node_id,
1166                } => {
1167                    let inline_call_context = package_debug_info.clone().and_then(|debug_info| {
1168                        SourceInlineCallContext::for_source_boundary(debug_info, source_node_id)
1169                    });
1170                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1171                        match self
1172                            .load_mast_forest(
1173                                procedure_hash,
1174                                host,
1175                                current_package_debug_info,
1176                                source_node_id,
1177                                source_aware_execution,
1178                            )
1179                            .await
1180                        {
1181                            Ok(result) => result,
1182                            Err(err) => {
1183                                let maybe_enriched_err = maybe_use_caller_error_context(
1184                                    err,
1185                                    continuation_stack,
1186                                    current_package_debug_info,
1187                                    host,
1188                                );
1189                                return ControlFlow::Break(BreakReason::Err(maybe_enriched_err));
1190                            },
1191                        };
1192
1193                    finish_load_mast_forest_from_external(
1194                        root_id,
1195                        new_forest,
1196                        new_package_debug_info,
1197                        new_source_node_id,
1198                        inline_call_context,
1199                        (external_node_id, source_node_id),
1200                        current_forest,
1201                        package_debug_info,
1202                        inline_call_contexts,
1203                        continuation_stack,
1204                        tracer,
1205                    )?;
1206                },
1207            }
1208        }
1209
1210        match StackOutputs::new(
1211            &self.stack[self.stack_bot_idx..self.stack_top_idx]
1212                .iter()
1213                .rev()
1214                .copied()
1215                .collect::<Vec<_>>(),
1216        ) {
1217            Ok(stack_outputs) => ControlFlow::Continue(stack_outputs),
1218            Err(_) => ControlFlow::Break(BreakReason::Err(ExecutionError::OutputStackOverflow(
1219                self.stack_top_idx - self.stack_bot_idx - MIN_STACK_DEPTH,
1220            ))),
1221        }
1222    }
1223
1224    // HELPERS
1225    // ------------------------------------------------------------------------------------------
1226
1227    fn load_mast_forest_sync(
1228        &mut self,
1229        node_digest: Word,
1230        host: &mut impl SyncHost,
1231        package_debug_info: Option<&PackageDebugInfo>,
1232        source_node_id: Option<DebugSourceNodeId>,
1233        source_aware_execution: bool,
1234    ) -> Result<
1235        (
1236            MastNodeId,
1237            Arc<MastForest>,
1238            Option<Arc<PackageDebugInfo>>,
1239            Option<DebugSourceNodeId>,
1240        ),
1241        ExecutionError,
1242    > {
1243        let cached = self.loaded_mast_forests.get(&node_digest).cloned();
1244        let was_cached = cached.is_some();
1245        let loaded_mast_forest = match cached {
1246            Some(mast_forest) => mast_forest,
1247            None => host.get_mast_forest(&node_digest).ok_or_else(|| {
1248                match (package_debug_info, source_node_id) {
1249                    (Some(debug_info), Some(source_node_id)) => {
1250                        crate::errors::procedure_not_found_with_package_source_context(
1251                            node_digest,
1252                            PackageSourceDebugContext::new(debug_info, source_node_id),
1253                            host,
1254                        )
1255                    },
1256                    _ => crate::errors::procedure_not_found_with_context(node_digest),
1257                }
1258            })?,
1259        };
1260        let mast_forest = loaded_mast_forest.mast_forest().clone();
1261
1262        let root_id = mast_forest.find_procedure_root(node_digest).ok_or_else(|| {
1263            let context = match (package_debug_info, source_node_id) {
1264                (Some(debug_info), Some(source_node_id)) => {
1265                    Some(PackageSourceDebugContext::new(debug_info, source_node_id))
1266                },
1267                _ => None,
1268            };
1269            malformed_mast_forest_with_context(node_digest, context, host)
1270        })?;
1271
1272        if !was_cached {
1273            self.cache_loaded_mast_forest(&loaded_mast_forest);
1274        }
1275        self.merge_mast_forest_advice(&mast_forest).map_exec_err()?;
1276        let (loaded_package_debug_info, loaded_source_node_id) =
1277            Self::loaded_package_source_context(
1278                &loaded_mast_forest,
1279                root_id,
1280                source_aware_execution,
1281            )?;
1282
1283        Ok((root_id, mast_forest, loaded_package_debug_info, loaded_source_node_id))
1284    }
1285
1286    async fn load_mast_forest(
1287        &mut self,
1288        node_digest: Word,
1289        host: &mut impl Host,
1290        package_debug_info: Option<&PackageDebugInfo>,
1291        source_node_id: Option<DebugSourceNodeId>,
1292        source_aware_execution: bool,
1293    ) -> Result<
1294        (
1295            MastNodeId,
1296            Arc<MastForest>,
1297            Option<Arc<PackageDebugInfo>>,
1298            Option<DebugSourceNodeId>,
1299        ),
1300        ExecutionError,
1301    > {
1302        let cached = self.loaded_mast_forests.get(&node_digest).cloned();
1303        let was_cached = cached.is_some();
1304        let loaded_mast_forest = match cached {
1305            Some(mast_forest) => mast_forest,
1306            None => {
1307                if let Some(mast_forest) = host.get_mast_forest(&node_digest).await {
1308                    mast_forest
1309                } else {
1310                    return Err(match (package_debug_info, source_node_id) {
1311                        (Some(debug_info), Some(source_node_id)) => {
1312                            crate::errors::procedure_not_found_with_package_source_context(
1313                                node_digest,
1314                                PackageSourceDebugContext::new(debug_info, source_node_id),
1315                                host,
1316                            )
1317                        },
1318                        _ => crate::errors::procedure_not_found_with_context(node_digest),
1319                    });
1320                }
1321            },
1322        };
1323        let mast_forest = loaded_mast_forest.mast_forest().clone();
1324
1325        let root_id = mast_forest.find_procedure_root(node_digest).ok_or_else(|| {
1326            let context = match (package_debug_info, source_node_id) {
1327                (Some(debug_info), Some(source_node_id)) => {
1328                    Some(PackageSourceDebugContext::new(debug_info, source_node_id))
1329                },
1330                _ => None,
1331            };
1332            malformed_mast_forest_with_context(node_digest, context, host)
1333        })?;
1334
1335        if !was_cached {
1336            self.cache_loaded_mast_forest(&loaded_mast_forest);
1337        }
1338        self.merge_mast_forest_advice(&mast_forest).map_exec_err()?;
1339        let (loaded_package_debug_info, loaded_source_node_id) =
1340            Self::loaded_package_source_context(
1341                &loaded_mast_forest,
1342                root_id,
1343                source_aware_execution,
1344            )?;
1345
1346        Ok((root_id, mast_forest, loaded_package_debug_info, loaded_source_node_id))
1347    }
1348
1349    fn cache_loaded_mast_forest(&mut self, loaded_mast_forest: &LoadedMastForest) {
1350        for procedure_digest in loaded_mast_forest.mast_forest().local_procedure_digests() {
1351            self.loaded_mast_forests
1352                .entry(procedure_digest)
1353                .or_insert_with(|| loaded_mast_forest.clone());
1354        }
1355    }
1356
1357    fn merge_mast_forest_advice(&mut self, mast_forest: &MastForest) -> Result<(), AdviceError> {
1358        let commitment = mast_forest.commitment();
1359        if self.merged_mast_forests.contains(&commitment) {
1360            return Ok(());
1361        }
1362
1363        self.advice.extend_map(mast_forest.advice_map())?;
1364        self.merged_mast_forests.insert(commitment);
1365        Ok(())
1366    }
1367
1368    fn loaded_package_source_context(
1369        loaded_mast_forest: &LoadedMastForest,
1370        root_id: MastNodeId,
1371        source_aware_execution: bool,
1372    ) -> Result<(Option<Arc<PackageDebugInfo>>, Option<DebugSourceNodeId>), ExecutionError> {
1373        if !source_aware_execution {
1374            return Ok((None, None));
1375        }
1376
1377        let Some(package_debug_info) = loaded_mast_forest
1378            .package_debug_info()
1379            .map_err(|_| ExecutionError::Internal("loaded package debug info is malformed"))?
1380        else {
1381            return Ok((None, None));
1382        };
1383
1384        let source_node_id = match package_debug_info.unique_source_root_for_exec_node(root_id) {
1385            Ok(source_node_id) => source_node_id,
1386            Err(DebugSourceGraphLookupError::AmbiguousRoot { .. }) => None,
1387            Err(_) => {
1388                return Err(ExecutionError::Internal(
1389                    "loaded package debug source graph has malformed entrypoint roots",
1390                ));
1391            },
1392        };
1393
1394        Ok((Some(package_debug_info), source_node_id))
1395    }
1396
1397    /// Executes the given program synchronously one step at a time.
1398    pub fn execute_by_step_sync(
1399        mut self,
1400        program: &Program,
1401        host: &mut impl SyncHost,
1402    ) -> Result<StackOutputs, ExecutionError> {
1403        let mut current_resume_ctx = self.get_initial_resume_context(program)?;
1404
1405        loop {
1406            match self.step_sync(host, current_resume_ctx)? {
1407                Some(next_resume_ctx) => {
1408                    current_resume_ctx = next_resume_ctx;
1409                },
1410                None => break Ok(self.current_stack_outputs()),
1411            }
1412        }
1413    }
1414
1415    /// Executes the given program synchronously one step at a time with package-owned source/debug
1416    /// context.
1417    #[cfg(any(test, feature = "testing"))]
1418    pub fn execute_by_step_with_package_debug_info_sync(
1419        mut self,
1420        program: &Program,
1421        package_debug_info: &PackageDebugInfo,
1422        host: &mut impl SyncHost,
1423    ) -> Result<StackOutputs, ExecutionError> {
1424        let mut current_resume_ctx =
1425            self.source_aware_resume_context(program, package_debug_info, None)?;
1426
1427        loop {
1428            match self.step_with_package_debug_info_sync(
1429                host,
1430                current_resume_ctx,
1431                package_debug_info,
1432            )? {
1433                Some(next_resume_ctx) => {
1434                    current_resume_ctx = next_resume_ctx;
1435                },
1436                None => break Ok(self.current_stack_outputs()),
1437            }
1438        }
1439    }
1440
1441    /// Executes the given program synchronously one step at a time with package-owned source/debug
1442    /// context rooted at `entrypoint_source_node_id`.
1443    #[cfg(any(test, feature = "testing"))]
1444    pub fn execute_by_step_with_package_debug_info_at_source_node_sync(
1445        mut self,
1446        program: &Program,
1447        package_debug_info: &PackageDebugInfo,
1448        entrypoint_source_node_id: DebugSourceNodeId,
1449        host: &mut impl SyncHost,
1450    ) -> Result<StackOutputs, ExecutionError> {
1451        let mut current_resume_ctx = self.source_aware_resume_context(
1452            program,
1453            package_debug_info,
1454            Some(entrypoint_source_node_id),
1455        )?;
1456
1457        loop {
1458            match self.step_with_package_debug_info_sync(
1459                host,
1460                current_resume_ctx,
1461                package_debug_info,
1462            )? {
1463                Some(next_resume_ctx) => {
1464                    current_resume_ctx = next_resume_ctx;
1465                },
1466                None => break Ok(self.current_stack_outputs()),
1467            }
1468        }
1469    }
1470
1471    /// Async variant of [`Self::execute_by_step_sync`].
1472    #[inline(always)]
1473    pub async fn execute_by_step(
1474        mut self,
1475        program: &Program,
1476        host: &mut impl Host,
1477    ) -> Result<StackOutputs, ExecutionError> {
1478        let mut current_resume_ctx = self.get_initial_resume_context(program)?;
1479        let mut processor = self;
1480
1481        loop {
1482            match processor.step(host, current_resume_ctx).await? {
1483                Some(next_resume_ctx) => {
1484                    current_resume_ctx = next_resume_ctx;
1485                },
1486                None => break Ok(processor.current_stack_outputs()),
1487            }
1488        }
1489    }
1490
1491    /// Async variant of [`Self::execute_by_step_with_package_debug_info_sync`].
1492    #[cfg(any(test, feature = "testing"))]
1493    #[inline(always)]
1494    pub async fn execute_by_step_with_package_debug_info(
1495        mut self,
1496        program: &Program,
1497        package_debug_info: &PackageDebugInfo,
1498        host: &mut impl Host,
1499    ) -> Result<StackOutputs, ExecutionError> {
1500        let mut current_resume_ctx =
1501            self.source_aware_resume_context(program, package_debug_info, None)?;
1502        let mut processor = self;
1503
1504        loop {
1505            match processor
1506                .step_with_package_debug_info(host, current_resume_ctx, package_debug_info)
1507                .await?
1508            {
1509                Some(next_resume_ctx) => {
1510                    current_resume_ctx = next_resume_ctx;
1511                },
1512                None => break Ok(processor.current_stack_outputs()),
1513            }
1514        }
1515    }
1516
1517    /// Async variant of
1518    /// [`Self::execute_by_step_with_package_debug_info_at_source_node_sync`].
1519    #[cfg(any(test, feature = "testing"))]
1520    #[inline(always)]
1521    pub async fn execute_by_step_with_package_debug_info_at_source_node(
1522        mut self,
1523        program: &Program,
1524        package_debug_info: &PackageDebugInfo,
1525        entrypoint_source_node_id: DebugSourceNodeId,
1526        host: &mut impl Host,
1527    ) -> Result<StackOutputs, ExecutionError> {
1528        let mut current_resume_ctx = self.source_aware_resume_context(
1529            program,
1530            package_debug_info,
1531            Some(entrypoint_source_node_id),
1532        )?;
1533        let mut processor = self;
1534
1535        loop {
1536            match processor
1537                .step_with_package_debug_info(host, current_resume_ctx, package_debug_info)
1538                .await?
1539            {
1540                Some(next_resume_ctx) => {
1541                    current_resume_ctx = next_resume_ctx;
1542                },
1543                None => break Ok(processor.current_stack_outputs()),
1544            }
1545        }
1546    }
1547
1548    /// Similar to [`Self::execute_sync`], but allows mutable access to the processor.
1549    ///
1550    /// This is mainly meant to be used in tests.
1551    #[cfg(any(test, feature = "testing"))]
1552    pub fn execute_mut_sync(
1553        &mut self,
1554        program: &Program,
1555        host: &mut impl SyncHost,
1556    ) -> Result<StackOutputs, ExecutionError> {
1557        let mut continuation_stack = ContinuationStack::new(program);
1558        let mut current_forest = program.mast_forest().clone();
1559        let mut package_debug_info = None;
1560        let mut inline_call_contexts = Vec::new();
1561
1562        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
1563
1564        let flow = self.execute_impl(
1565            &mut continuation_stack,
1566            &mut current_forest,
1567            program.kernel(),
1568            host,
1569            &mut NoopTracer,
1570            &NeverStopper,
1571            &mut package_debug_info,
1572            &mut inline_call_contexts,
1573        );
1574        Self::stack_result_from_flow(flow)
1575    }
1576
1577    /// Async variant of [`Self::execute_mut_sync`].
1578    #[cfg(any(test, feature = "testing"))]
1579    #[inline(always)]
1580    pub async fn execute_mut(
1581        &mut self,
1582        program: &Program,
1583        host: &mut impl Host,
1584    ) -> Result<StackOutputs, ExecutionError> {
1585        let mut continuation_stack = ContinuationStack::new(program);
1586        let mut current_forest = program.mast_forest().clone();
1587        let mut package_debug_info = None;
1588        let mut inline_call_contexts = Vec::new();
1589
1590        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
1591
1592        let flow = self
1593            .execute_impl_async(
1594                &mut continuation_stack,
1595                &mut current_forest,
1596                program.kernel(),
1597                host,
1598                &mut NoopTracer,
1599                &NeverStopper,
1600                &mut package_debug_info,
1601                &mut inline_call_contexts,
1602            )
1603            .await;
1604        Self::stack_result_from_flow(flow)
1605    }
1606}
1607
1608#[cfg(all(test, feature = "std"))]
1609mod tests {
1610    use super::FastProcessor;
1611
1612    #[test]
1613    fn sole_rayon_worker_requires_buffered_trace_building() {
1614        rayon::ThreadPoolBuilder::new()
1615            .num_threads(1)
1616            .build()
1617            .unwrap()
1618            .install(|| assert!(FastProcessor::rayon_has_no_parallel_worker()));
1619    }
1620}