Skip to main content

leo_errors/common/
backtraced.rs

1// Copyright (C) 2019-2026 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use std::fmt;
18
19use crate::Backtrace;
20use colored::Colorize;
21use derivative::Derivative;
22use leo_span::source_map::is_color;
23
24#[cfg(not(target_arch = "wasm32"))]
25use color_backtrace::{BacktracePrinter, Verbosity};
26
27/// The indent for an error message.
28pub(crate) const INDENT: &str = "    ";
29
30/// Computes the exit code from a code identifier and error code.
31pub fn compute_exit_code(code_identifier: i8, code: i32) -> i32 {
32    let base = if code_identifier > 99 {
33        code_identifier as i32 * 100_000
34    } else if code_identifier as i32 > 9 {
35        code_identifier as i32 * 10_000
36    } else {
37        code_identifier as i32 * 1_000
38    };
39    base + code
40}
41
42/// Formats a unique error identifier string.
43pub fn format_error_code(type_: &str, code_identifier: i8, code: i32) -> String {
44    format!("E{type_}{code_identifier:0>3}{code:0>4}")
45}
46
47/// Formats a unique warning identifier string.
48pub fn format_warning_code(type_: &str, code_identifier: i8, code: i32) -> String {
49    format!("W{type_}{code_identifier:0>3}{code:0>4}")
50}
51
52/// Backtraced compiler output type
53///     undefined value `x`
54///     --> file.leo: 2:8
55///      = help: Initialize a variable `x` first.
56#[derive(Derivative)]
57#[derivative(Clone, Debug, Default, Hash, PartialEq, Eq)]
58pub struct Backtraced {
59    /// The error message.
60    pub message: String,
61    /// The error help message if it exists.
62    pub help: Option<String>,
63    /// An optional contextual note (background information rather than an actionable fix).
64    pub note: Option<String>,
65    /// The error exit code.
66    pub code: i32,
67    /// The characters representing the type of error.
68    pub type_: String,
69    /// Is this Backtrace a warning or error?
70    pub error: bool,
71    /// The backtrace representing where the error occurred in Leo.
72    #[derivative(PartialEq = "ignore")]
73    #[derivative(Hash = "ignore")]
74    pub backtrace: Backtrace,
75}
76
77impl Backtraced {
78    /// Creates a backtraced error from a backtrace.
79    pub fn new_from_backtrace<S>(
80        message: S,
81        help: Option<String>,
82        code: i32,
83        type_: String,
84        error: bool,
85        backtrace: Backtrace,
86    ) -> Self
87    where
88        S: ToString,
89    {
90        Self { message: message.to_string(), help, note: None, code, type_, error, backtrace }
91    }
92
93    /// Create a new error.
94    pub fn error(code_prefix: &str, code: i32, message: impl ToString) -> Self {
95        Self::new_from_backtrace(message, None, code, code_prefix.to_string(), true, Backtrace::new())
96    }
97
98    /// Create a new warning.
99    pub fn warning(code_prefix: &str, code: i32, message: impl ToString) -> Self {
100        Self::new_from_backtrace(message, None, code, code_prefix.to_string(), false, Backtrace::new())
101    }
102
103    pub fn with_help(mut self, help: impl fmt::Display) -> Self {
104        self.help = Some(help.to_string());
105        self
106    }
107
108    pub fn with_note(mut self, note: impl fmt::Display) -> Self {
109        self.note = Some(note.to_string());
110        self
111    }
112
113    /// Gets the backtraced error exit code.
114    pub fn exit_code(&self) -> i32 {
115        compute_exit_code(37, self.code)
116    }
117
118    /// Gets a unique error identifier.
119    pub fn error_code(&self) -> String {
120        format_error_code(&self.type_, 37, self.code)
121    }
122
123    /// Gets a unique warning identifier.
124    pub fn warning_code(&self) -> String {
125        format_warning_code(&self.type_, 37, self.code)
126    }
127
128    /// Return whether this diagnostic represents an error rather than a warning.
129    ///
130    /// LSP severity mapping inspects this flag rather than the rendered prefix
131    /// in the diagnostic's `Display` output.
132    pub fn is_error(&self) -> bool {
133        self.error
134    }
135}
136
137impl fmt::Display for Backtraced {
138    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139        let (kind, code) = if self.error { ("Error", self.error_code()) } else { ("Warning", self.warning_code()) };
140        let message = format!("{kind} [{code}]: {message}", message = self.message,);
141
142        // To avoid the color enabling characters for comparison with test expectations.
143        if is_color() {
144            if self.error {
145                writeln!(f, "{}", message.bold().red())?;
146            } else {
147                writeln!(f, "{}", message.bold().yellow())?;
148            }
149        } else {
150            writeln!(f, "{message}")?;
151        };
152
153        if self.help.is_some() || self.note.is_some() {
154            write!(f, "{INDENT     } |")?;
155            if let Some(help) = &self.help {
156                write!(f, "\n{INDENT     } = {help}")?;
157            }
158            if let Some(note) = &self.note {
159                write!(f, "\n{INDENT     } = note: {note}")?;
160            }
161        }
162
163        #[cfg(not(target_arch = "wasm32"))]
164        {
165            let leo_backtrace = std::env::var("LEO_BACKTRACE").unwrap_or_default().trim().to_owned();
166            match leo_backtrace.as_ref() {
167                "1" => {
168                    let mut printer = BacktracePrinter::default();
169                    printer = printer.lib_verbosity(Verbosity::Medium);
170                    let trace = printer.format_trace_to_string(&self.backtrace).map_err(|_| fmt::Error)?;
171                    write!(f, "{trace}")?;
172                }
173                "full" => {
174                    let mut printer = BacktracePrinter::default();
175                    printer = printer.lib_verbosity(Verbosity::Full);
176                    let trace = printer.format_trace_to_string(&self.backtrace).map_err(|_| fmt::Error)?;
177                    write!(f, "{trace}")?;
178                }
179                _ => {}
180            }
181        }
182
183        Ok(())
184    }
185}
186
187impl std::error::Error for Backtraced {
188    fn description(&self) -> &str {
189        &self.message
190    }
191}