Skip to main content

miden_processor/
errors.rs

1// Allow unused assignments - required by miette::Diagnostic derive macro
2#![allow(unused_assignments)]
3
4use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
5
6use miden_air_definitions::vm::trace::chiplets::hasher::MAX_MERKLE_DEPTH;
7use miden_core::{deferred::PrecompileError, program::MIN_STACK_DEPTH};
8use miden_debug_types::{Location, SourceFile, SourceSpan};
9use miden_mast_package::{
10    PackageDebugInfoError,
11    debug_info::{DebugSourceNodeId, PackageDebugInfo},
12};
13use miden_utils_diagnostics::{Diagnostic, miette};
14
15use crate::{
16    BaseHost, ContextId, Felt, Word,
17    advice::AdviceError,
18    event::{EventError, EventId, EventName},
19    fast::SystemEventError,
20    utils::to_hex,
21};
22
23// EXECUTION ERROR
24// ================================================================================================
25
26#[non_exhaustive]
27#[derive(Debug, thiserror::Error, Diagnostic)]
28pub enum ExecutionError {
29    #[error("failed to execute arithmetic circuit evaluation operation: {error}")]
30    #[diagnostic()]
31    AceChipError {
32        #[label("this call failed")]
33        label: SourceSpan,
34        #[source_code]
35        source_file: Option<Arc<SourceFile>>,
36        error: AceError,
37    },
38    #[error("{err}")]
39    #[diagnostic(forward(err))]
40    AdviceError {
41        #[label]
42        label: SourceSpan,
43        #[source_code]
44        source_file: Option<Arc<SourceFile>>,
45        err: AdviceError,
46    },
47    #[error("exceeded the allowed number of max cycles {0}")]
48    CycleLimitExceeded(u32),
49    #[error("error during processing of event {}", match event_name {
50        Some(name) => format!("'{name}' (ID: {event_id})"),
51        None => format!("with ID: {event_id}"),
52    })]
53    #[diagnostic()]
54    EventError {
55        #[label]
56        label: SourceSpan,
57        #[source_code]
58        source_file: Option<Arc<SourceFile>>,
59        event_id: EventId,
60        event_name: Option<EventName>,
61        #[source]
62        error: EventError,
63    },
64    /// Deferred system event failed while validating or evaluating a committed node.
65    #[error("{err}")]
66    #[diagnostic()]
67    DeferredError {
68        #[label]
69        label: SourceSpan,
70        #[source_code]
71        source_file: Option<Arc<SourceFile>>,
72        err: PrecompileError,
73    },
74    #[error("failed to execute the program for internal reason: {0}")]
75    Internal(&'static str),
76    #[error("operand stack depth {depth} exceeds the maximum of {max}")]
77    StackDepthLimitExceeded { depth: usize, max: usize },
78    /// This means trace generation would go over the configured row limit.
79    ///
80    /// In parallel trace building, this is used for core-row prechecks and chiplet overflow.
81    #[error("trace length exceeded the maximum of {0} rows")]
82    TraceLenExceeded(usize),
83    /// This means the modelled peak prover memory for the trace exceeds the configured budget.
84    #[error(
85        "estimated prover memory of {estimated_bytes} bytes exceeds the budget of {budget_bytes} bytes"
86    )]
87    ProverMemoryExceeded { estimated_bytes: u64, budget_bytes: u64 },
88    /// Memory error with source context for diagnostics.
89    ///
90    /// Use `MemoryResultExt::map_mem_err` to convert `Result<T, MemoryError>` with context.
91    #[error("{err}")]
92    #[diagnostic(forward(err))]
93    MemoryError {
94        #[label]
95        label: SourceSpan,
96        #[source_code]
97        source_file: Option<Arc<SourceFile>>,
98        err: MemoryError,
99    },
100    /// Memory error without source context (for internal operations like FMP initialization).
101    ///
102    /// Use `ExecutionError::MemoryErrorNoCtx` for memory errors that don't have error context
103    /// available (e.g., during call/syscall context initialization).
104    #[error(transparent)]
105    #[diagnostic(transparent)]
106    MemoryErrorNoCtx(MemoryError),
107    #[error("{err}")]
108    #[diagnostic(forward(err))]
109    OperationError {
110        #[label]
111        label: SourceSpan,
112        #[source_code]
113        source_file: Option<Arc<SourceFile>>,
114        err: OperationError,
115    },
116    #[error("stack should have at most {MIN_STACK_DEPTH} elements at the end of program execution, but had {} elements", MIN_STACK_DEPTH + .0)]
117    OutputStackOverflow(usize),
118    #[error("procedure with root digest {root_digest} could not be found")]
119    #[diagnostic()]
120    ProcedureNotFound {
121        #[label]
122        label: SourceSpan,
123        #[source_code]
124        source_file: Option<Arc<SourceFile>>,
125        root_digest: Word,
126    },
127    #[error("failed to generate STARK proof: {0}")]
128    ProvingError(String),
129    #[error(transparent)]
130    HostError(#[from] HostError),
131    #[error(transparent)]
132    PackageDebugInfoError(#[from] PackageDebugInfoError),
133}
134
135impl ExecutionError {
136    /// Wraps an advice error without source-location context.
137    pub fn advice_error_no_context(err: AdviceError) -> Self {
138        Self::AdviceError {
139            label: SourceSpan::UNKNOWN,
140            source_file: None,
141            err,
142        }
143    }
144}
145
146impl AsRef<dyn Diagnostic> for ExecutionError {
147    fn as_ref(&self) -> &(dyn Diagnostic + 'static) {
148        self
149    }
150}
151
152// ACE ERROR
153// ================================================================================================
154
155#[derive(Debug, thiserror::Error)]
156#[error("ace circuit evaluation failed: {0}")]
157pub struct AceError(pub String);
158
159// ACE EVAL ERROR
160// ================================================================================================
161
162/// Context-free error type for ACE circuit evaluation operations.
163///
164/// This enum wraps errors from ACE evaluation and memory subsystems without
165/// carrying source location context. Context is added at the call site via
166/// `AceEvalResultExt::map_ace_eval_err`.
167#[derive(Debug, thiserror::Error)]
168pub enum AceEvalError {
169    #[error(transparent)]
170    Ace(#[from] AceError),
171    #[error(transparent)]
172    Memory(#[from] MemoryError),
173}
174
175// HOST ERROR
176// ================================================================================================
177
178/// Error type for host-related operations.
179#[derive(Debug, thiserror::Error)]
180pub enum HostError {
181    #[error("attempted to add event handler for '{event}' (already registered)")]
182    DuplicateEventHandler { event: EventName },
183    #[error(
184        "attempted to add event handler for '{event}' (reserved '{namespace}' namespace)",
185        namespace = EventName::RESERVED_NAMESPACE
186    )]
187    ReservedEventNamespace { event: EventName },
188    #[error("attempted to add event handler with an empty event name")]
189    EmptyEventName,
190}
191
192// IO ERROR
193// ================================================================================================
194
195/// Context-free error type for IO operations.
196///
197/// This enum wraps errors from the advice provider and memory subsystems without
198/// carrying source location context. Context is added at the call site via
199/// `IoResultExt::map_io_err`.
200#[derive(Debug, thiserror::Error, Diagnostic)]
201pub enum IoError {
202    #[error(transparent)]
203    Advice(#[from] AdviceError),
204    #[error(transparent)]
205    Memory(#[from] MemoryError),
206    #[error(transparent)]
207    #[diagnostic(transparent)]
208    Operation(#[from] OperationError),
209    /// Stack operation error (increment/decrement size failures).
210    ///
211    /// These are internal execution errors that don't need additional context
212    /// since they already carry their own error information.
213    #[error(transparent)]
214    #[diagnostic(transparent)]
215    Execution(Box<ExecutionError>),
216}
217
218impl From<ExecutionError> for IoError {
219    fn from(err: ExecutionError) -> Self {
220        IoError::Execution(Box::new(err))
221    }
222}
223
224// MEMORY ERROR
225// ================================================================================================
226
227/// Lightweight error type for memory operations.
228///
229/// This enum captures error conditions without expensive context information (no source location,
230/// no file references). When a `MemoryError` propagates up to become an `ExecutionError`, the
231/// context is resolved lazily via `MapExecErr::map_exec_err`.
232#[derive(Debug, thiserror::Error, Diagnostic)]
233pub enum MemoryError {
234    #[error("memory address cannot exceed 2^32 but was {addr}")]
235    AddressOutOfBounds { addr: u64 },
236    #[error(
237        "memory address {addr} in context {ctx} was read and written, or written twice, in the same clock cycle {clk}"
238    )]
239    IllegalMemoryAccess { ctx: ContextId, addr: u32, clk: Felt },
240    #[error(
241        "memory range start address cannot exceed end address, but was ({start_addr}, {end_addr})"
242    )]
243    InvalidMemoryRange { start_addr: u64, end_addr: u64 },
244    #[error(
245        "word access at memory address {addr} in context {ctx} is unaligned: word accesses require addresses that are multiples of 4"
246    )]
247    UnalignedWordAccess { addr: u32, ctx: ContextId },
248    #[error("failed to read from memory: {0}")]
249    MemoryReadFailed(String),
250    #[error(
251        "writing to memory address {addr} in context {ctx} would exceed the maximum number of memory elements {max}"
252    )]
253    #[diagnostic(help(
254        "increase the limit via `ExecutionOptions::with_max_memory_elements`, or reduce the number of distinct memory addresses the program writes to"
255    ))]
256    MemoryElementLimitExceeded { ctx: ContextId, addr: u32, max: usize },
257}
258
259// CRYPTO ERROR
260// ================================================================================================
261
262/// Context-free error type for cryptographic operations (Merkle path verification, updates).
263///
264/// This enum wraps errors from the advice provider and operation subsystems without carrying
265/// source location context. Context is added at the call site via
266/// `CryptoResultExt::map_crypto_err`.
267#[derive(Debug, thiserror::Error, Diagnostic)]
268pub enum CryptoError {
269    #[error(transparent)]
270    Advice(#[from] AdviceError),
271    #[error(transparent)]
272    #[diagnostic(transparent)]
273    Operation(#[from] OperationError),
274}
275
276// OPERATION ERROR
277// ================================================================================================
278
279/// Lightweight error type for operations that can fail.
280///
281/// This enum captures error conditions without expensive context information (no source location,
282/// no file references). When an `OperationError` propagates up to become an `ExecutionError`, the
283/// context is resolved lazily via extension traits like `OperationResultExt::map_exec_err`.
284///
285/// # Adding new errors (for contributors)
286///
287/// **Use `OperationError` when:**
288/// - The error occurs during operation execution (e.g., assertion failures, type mismatches)
289/// - Context can be resolved at the call site via the extension traits
290/// - The error needs both a human-readable message and optional diagnostic help
291///
292/// **Avoid duplicating error context.** Context is added by the extension traits,
293/// so do NOT add `label` or `source_file` fields to the variant.
294///
295/// **Pattern at call sites:**
296/// ```ignore
297/// // Return OperationError and let the caller wrap it:
298/// fn some_op() -> Result<(), OperationError> {
299///     Err(OperationError::DivideByZero)
300/// }
301///
302/// // Caller wraps with context lazily:
303/// some_op().map_exec_err()?;
304/// ```
305///
306/// For wrapper errors (`AdviceError`, `EventError`, `AceError`), use the corresponding extension
307/// traits (`AdviceResultExt`, `AceResultExt`) or helper functions (`advice_error_with_context`,
308/// `event_error_with_context`).
309#[derive(Debug, Clone, thiserror::Error, Diagnostic)]
310pub enum OperationError {
311    #[error("external node with mast root {0} resolved to an external node")]
312    CircularExternalNode(Word),
313    #[error("clear_deferred requires root context, but was executed in context {ctx}")]
314    ClearDeferredOutsideRootContext { ctx: ContextId },
315    #[error("division by zero: divisor must be non-zero for division or modulo operations")]
316    DivideByZero,
317    #[error(transparent)]
318    Deferred(#[from] PrecompileError),
319    #[error(
320        "assertion failed with error {}",
321        match err_msg {
322            Some(msg) => format!("message: {msg}"),
323            None => format!("code: {err_code}"),
324        }
325    )]
326    FailedAssertion {
327        err_code: Felt,
328        err_msg: Option<Arc<str>>,
329    },
330    #[error(
331        "u32 assertion failed: u32assert2 requires both stack values to be valid 32-bit unsigned integers; error {}; invalid values: {invalid_values:?}",
332        match err_msg {
333            Some(msg) => format!("message: {msg}"),
334            None => format!("code: {err_code}"),
335        }
336    )]
337    U32AssertionFailed {
338        err_code: Felt,
339        err_msg: Option<Arc<str>>,
340        invalid_values: Vec<Felt>,
341    },
342    #[error("FRI operation failed: {0}")]
343    FriError(String),
344    #[error(
345        "Horner evaluation point at memory address {addr} in context {ctx} must be encoded as [alpha0, alpha1, 0, 0]"
346    )]
347    InvalidHornerEvaluationPointWord { ctx: ContextId, addr: u64 },
348    #[error(
349        "invalid crypto operation: Merkle path length {path_len} does not match expected depth {depth}"
350    )]
351    InvalidMerklePathLength { path_len: usize, depth: Felt },
352    #[error("when returning from a call, stack depth must be {MIN_STACK_DEPTH}, but was {depth}")]
353    InvalidStackDepthOnReturn { depth: usize },
354    #[error("ilog2 requires a non-zero argument")]
355    LogArgumentZero,
356    #[error(
357        "MAST forest in host indexed by procedure root {root_digest} doesn't contain that root"
358    )]
359    MalformedMastForestInHost { root_digest: Word },
360    #[error("Merkle tree depth must be in the range 1..={MAX_MERKLE_DEPTH}, but was {depth}")]
361    MerkleDepthOutOfRange { depth: Felt },
362    #[error("merkle path verification failed for value {value} at index {index} in the Merkle tree with root {root} (error {err})",
363      value = to_hex(inner.value.as_bytes()),
364      root = to_hex(inner.root.as_bytes()),
365      index = inner.index,
366      err = match &inner.err_msg {
367        Some(msg) => format!("message: {msg}"),
368        None => format!("code: {}", inner.err_code),
369      }
370    )]
371    MerklePathVerificationFailed {
372        inner: Box<MerklePathVerificationFailedInner>,
373    },
374    #[error("{message}, but got {value}", message = context.message())]
375    NotBinaryValue {
376        context: BinaryValueErrorContext,
377        value: Felt,
378    },
379    #[error("operation expected u32 values, but got values: {values:?}")]
380    NotU32Values { values: Vec<Felt> },
381    #[error("syscall failed: procedure with root {proc_root} was not found in the kernel")]
382    SyscallTargetNotInKernel { proc_root: Word },
383    #[error("failed to execute the operation for internal reason: {0}")]
384    Internal(&'static str),
385}
386
387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
388pub enum BinaryValueErrorContext {
389    Operation,
390    If,
391    Loop,
392}
393
394impl BinaryValueErrorContext {
395    const fn message(self) -> &'static str {
396        match self {
397            Self::Operation => "operation expected a binary value",
398            Self::If => "if statement expected a binary value on top of the stack",
399            Self::Loop => {
400                "loop condition must be a binary value on entry and each subsequent iteration"
401            },
402        }
403    }
404}
405
406impl OperationError {
407    /// Wraps this error with execution context to produce an `ExecutionError`.
408    ///
409    /// This is useful when working with `ControlFlow` or other non-`Result` return types
410    /// where the `OperationResultExt::map_exec_err` extension trait cannot be used directly.
411    pub fn with_context(self) -> ExecutionError {
412        let (label, source_file) = get_label_and_source_file();
413        ExecutionError::OperationError { label, source_file, err: self }
414    }
415
416    /// Wraps this error with package-owned source-occurrence execution context.
417    ///
418    /// Unlike [`Self::with_context`], this resolves source metadata from package debug sections
419    /// keyed by a source/debug MAST occurrence rather than by the reduced execution MAST node.
420    pub fn with_package_source_context(
421        self,
422        context: PackageSourceDebugContext<'_>,
423        host: &(dyn BaseHost + '_),
424        op_idx: Option<usize>,
425    ) -> ExecutionError {
426        let (label, source_file) =
427            label_and_source_file_from_location(context.assembly_location(op_idx).as_ref(), host);
428        ExecutionError::OperationError {
429            label,
430            source_file,
431            err: self.with_package_debug_info(context.debug_info()),
432        }
433    }
434
435    fn with_package_debug_info(self, debug_info: &PackageDebugInfo) -> Self {
436        match self {
437            Self::FailedAssertion { err_code, err_msg: None } => Self::FailedAssertion {
438                err_msg: debug_info.error_message(err_code.as_canonical_u64()),
439                err_code,
440            },
441            Self::U32AssertionFailed { err_code, err_msg: None, invalid_values } => {
442                Self::U32AssertionFailed {
443                    err_msg: debug_info.error_message(err_code.as_canonical_u64()),
444                    err_code,
445                    invalid_values,
446                }
447            },
448            Self::MerklePathVerificationFailed { mut inner } if inner.err_msg.is_none() => {
449                inner.err_msg = debug_info.error_message(inner.err_code.as_canonical_u64());
450                Self::MerklePathVerificationFailed { inner }
451            },
452            err => err,
453        }
454    }
455}
456
457/// Inner data for `OperationError::MerklePathVerificationFailed`.
458///
459/// Boxed to reduce the size of `OperationError`.
460#[derive(Debug, Clone)]
461pub struct MerklePathVerificationFailedInner {
462    pub value: Word,
463    pub index: Felt,
464    pub root: Word,
465    pub err_code: Felt,
466    pub err_msg: Option<Arc<str>>,
467}
468
469// EXTENSION TRAITS
470// ================================================================================================
471
472/// Source-occurrence debug context decoded from package debug sections.
473///
474/// This keeps diagnostic lookup keyed by [`DebugSourceNodeId`] so two source occurrences that
475/// reduce to the same executable MAST node can still report distinct source locations.
476#[derive(Clone, Copy, Debug)]
477pub struct PackageSourceDebugContext<'a> {
478    debug_info: &'a PackageDebugInfo,
479    source_node_id: Option<DebugSourceNodeId>,
480}
481
482impl<'a> PackageSourceDebugContext<'a> {
483    /// Creates a source debug context for one package-owned source/debug MAST occurrence.
484    pub fn new(debug_info: &'a PackageDebugInfo, source_node_id: DebugSourceNodeId) -> Self {
485        Self {
486            debug_info,
487            source_node_id: Some(source_node_id),
488        }
489    }
490
491    /// Creates a package debug context when source location metadata may be unavailable.
492    pub(crate) fn new_optional(
493        debug_info: &'a PackageDebugInfo,
494        source_node_id: Option<DebugSourceNodeId>,
495    ) -> Self {
496        Self { debug_info, source_node_id }
497    }
498
499    /// Returns the source/debug MAST occurrence associated with this context, if known.
500    pub fn source_node_id(&self) -> Option<DebugSourceNodeId> {
501        self.source_node_id
502    }
503
504    /// Returns the package debug info backing this context.
505    pub fn debug_info(&self) -> &'a PackageDebugInfo {
506        self.debug_info
507    }
508
509    /// Returns source location metadata for `op_idx`, if present.
510    ///
511    /// If `op_idx` is absent, this falls back to the first operation row for the source occurrence.
512    pub fn assembly_location(&self, op_idx: Option<usize>) -> Option<Location> {
513        let source_node_id = self.source_node_id?;
514        let assembly_op = match op_idx {
515            Some(op_idx) => u32::try_from(op_idx)
516                .ok()
517                .and_then(|op_idx| self.debug_info.asm_op_for_operation(source_node_id, op_idx)),
518            None => self.debug_info.first_asm_op_for_source_node(source_node_id),
519        }?;
520
521        assembly_op
522            .location_idx
523            .into_option()
524            .and_then(|idx| self.debug_info.get_location(idx))
525    }
526}
527
528fn label_and_source_file_from_location(
529    location: Option<&Location>,
530    host: &(dyn BaseHost + '_),
531) -> (SourceSpan, Option<Arc<SourceFile>>) {
532    location.map_or_else(
533        || (SourceSpan::UNKNOWN, None),
534        |location| host.get_label_and_source_file(location),
535    )
536}
537
538/// Computes the label and source file for error context.
539///
540/// This function is called by the extension traits to compute source location
541/// only when an error occurs. Since errors are rare, the cost of source metadata lookup is
542/// acceptable.
543fn get_label_and_source_file() -> (SourceSpan, Option<Arc<SourceFile>>) {
544    (SourceSpan::UNKNOWN, None)
545}
546
547/// Wraps an `AdviceError` with execution context to produce an `ExecutionError`.
548///
549/// This is useful when working with `ControlFlow` or other non-`Result` return types
550/// where the extension traits cannot be used directly.
551pub fn advice_error_with_context(err: AdviceError) -> ExecutionError {
552    let (label, source_file) = get_label_and_source_file();
553    ExecutionError::AdviceError { label, source_file, err }
554}
555
556/// Wraps an `AdviceError` with package-owned source-occurrence execution context.
557pub fn advice_error_with_package_source_context(
558    err: AdviceError,
559    context: PackageSourceDebugContext<'_>,
560    host: &(dyn BaseHost + '_),
561    op_idx: Option<usize>,
562) -> ExecutionError {
563    let (label, source_file) =
564        label_and_source_file_from_location(context.assembly_location(op_idx).as_ref(), host);
565    ExecutionError::AdviceError { label, source_file, err }
566}
567
568/// Wraps an `EventError` with execution context to produce an `ExecutionError`.
569///
570/// This is useful when working with `ControlFlow` or other non-`Result` return types
571/// where an extension trait on `Result` cannot be used directly.
572pub fn event_error_with_context(
573    error: EventError,
574    event_id: EventId,
575    event_name: Option<EventName>,
576) -> ExecutionError {
577    let (label, source_file) = get_label_and_source_file();
578    ExecutionError::EventError {
579        label,
580        source_file,
581        event_id,
582        event_name,
583        error,
584    }
585}
586
587/// Wraps an `EventError` with package-owned source-occurrence execution context.
588pub fn event_error_with_package_source_context(
589    error: EventError,
590    context: PackageSourceDebugContext<'_>,
591    host: &(dyn BaseHost + '_),
592    op_idx: Option<usize>,
593    event_id: EventId,
594    event_name: Option<EventName>,
595) -> ExecutionError {
596    let (label, source_file) =
597        label_and_source_file_from_location(context.assembly_location(op_idx).as_ref(), host);
598    ExecutionError::EventError {
599        label,
600        source_file,
601        event_id,
602        event_name,
603        error,
604    }
605}
606
607/// Creates a `ProcedureNotFound` error with execution context.
608pub fn procedure_not_found_with_context(root_digest: Word) -> ExecutionError {
609    let (label, source_file) = get_label_and_source_file();
610    ExecutionError::ProcedureNotFound { label, source_file, root_digest }
611}
612
613/// Creates a `ProcedureNotFound` error with package-owned source-occurrence execution context.
614pub fn procedure_not_found_with_package_source_context(
615    root_digest: Word,
616    context: PackageSourceDebugContext<'_>,
617    host: &(dyn BaseHost + '_),
618) -> ExecutionError {
619    let (label, source_file) =
620        label_and_source_file_from_location(context.assembly_location(None).as_ref(), host);
621    ExecutionError::ProcedureNotFound { label, source_file, root_digest }
622}
623
624/// Creates a `MalformedMastForestInHost` operation error with execution context.
625pub fn malformed_mast_forest_with_context(
626    root_digest: Word,
627    context: Option<PackageSourceDebugContext<'_>>,
628    host: &(dyn BaseHost + '_),
629) -> ExecutionError {
630    let err = OperationError::MalformedMastForestInHost { root_digest };
631    match context {
632        Some(context) => err.with_package_source_context(context, host, None),
633        None => err.with_context(),
634    }
635}
636
637// CONSOLIDATED EXTENSION TRAITS (plafer's approach)
638// ================================================================================================
639//
640// Three traits organized by method signature rather than by error type:
641// 1. MapExecErr - for errors with basic context
642// 2. MapExecErrWithOpIdx - for errors in basic blocks that may need op_idx
643// 3. MapExecErrNoCtx - for errors without any context
644
645/// Extension trait for mapping errors to `ExecutionError`.
646///
647/// Legacy MAST-local debug metadata no longer provides source locations here; callers that have
648/// package-owned source context should use `map_exec_err_with_package_source_op_idx`.
649pub trait MapExecErr<T> {
650    fn map_exec_err(self) -> Result<T, ExecutionError>;
651}
652
653/// Extension trait for mapping errors to `ExecutionError` with op index context.
654///
655/// Implement this for error types that occur within basic blocks where the
656/// operation index is available for more precise source location.
657pub trait MapExecErrWithOpIdx<T> {
658    fn map_exec_err_with_op_idx(self) -> Result<T, ExecutionError>;
659
660    fn map_exec_err_with_package_source_op_idx(
661        self,
662        context: Option<PackageSourceDebugContext<'_>>,
663        _host: &(dyn BaseHost + '_),
664        _op_idx: usize,
665    ) -> Result<T, ExecutionError>
666    where
667        Self: Sized,
668    {
669        if context.is_some() {
670            return Err(ExecutionError::Internal(
671                "package source context is unsupported for this error type",
672            ));
673        }
674
675        self.map_exec_err_with_op_idx()
676    }
677}
678
679/// Extension trait for mapping errors to `ExecutionError` without context.
680///
681/// Implement this for error types that may need to be converted when no
682/// error context is available (e.g., during initialization).
683pub trait MapExecErrNoCtx<T> {
684    fn map_exec_err_no_ctx(self) -> Result<T, ExecutionError>;
685}
686
687// OperationError implementations
688impl<T> MapExecErr<T> for Result<T, OperationError> {
689    #[inline(always)]
690    fn map_exec_err(self) -> Result<T, ExecutionError> {
691        match self {
692            Ok(v) => Ok(v),
693            Err(err) => {
694                let (label, source_file) = get_label_and_source_file();
695                Err(ExecutionError::OperationError { label, source_file, err })
696            },
697        }
698    }
699}
700
701impl<T> MapExecErrWithOpIdx<T> for Result<T, OperationError> {
702    #[inline(always)]
703    fn map_exec_err_with_op_idx(self) -> Result<T, ExecutionError> {
704        match self {
705            Ok(v) => Ok(v),
706            Err(err) => {
707                let (label, source_file) = get_label_and_source_file();
708                Err(ExecutionError::OperationError { label, source_file, err })
709            },
710        }
711    }
712
713    #[inline(always)]
714    fn map_exec_err_with_package_source_op_idx(
715        self,
716        context: Option<PackageSourceDebugContext<'_>>,
717        host: &(dyn BaseHost + '_),
718        op_idx: usize,
719    ) -> Result<T, ExecutionError> {
720        match (self, context) {
721            (Ok(v), _) => Ok(v),
722            (Err(err), Some(context)) => {
723                Err(err.with_package_source_context(context, host, Some(op_idx)))
724            },
725            (Err(err), None) => {
726                let (label, source_file) = get_label_and_source_file();
727                Err(ExecutionError::OperationError { label, source_file, err })
728            },
729        }
730    }
731}
732
733impl<T> MapExecErrNoCtx<T> for Result<T, OperationError> {
734    #[inline(always)]
735    fn map_exec_err_no_ctx(self) -> Result<T, ExecutionError> {
736        match self {
737            Ok(v) => Ok(v),
738            Err(err) => Err(ExecutionError::OperationError {
739                label: SourceSpan::UNKNOWN,
740                source_file: None,
741                err,
742            }),
743        }
744    }
745}
746
747// AdviceError implementations
748impl<T> MapExecErr<T> for Result<T, AdviceError> {
749    #[inline(always)]
750    fn map_exec_err(self) -> Result<T, ExecutionError> {
751        match self {
752            Ok(v) => Ok(v),
753            Err(err) => Err(advice_error_with_context(err)),
754        }
755    }
756}
757
758impl<T> MapExecErrNoCtx<T> for Result<T, AdviceError> {
759    #[inline(always)]
760    fn map_exec_err_no_ctx(self) -> Result<T, ExecutionError> {
761        match self {
762            Ok(v) => Ok(v),
763            Err(err) => Err(ExecutionError::AdviceError {
764                label: SourceSpan::UNKNOWN,
765                source_file: None,
766                err,
767            }),
768        }
769    }
770}
771
772// MemoryError implementations
773impl<T> MapExecErr<T> for Result<T, MemoryError> {
774    #[inline(always)]
775    fn map_exec_err(self) -> Result<T, ExecutionError> {
776        match self {
777            Ok(v) => Ok(v),
778            Err(err) => {
779                let (label, source_file) = get_label_and_source_file();
780                Err(ExecutionError::MemoryError { label, source_file, err })
781            },
782        }
783    }
784}
785
786impl<T> MapExecErrWithOpIdx<T> for Result<T, MemoryError> {
787    #[inline(always)]
788    fn map_exec_err_with_op_idx(self) -> Result<T, ExecutionError> {
789        match self {
790            Ok(v) => Ok(v),
791            Err(err) => {
792                let (label, source_file) = get_label_and_source_file();
793                Err(ExecutionError::MemoryError { label, source_file, err })
794            },
795        }
796    }
797
798    #[inline(always)]
799    fn map_exec_err_with_package_source_op_idx(
800        self,
801        context: Option<PackageSourceDebugContext<'_>>,
802        host: &(dyn BaseHost + '_),
803        op_idx: usize,
804    ) -> Result<T, ExecutionError> {
805        match (self, context) {
806            (Ok(v), _) => Ok(v),
807            (Err(err), Some(context)) => {
808                let (label, source_file) = label_and_source_file_from_location(
809                    context.assembly_location(Some(op_idx)).as_ref(),
810                    host,
811                );
812                Err(ExecutionError::MemoryError { label, source_file, err })
813            },
814            (Err(err), None) => {
815                let (label, source_file) = get_label_and_source_file();
816                Err(ExecutionError::MemoryError { label, source_file, err })
817            },
818        }
819    }
820}
821
822// SystemEventError implementations
823impl<T> MapExecErr<T> for Result<T, SystemEventError> {
824    #[inline(always)]
825    fn map_exec_err(self) -> Result<T, ExecutionError> {
826        match self {
827            Ok(v) => Ok(v),
828            Err(err) => {
829                let (label, source_file) = get_label_and_source_file();
830                Err(match err {
831                    SystemEventError::Advice(err) => {
832                        ExecutionError::AdviceError { label, source_file, err }
833                    },
834                    SystemEventError::Operation(err) => {
835                        ExecutionError::OperationError { label, source_file, err }
836                    },
837                    SystemEventError::Memory(err) => {
838                        ExecutionError::MemoryError { label, source_file, err }
839                    },
840                    SystemEventError::Deferred(err) => {
841                        ExecutionError::DeferredError { label, source_file, err }
842                    },
843                })
844            },
845        }
846    }
847}
848
849impl<T> MapExecErrWithOpIdx<T> for Result<T, SystemEventError> {
850    #[inline(always)]
851    fn map_exec_err_with_op_idx(self) -> Result<T, ExecutionError> {
852        match self {
853            Ok(v) => Ok(v),
854            Err(err) => {
855                let (label, source_file) = get_label_and_source_file();
856                Err(match err {
857                    SystemEventError::Advice(err) => {
858                        ExecutionError::AdviceError { label, source_file, err }
859                    },
860                    SystemEventError::Operation(err) => {
861                        ExecutionError::OperationError { label, source_file, err }
862                    },
863                    SystemEventError::Memory(err) => {
864                        ExecutionError::MemoryError { label, source_file, err }
865                    },
866                    SystemEventError::Deferred(err) => {
867                        ExecutionError::DeferredError { label, source_file, err }
868                    },
869                })
870            },
871        }
872    }
873
874    #[inline(always)]
875    fn map_exec_err_with_package_source_op_idx(
876        self,
877        context: Option<PackageSourceDebugContext<'_>>,
878        host: &(dyn BaseHost + '_),
879        op_idx: usize,
880    ) -> Result<T, ExecutionError> {
881        match (self, context) {
882            (Ok(v), _) => Ok(v),
883            (Err(err), Some(context)) => {
884                let (label, source_file) = label_and_source_file_from_location(
885                    context.assembly_location(Some(op_idx)).as_ref(),
886                    host,
887                );
888                Err(match err {
889                    SystemEventError::Advice(err) => {
890                        ExecutionError::AdviceError { label, source_file, err }
891                    },
892                    SystemEventError::Operation(err) => {
893                        ExecutionError::OperationError { label, source_file, err }
894                    },
895                    SystemEventError::Memory(err) => {
896                        ExecutionError::MemoryError { label, source_file, err }
897                    },
898                    SystemEventError::Deferred(err) => {
899                        ExecutionError::DeferredError { label, source_file, err }
900                    },
901                })
902            },
903            (Err(err), None) => {
904                let (label, source_file) = get_label_and_source_file();
905                Err(match err {
906                    SystemEventError::Advice(err) => {
907                        ExecutionError::AdviceError { label, source_file, err }
908                    },
909                    SystemEventError::Operation(err) => {
910                        ExecutionError::OperationError { label, source_file, err }
911                    },
912                    SystemEventError::Memory(err) => {
913                        ExecutionError::MemoryError { label, source_file, err }
914                    },
915                    SystemEventError::Deferred(err) => {
916                        ExecutionError::DeferredError { label, source_file, err }
917                    },
918                })
919            },
920        }
921    }
922}
923
924// IoError implementations
925impl<T> MapExecErrWithOpIdx<T> for Result<T, IoError> {
926    #[inline(always)]
927    fn map_exec_err_with_op_idx(self) -> Result<T, ExecutionError> {
928        match self {
929            Ok(v) => Ok(v),
930            Err(err) => {
931                let (label, source_file) = get_label_and_source_file();
932                Err(match err {
933                    IoError::Advice(err) => ExecutionError::AdviceError { label, source_file, err },
934                    IoError::Memory(err) => ExecutionError::MemoryError { label, source_file, err },
935                    IoError::Operation(err) => {
936                        ExecutionError::OperationError { label, source_file, err }
937                    },
938                    // Execution errors are already fully formed with their own message.
939                    IoError::Execution(boxed_err) => *boxed_err,
940                })
941            },
942        }
943    }
944
945    #[inline(always)]
946    fn map_exec_err_with_package_source_op_idx(
947        self,
948        context: Option<PackageSourceDebugContext<'_>>,
949        host: &(dyn BaseHost + '_),
950        op_idx: usize,
951    ) -> Result<T, ExecutionError> {
952        match (self, context) {
953            (Ok(v), _) => Ok(v),
954            (Err(IoError::Execution(boxed_err)), _) => Err(*boxed_err),
955            (Err(err), Some(context)) => {
956                let (label, source_file) = label_and_source_file_from_location(
957                    context.assembly_location(Some(op_idx)).as_ref(),
958                    host,
959                );
960                Err(match err {
961                    IoError::Advice(err) => ExecutionError::AdviceError { label, source_file, err },
962                    IoError::Memory(err) => ExecutionError::MemoryError { label, source_file, err },
963                    IoError::Operation(err) => {
964                        ExecutionError::OperationError { label, source_file, err }
965                    },
966                    IoError::Execution(_) => unreachable!("handled above"),
967                })
968            },
969            (Err(err), None) => {
970                let (label, source_file) = get_label_and_source_file();
971                Err(match err {
972                    IoError::Advice(err) => ExecutionError::AdviceError { label, source_file, err },
973                    IoError::Memory(err) => ExecutionError::MemoryError { label, source_file, err },
974                    IoError::Operation(err) => {
975                        ExecutionError::OperationError { label, source_file, err }
976                    },
977                    IoError::Execution(_) => unreachable!("handled above"),
978                })
979            },
980        }
981    }
982}
983
984// CryptoError implementations
985impl<T> MapExecErrWithOpIdx<T> for Result<T, CryptoError> {
986    #[inline(always)]
987    fn map_exec_err_with_op_idx(self) -> Result<T, ExecutionError> {
988        match self {
989            Ok(v) => Ok(v),
990            Err(err) => {
991                let (label, source_file) = get_label_and_source_file();
992                Err(match err {
993                    CryptoError::Advice(err) => {
994                        ExecutionError::AdviceError { label, source_file, err }
995                    },
996                    CryptoError::Operation(err) => {
997                        ExecutionError::OperationError { label, source_file, err }
998                    },
999                })
1000            },
1001        }
1002    }
1003
1004    #[inline(always)]
1005    fn map_exec_err_with_package_source_op_idx(
1006        self,
1007        context: Option<PackageSourceDebugContext<'_>>,
1008        host: &(dyn BaseHost + '_),
1009        op_idx: usize,
1010    ) -> Result<T, ExecutionError> {
1011        match (self, context) {
1012            (Ok(v), _) => Ok(v),
1013            (Err(err), Some(context)) => {
1014                let (label, source_file) = label_and_source_file_from_location(
1015                    context.assembly_location(Some(op_idx)).as_ref(),
1016                    host,
1017                );
1018                Err(match err {
1019                    CryptoError::Advice(err) => {
1020                        ExecutionError::AdviceError { label, source_file, err }
1021                    },
1022                    CryptoError::Operation(err) => ExecutionError::OperationError {
1023                        label,
1024                        source_file,
1025                        err: err.with_package_debug_info(context.debug_info()),
1026                    },
1027                })
1028            },
1029            (Err(err), None) => {
1030                let (label, source_file) = get_label_and_source_file();
1031                Err(match err {
1032                    CryptoError::Advice(err) => {
1033                        ExecutionError::AdviceError { label, source_file, err }
1034                    },
1035                    CryptoError::Operation(err) => {
1036                        ExecutionError::OperationError { label, source_file, err }
1037                    },
1038                })
1039            },
1040        }
1041    }
1042}
1043
1044// AceEvalError implementations
1045impl<T> MapExecErrWithOpIdx<T> for Result<T, AceEvalError> {
1046    #[inline(always)]
1047    fn map_exec_err_with_op_idx(self) -> Result<T, ExecutionError> {
1048        match self {
1049            Ok(v) => Ok(v),
1050            Err(err) => {
1051                let (label, source_file) = get_label_and_source_file();
1052                Err(match err {
1053                    AceEvalError::Ace(error) => {
1054                        ExecutionError::AceChipError { label, source_file, error }
1055                    },
1056                    AceEvalError::Memory(err) => {
1057                        ExecutionError::MemoryError { label, source_file, err }
1058                    },
1059                })
1060            },
1061        }
1062    }
1063
1064    #[inline(always)]
1065    fn map_exec_err_with_package_source_op_idx(
1066        self,
1067        context: Option<PackageSourceDebugContext<'_>>,
1068        host: &(dyn BaseHost + '_),
1069        op_idx: usize,
1070    ) -> Result<T, ExecutionError> {
1071        match (self, context) {
1072            (Ok(v), _) => Ok(v),
1073            (Err(err), Some(context)) => {
1074                let (label, source_file) = label_and_source_file_from_location(
1075                    context.assembly_location(Some(op_idx)).as_ref(),
1076                    host,
1077                );
1078                Err(match err {
1079                    AceEvalError::Ace(error) => {
1080                        ExecutionError::AceChipError { label, source_file, error }
1081                    },
1082                    AceEvalError::Memory(err) => {
1083                        ExecutionError::MemoryError { label, source_file, err }
1084                    },
1085                })
1086            },
1087            (Err(err), None) => {
1088                let (label, source_file) = get_label_and_source_file();
1089                Err(match err {
1090                    AceEvalError::Ace(error) => {
1091                        ExecutionError::AceChipError { label, source_file, error }
1092                    },
1093                    AceEvalError::Memory(err) => {
1094                        ExecutionError::MemoryError { label, source_file, err }
1095                    },
1096                })
1097            },
1098        }
1099    }
1100}
1101
1102// TESTS
1103// ================================================================================================
1104
1105#[cfg(test)]
1106mod error_assertions {
1107    use alloc::sync::Arc;
1108
1109    use miden_core::mast::MastNodeId;
1110    use miden_debug_types::{ByteIndex, SourceId, Uri};
1111    use miden_mast_package::debug_info::{
1112        DebugSourceAsmOp, DebugSourceNode, PackageDebugInfoBuilder,
1113    };
1114
1115    use super::*;
1116
1117    /// Asserts at compile time that the passed error has Send + Sync + 'static bounds.
1118    fn _assert_error_is_send_sync_static<E: core::error::Error + Send + Sync + 'static>(_: E) {}
1119
1120    fn _assert_execution_error_bounds(err: ExecutionError) {
1121        _assert_error_is_send_sync_static(err);
1122    }
1123
1124    fn debug_asm_op(
1125        builder: &mut PackageDebugInfoBuilder,
1126        op_idx: u32,
1127        location: Option<Location>,
1128        context_name: &str,
1129        op_name: &str,
1130    ) -> DebugSourceAsmOp {
1131        DebugSourceAsmOp::new(
1132            op_idx,
1133            location.map(|location| builder.add_location(location)),
1134            builder.add_string(context_name),
1135            builder.add_string(op_name),
1136            1,
1137        )
1138    }
1139
1140    fn debug_source_node(exec_node: u32, asm_ops: Vec<DebugSourceAsmOp>) -> DebugSourceNode {
1141        let op_end = asm_ops.iter().map(|row| row.op_idx + 1).max().unwrap_or(1);
1142        DebugSourceNode {
1143            exec_node: MastNodeId::from(exec_node),
1144            children: Vec::new(),
1145            op_start: 0,
1146            op_end,
1147            asm_ops,
1148            debug_vars: Vec::new(),
1149            inline_calls: Vec::new(),
1150        }
1151    }
1152
1153    struct RecordingHost {
1154        expected_location: Location,
1155        returned_span: SourceSpan,
1156    }
1157
1158    impl BaseHost for RecordingHost {
1159        fn get_label_and_source_file(
1160            &self,
1161            location: &Location,
1162        ) -> (SourceSpan, Option<Arc<SourceFile>>) {
1163            assert_eq!(location, &self.expected_location);
1164            (self.returned_span, None)
1165        }
1166    }
1167
1168    #[test]
1169    fn package_source_context_resolves_by_source_occurrence() {
1170        let location_a = Location::new(
1171            Uri::new("file://pkg/first.masm"),
1172            ByteIndex::new(10),
1173            ByteIndex::new(13),
1174        );
1175        let location_b = Location::new(
1176            Uri::new("file://pkg/second.masm"),
1177            ByteIndex::new(20),
1178            ByteIndex::new(24),
1179        );
1180        let later_location_b = Location::new(
1181            Uri::new("file://pkg/second-later.masm"),
1182            ByteIndex::new(30),
1183            ByteIndex::new(35),
1184        );
1185        let mut builder = PackageDebugInfoBuilder::default();
1186        let source_a_op = debug_asm_op(&mut builder, 0, Some(location_a), "first", "add");
1187        let _source_a = builder.add_node(debug_source_node(0, vec![source_a_op])).unwrap();
1188        let source_b_later_op =
1189            debug_asm_op(&mut builder, 2, Some(later_location_b), "second_later", "mul");
1190        let source_b_op = debug_asm_op(&mut builder, 0, Some(location_b.clone()), "second", "add");
1191        let source_b = builder
1192            .add_node(debug_source_node(1, vec![source_b_later_op, source_b_op]))
1193            .unwrap();
1194        let debug_info = *builder.build();
1195        let host = RecordingHost {
1196            expected_location: location_b,
1197            returned_span: SourceSpan::new(SourceId::new(7), 20u32..24),
1198        };
1199        let context = PackageSourceDebugContext::new(&debug_info, source_b);
1200
1201        assert_eq!(context.assembly_location(None), Some(host.expected_location.clone()));
1202
1203        let err = OperationError::DivideByZero.with_package_source_context(context, &host, Some(0));
1204
1205        match err {
1206            ExecutionError::OperationError { label, source_file, err } => {
1207                assert_eq!(label, host.returned_span);
1208                assert!(source_file.is_none());
1209                assert!(matches!(err, OperationError::DivideByZero));
1210            },
1211            err => panic!("expected operation error, got {err:?}"),
1212        }
1213    }
1214
1215    #[test]
1216    fn package_source_context_without_location_uses_unknown_span() {
1217        let mut builder = PackageDebugInfoBuilder::default();
1218        let asm_op = debug_asm_op(&mut builder, 0, None, "missing_location", "add");
1219        let source_node_id = builder.add_node(debug_source_node(0, vec![asm_op])).unwrap();
1220        let debug_info = *builder.build();
1221        let host = RecordingHost {
1222            expected_location: Location::new(
1223                Uri::new("file://unused.masm"),
1224                ByteIndex::new(0),
1225                ByteIndex::new(0),
1226            ),
1227            returned_span: SourceSpan::new(SourceId::new(7), 20u32..24),
1228        };
1229        let context = PackageSourceDebugContext::new(&debug_info, source_node_id);
1230
1231        let err = advice_error_with_package_source_context(
1232            AdviceError::StackReadFailed,
1233            context,
1234            &host,
1235            Some(0),
1236        );
1237
1238        match err {
1239            ExecutionError::AdviceError { label, source_file, err } => {
1240                assert_eq!(label, SourceSpan::UNKNOWN);
1241                assert!(source_file.is_none());
1242                assert!(matches!(err, AdviceError::StackReadFailed));
1243            },
1244            err => panic!("expected advice error, got {err:?}"),
1245        }
1246    }
1247
1248    #[test]
1249    fn package_debug_info_without_source_node_restores_error_message() {
1250        let mut builder = PackageDebugInfoBuilder::default();
1251        assert!(builder.add_error_message(7, Arc::from("some error message")));
1252        let debug_info = *builder.build();
1253        let context = PackageSourceDebugContext::new_optional(&debug_info, None);
1254        let err = Err::<(), _>(OperationError::FailedAssertion {
1255            err_code: Felt::from_u32(7),
1256            err_msg: None,
1257        })
1258        .map_exec_err_with_package_source_op_idx(
1259            Some(context),
1260            &RecordingHost {
1261                expected_location: Location::new(
1262                    Uri::new("file://unused.masm"),
1263                    ByteIndex::new(0),
1264                    ByteIndex::new(0),
1265                ),
1266                returned_span: SourceSpan::new(SourceId::new(7), 20u32..24),
1267            },
1268            0,
1269        )
1270        .unwrap_err();
1271
1272        match err {
1273            ExecutionError::OperationError {
1274                label,
1275                source_file,
1276                err: OperationError::FailedAssertion { err_msg, .. },
1277            } => {
1278                assert_eq!(label, SourceSpan::UNKNOWN);
1279                assert!(source_file.is_none());
1280                assert_eq!(err_msg.as_deref(), Some("some error message"));
1281            },
1282            err => panic!("expected failed assertion operation error, got {err:?}"),
1283        }
1284    }
1285
1286    #[test]
1287    fn package_debug_info_restores_merkle_path_error_message() {
1288        let mut builder = PackageDebugInfoBuilder::default();
1289        assert!(builder.add_error_message(7, Arc::from("some error message")));
1290        let debug_info = *builder.build();
1291        let err = OperationError::MerklePathVerificationFailed {
1292            inner: Box::new(MerklePathVerificationFailedInner {
1293                value: Word::default(),
1294                index: Felt::from_u32(3),
1295                root: Word::default(),
1296                err_code: Felt::from_u32(7),
1297                err_msg: None,
1298            }),
1299        }
1300        .with_package_debug_info(&debug_info);
1301
1302        match err {
1303            OperationError::MerklePathVerificationFailed { inner } => {
1304                assert_eq!(inner.err_msg.as_deref(), Some("some error message"));
1305            },
1306            err => panic!("expected MerklePathVerificationFailed, got {err:?}"),
1307        }
1308    }
1309}