leo_errors/common/
formatted.rs

1// Copyright (C) 2019-2025 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 crate::{Backtraced, INDENT};
18
19use leo_span::{Span, with_session_globals};
20
21use backtrace::Backtrace;
22use color_backtrace::{BacktracePrinter, Verbosity};
23use colored::Colorize;
24use std::fmt;
25
26/// Formatted compiler error type
27///     undefined value `x`
28///     --> file.leo: 2:8
29///      |
30///    2 | let a = x;
31///      |         ^
32///      |
33///      = help: Initialize a variable `x` first.
34/// Makes use of the same fields as a BacktracedError.
35#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
36pub struct Formatted {
37    /// The formatted error span information.
38    pub span: Span,
39    /// The backtrace to track where the Leo error originated.
40    pub backtrace: Backtraced,
41}
42
43impl Formatted {
44    /// Creates a backtraced error from a span and a backtrace.
45    #[allow(clippy::too_many_arguments)]
46    pub fn new_from_span<S>(
47        message: S,
48        help: Option<String>,
49        code: i32,
50        code_identifier: i8,
51        type_: String,
52        error: bool,
53        span: Span,
54        backtrace: Backtrace,
55    ) -> Self
56    where
57        S: ToString,
58    {
59        Self {
60            span,
61            backtrace: Backtraced::new_from_backtrace(
62                message.to_string(),
63                help,
64                code,
65                code_identifier,
66                type_,
67                error,
68                backtrace,
69            ),
70        }
71    }
72
73    /// Calls the backtraces error exit code.
74    pub fn exit_code(&self) -> i32 {
75        self.backtrace.exit_code()
76    }
77
78    /// Returns an error identifier.
79    pub fn error_code(&self) -> String {
80        self.backtrace.error_code()
81    }
82
83    /// Returns an warning identifier.
84    pub fn warning_code(&self) -> String {
85        self.backtrace.warning_code()
86    }
87}
88
89impl fmt::Display for Formatted {
90    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91        let (kind, code) =
92            if self.backtrace.error { ("Error", self.error_code()) } else { ("Warning", self.warning_code()) };
93
94        let message = format!("{kind} [{code}]: {message}", message = self.backtrace.message,);
95
96        // To avoid the color enabling characters for comparison with test expectations.
97        if std::env::var("NOCOLOR").unwrap_or_default().trim().to_owned().is_empty() {
98            if self.backtrace.error {
99                writeln!(f, "{}", message.bold().red())?;
100            } else {
101                writeln!(f, "{}", message.bold().yellow())?;
102            }
103        } else {
104            writeln!(f, "{message}")?;
105        };
106
107        if let Some(source_file) = with_session_globals(|s| s.source_map.find_source_file(self.span.lo)) {
108            let line_contents = source_file.line_contents(self.span);
109
110            writeln!(
111                f,
112                "{indent     }--> {path}:{line_start}:{start}",
113                indent = INDENT,
114                path = &source_file.name,
115                // Report lines starting from line 1.
116                line_start = line_contents.line + 1,
117                // And columns - comments in some old code claims to report columns indexing from 0,
118                // but that doesn't appear to have been true.
119                start = line_contents.start + 1,
120            )?;
121
122            write!(f, "{line_contents}")?;
123        };
124
125        if let Some(help) = &self.backtrace.help {
126            writeln!(
127                f,
128                "{INDENT     } |\n\
129                {INDENT     } = {help}",
130            )?;
131        }
132
133        let leo_backtrace = std::env::var("LEO_BACKTRACE").unwrap_or_default().trim().to_owned();
134        match leo_backtrace.as_ref() {
135            "1" => {
136                let mut printer = BacktracePrinter::default();
137                printer = printer.verbosity(Verbosity::Medium);
138                printer = printer.lib_verbosity(Verbosity::Medium);
139                let trace = printer.format_trace_to_string(&self.backtrace.backtrace).map_err(|_| fmt::Error)?;
140                write!(f, "\n{trace}")?;
141            }
142            "full" => {
143                let mut printer = BacktracePrinter::default();
144                printer = printer.verbosity(Verbosity::Full);
145                printer = printer.lib_verbosity(Verbosity::Full);
146                let trace = printer.format_trace_to_string(&self.backtrace.backtrace).map_err(|_| fmt::Error)?;
147                write!(f, "\n{trace}")?;
148            }
149            _ => {}
150        }
151
152        Ok(())
153    }
154}
155
156impl std::error::Error for Formatted {
157    fn description(&self) -> &str {
158        &self.backtrace.message
159    }
160}