Skip to main content

miden_processor/fast/
step.rs

1//! This module defines items relevant to controlling execution stopping conditions.
2
3use alloc::{sync::Arc, vec::Vec};
4use core::ops::ControlFlow;
5
6use miden_core::{mast::MastForest, program::KernelDescriptor};
7use miden_mast_package::debug_info::{DebugSourceNodeId, PackageDebugInfo};
8
9use crate::{
10    ExecutionError, FastProcessor, SourceInlineCallContext, Stopper,
11    continuation_stack::{Continuation, ContinuationStack},
12};
13
14// RESUME CONTEXT
15// ===============================================================================================
16
17/// The context required to resume execution of a program from the last point at which it was
18/// stopped.
19#[derive(Debug)]
20pub struct ResumeContext {
21    pub(crate) current_forest: Arc<MastForest>,
22    pub(crate) continuation_stack: ContinuationStack<Arc<MastForest>>,
23    pub(crate) kernel: KernelDescriptor,
24    pub(crate) package_debug_info: Option<Arc<PackageDebugInfo>>,
25    pub(crate) inline_call_contexts: Vec<Option<SourceInlineCallContext>>,
26}
27
28impl ResumeContext {
29    /// Returns a reference to the continuation stack.
30    pub fn continuation_stack(&self) -> &ContinuationStack<Arc<MastForest>> {
31        &self.continuation_stack
32    }
33
34    /// Returns a reference to the MAST forest being currently executed.
35    pub fn current_forest(&self) -> &Arc<MastForest> {
36        &self.current_forest
37    }
38
39    /// Returns a reference to the debug info associated with the current forest, if available
40    pub fn debug_info(&self) -> Option<Arc<PackageDebugInfo>> {
41        self.package_debug_info.clone()
42    }
43
44    /// Returns the source/debug occurrence associated with the next continuation, if available.
45    pub fn next_source_node_id(&self) -> Option<DebugSourceNodeId> {
46        self.continuation_stack
47            .peek_continuation_with_source_node_id()
48            .and_then(|(_, source_node_id)| source_node_id)
49    }
50
51    /// Returns dynamic-boundary inline contexts active for the next operation, ordered from the
52    /// innermost boundary to the outermost.
53    pub fn inherited_inline_call_contexts(&self) -> impl Iterator<Item = &SourceInlineCallContext> {
54        let effective_depth = self.continuation_stack.iter_continuations_for_next_clock().fold(
55            self.inline_call_contexts.len(),
56            |depth, continuation| match continuation {
57                Continuation::EnterForest { inline_context_depth, .. } => *inline_context_depth,
58                _ => depth,
59            },
60        );
61        self.inline_call_contexts[..effective_depth.min(self.inline_call_contexts.len())]
62            .iter()
63            .rev()
64            .filter_map(Option::as_ref)
65    }
66
67    /// Returns a reference to the kernel being currently executed.
68    pub fn kernel(&self) -> &KernelDescriptor {
69        &self.kernel
70    }
71}
72
73// STOPPERS
74// ===============================================================================================
75
76/// A [`Stopper`] that never stops execution (except for returning an error when the maximum cycle
77/// count is exceeded).
78pub struct NeverStopper;
79
80impl Stopper for NeverStopper {
81    type Processor = FastProcessor;
82    type Forest = Arc<MastForest>;
83
84    #[inline(always)]
85    fn should_stop(
86        &self,
87        processor: &FastProcessor,
88        continuation_stack: &ContinuationStack<Arc<MastForest>>,
89        _continuation_after_stop: impl FnOnce() -> Option<(
90            Continuation<Arc<MastForest>>,
91            Option<DebugSourceNodeId>,
92        )>,
93    ) -> ControlFlow<BreakReason<Arc<MastForest>>> {
94        check_if_max_cycles_exceeded(processor)?;
95        check_if_continuation_stack_too_large(processor, continuation_stack)
96    }
97}
98
99/// A [`Stopper`] that always stops execution after each single step. An error is returned if the
100/// maximum cycle count is exceeded.
101pub struct StepStopper;
102
103impl Stopper for StepStopper {
104    type Processor = FastProcessor;
105    type Forest = Arc<MastForest>;
106
107    #[inline(always)]
108    fn should_stop(
109        &self,
110        processor: &FastProcessor,
111        continuation_stack: &ContinuationStack<Arc<MastForest>>,
112        continuation_after_stop: impl FnOnce() -> Option<(
113            Continuation<Arc<MastForest>>,
114            Option<DebugSourceNodeId>,
115        )>,
116    ) -> ControlFlow<BreakReason<Arc<MastForest>>> {
117        check_if_max_cycles_exceeded(processor)?;
118        check_if_continuation_stack_too_large(processor, continuation_stack)?;
119
120        ControlFlow::Break(BreakReason::Stopped(continuation_after_stop()))
121    }
122}
123
124/// Checks if the maximum cycle count has been exceeded, returning a `BreakReason::Err` if so.
125#[inline(always)]
126fn check_if_max_cycles_exceeded<F>(processor: &FastProcessor) -> ControlFlow<BreakReason<F>> {
127    if processor.clk > processor.options.max_cycles() as usize {
128        ControlFlow::Break(BreakReason::Err(ExecutionError::CycleLimitExceeded(
129            processor.options.max_cycles(),
130        )))
131    } else {
132        ControlFlow::Continue(())
133    }
134}
135
136/// Checks if the continuation stack size exceeds the maximum allowed, returning a
137/// `BreakReason::Err` if so.
138#[inline(always)]
139fn check_if_continuation_stack_too_large<F>(
140    processor: &FastProcessor,
141    continuation_stack: &ContinuationStack<F>,
142) -> ControlFlow<BreakReason<F>> {
143    if continuation_stack.len() > processor.options.max_num_continuations() {
144        ControlFlow::Break(BreakReason::Err(ExecutionError::Internal(
145            "continuation stack size exceeded the allowed maximum",
146        )))
147    } else {
148        ControlFlow::Continue(())
149    }
150}
151
152// BREAK REASON
153// ===============================================================================================
154
155/// The reason why execution was interrupted.
156#[derive(Debug)]
157pub enum BreakReason<F> {
158    /// An execution error occurred
159    Err(ExecutionError),
160    /// Execution was stopped by a [`Stopper`]. Provides the continuation to add to the continuation
161    /// stack before returning, if any. The mental model to have in mind when choosing the
162    /// continuation to add on a call to `FastProcessor::increment_clk()` is:
163    ///
164    /// "If execution is stopped here, does the current continuation stack properly encode the next
165    /// step of execution?"
166    ///
167    /// If yes, then `None` should be returned. If not, then the continuation that runs the next
168    /// step in `FastProcessor::execute_impl()` should be returned.
169    Stopped(Option<(Continuation<F>, Option<DebugSourceNodeId>)>),
170}