miden_lib/errors/
script_builder_errors.rs

1use alloc::boxed::Box;
2use alloc::string::String;
3use core::error::Error;
4
5use miden_objects::assembly::diagnostics::Report;
6use miden_objects::assembly::diagnostics::reporting::PrintDiagnostic;
7
8// SCRIPT BUILDER ERROR
9// ================================================================================================
10
11#[derive(Debug, thiserror::Error)]
12#[error("failed to build script: {message}")]
13pub struct ScriptBuilderError {
14    /// Stack size of `Box<str>` is smaller than String.
15    message: Box<str>,
16    /// thiserror will return this when calling Error::source on ScriptBuilderError.
17    source: Option<Box<dyn Error + Send + Sync + 'static>>,
18}
19
20impl ScriptBuilderError {
21    /// Creates a script builder error from an error message and a source error.
22    pub fn build_error_with_source(
23        message: impl Into<String>,
24        source: impl Error + Send + Sync + 'static,
25    ) -> Self {
26        let message: String = message.into();
27        Self {
28            message: message.into(),
29            source: Some(Box::new(source)),
30        }
31    }
32
33    /// Creates a script builder error from a context message and a Report.
34    ///
35    /// This method uses PrintDiagnostic to stringify the Report since Report doesn't
36    /// implement core::error::Error and cannot be returned as a source error.
37    pub fn build_error_with_report(context: impl Into<String>, report: Report) -> Self {
38        let context: String = context.into();
39        let message = format!("{}: {}", context, PrintDiagnostic::new(&report));
40        Self { message: message.into(), source: None }
41    }
42}
43
44#[cfg(test)]
45mod error_assertions {
46    use super::*;
47
48    /// Asserts at compile time that the passed error has Send + Sync + 'static bounds.
49    fn _assert_error_is_send_sync_static<E: core::error::Error + Send + Sync + 'static>(_: E) {}
50
51    fn _assert_script_builder_error_bounds(err: ScriptBuilderError) {
52        _assert_error_is_send_sync_static(err);
53    }
54}