leo-errors 4.1.0

Errors for the Leo programming language
Documentation
// Copyright (C) 2019-2026 Provable Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use std::fmt;

use crate::Backtrace;
use colored::Colorize;
use derivative::Derivative;
use leo_span::source_map::is_color;

#[cfg(not(target_arch = "wasm32"))]
use color_backtrace::{BacktracePrinter, Verbosity};

/// The indent for an error message.
pub(crate) const INDENT: &str = "    ";

/// Computes the exit code from a code identifier and error code.
pub fn compute_exit_code(code_identifier: i8, code: i32) -> i32 {
    let base = if code_identifier > 99 {
        code_identifier as i32 * 100_000
    } else if code_identifier as i32 > 9 {
        code_identifier as i32 * 10_000
    } else {
        code_identifier as i32 * 1_000
    };
    base + code
}

/// Formats a unique error identifier string.
pub fn format_error_code(type_: &str, code_identifier: i8, code: i32) -> String {
    format!("E{type_}{code_identifier:0>3}{code:0>4}")
}

/// Formats a unique warning identifier string.
pub fn format_warning_code(type_: &str, code_identifier: i8, code: i32) -> String {
    format!("W{type_}{code_identifier:0>3}{code:0>4}")
}

/// Backtraced compiler output type
///     undefined value `x`
///     --> file.leo: 2:8
///      = help: Initialize a variable `x` first.
#[derive(Derivative)]
#[derivative(Clone, Debug, Default, Hash, PartialEq, Eq)]
pub struct Backtraced {
    /// The error message.
    pub message: String,
    /// The error help message if it exists.
    pub help: Option<String>,
    /// An optional contextual note (background information rather than an actionable fix).
    pub note: Option<String>,
    /// The error exit code.
    pub code: i32,
    /// The characters representing the type of error.
    pub type_: String,
    /// Is this Backtrace a warning or error?
    pub error: bool,
    /// The backtrace representing where the error occurred in Leo.
    #[derivative(PartialEq = "ignore")]
    #[derivative(Hash = "ignore")]
    pub backtrace: Backtrace,
}

impl Backtraced {
    /// Creates a backtraced error from a backtrace.
    pub fn new_from_backtrace<S>(
        message: S,
        help: Option<String>,
        code: i32,
        type_: String,
        error: bool,
        backtrace: Backtrace,
    ) -> Self
    where
        S: ToString,
    {
        Self { message: message.to_string(), help, note: None, code, type_, error, backtrace }
    }

    /// Create a new error.
    pub fn error(code_prefix: &str, code: i32, message: impl ToString) -> Self {
        Self::new_from_backtrace(message, None, code, code_prefix.to_string(), true, Backtrace::new())
    }

    /// Create a new warning.
    pub fn warning(code_prefix: &str, code: i32, message: impl ToString) -> Self {
        Self::new_from_backtrace(message, None, code, code_prefix.to_string(), false, Backtrace::new())
    }

    pub fn with_help(mut self, help: impl fmt::Display) -> Self {
        self.help = Some(help.to_string());
        self
    }

    pub fn with_note(mut self, note: impl fmt::Display) -> Self {
        self.note = Some(note.to_string());
        self
    }

    /// Gets the backtraced error exit code.
    pub fn exit_code(&self) -> i32 {
        compute_exit_code(37, self.code)
    }

    /// Gets a unique error identifier.
    pub fn error_code(&self) -> String {
        format_error_code(&self.type_, 37, self.code)
    }

    /// Gets a unique warning identifier.
    pub fn warning_code(&self) -> String {
        format_warning_code(&self.type_, 37, self.code)
    }

    /// Return whether this diagnostic represents an error rather than a warning.
    ///
    /// LSP severity mapping inspects this flag rather than the rendered prefix
    /// in the diagnostic's `Display` output.
    pub fn is_error(&self) -> bool {
        self.error
    }
}

impl fmt::Display for Backtraced {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (kind, code) = if self.error { ("Error", self.error_code()) } else { ("Warning", self.warning_code()) };
        let message = format!("{kind} [{code}]: {message}", message = self.message,);

        // To avoid the color enabling characters for comparison with test expectations.
        if is_color() {
            if self.error {
                writeln!(f, "{}", message.bold().red())?;
            } else {
                writeln!(f, "{}", message.bold().yellow())?;
            }
        } else {
            writeln!(f, "{message}")?;
        };

        if self.help.is_some() || self.note.is_some() {
            write!(f, "{INDENT     } |")?;
            if let Some(help) = &self.help {
                write!(f, "\n{INDENT     } = {help}")?;
            }
            if let Some(note) = &self.note {
                write!(f, "\n{INDENT     } = note: {note}")?;
            }
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let leo_backtrace = std::env::var("LEO_BACKTRACE").unwrap_or_default().trim().to_owned();
            match leo_backtrace.as_ref() {
                "1" => {
                    let mut printer = BacktracePrinter::default();
                    printer = printer.lib_verbosity(Verbosity::Medium);
                    let trace = printer.format_trace_to_string(&self.backtrace).map_err(|_| fmt::Error)?;
                    write!(f, "{trace}")?;
                }
                "full" => {
                    let mut printer = BacktracePrinter::default();
                    printer = printer.lib_verbosity(Verbosity::Full);
                    let trace = printer.format_trace_to_string(&self.backtrace).map_err(|_| fmt::Error)?;
                    write!(f, "{trace}")?;
                }
                _ => {}
            }
        }

        Ok(())
    }
}

impl std::error::Error for Backtraced {
    fn description(&self) -> &str {
        &self.message
    }
}