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, source_map::SpanLocation, symbol::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)]
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 underline = |mut start: usize, mut end: usize| -> String {
92            if start > end {
93                std::mem::swap(&mut start, &mut end)
94            }
95
96            let mut underline = String::new();
97
98            for _ in 0..start {
99                underline.push(' ');
100                end -= 1;
101            }
102
103            for _ in 0..end {
104                underline.push('^');
105            }
106
107            underline
108        };
109
110        let (loc, contents) = with_session_globals(|s| {
111            (
112                s.source_map.span_to_location(self.span).unwrap_or_else(SpanLocation::dummy),
113                s.source_map.line_contents_of_span(self.span).unwrap_or_else(|| "<contents unavailable>".to_owned()),
114            )
115        });
116
117        let underlined = underline(loc.col_start, loc.col_stop);
118
119        let (kind, code) =
120            if self.backtrace.error { ("Error", self.error_code()) } else { ("Warning", self.warning_code()) };
121
122        let message = format!("{kind} [{code}]: {message}", message = self.backtrace.message,);
123
124        // To avoid the color enabling characters for comparison with test expectations.
125        if std::env::var("NOCOLOR").unwrap_or_default().trim().to_owned().is_empty() {
126            if self.backtrace.error {
127                write!(f, "{}", message.bold().red())?;
128            } else {
129                write!(f, "{}", message.bold().yellow())?;
130            }
131        } else {
132            write!(f, "{message}")?;
133        };
134
135        write!(
136            f,
137            "\n{indent     }--> {path}:{line_start}:{start}\n\
138            {indent     } |\n",
139            indent = INDENT,
140            path = &loc.source_file.name,
141            line_start = loc.line_start,
142            start = loc.col_start,
143        )?;
144
145        for (line_no, line) in contents.lines().enumerate() {
146            writeln!(
147                f,
148                "{line_no:width$} | {text}",
149                width = INDENT.len(),
150                line_no = loc.line_start + line_no,
151                text = line,
152            )?;
153        }
154
155        write!(f, "{INDENT     } |{underlined}",)?;
156
157        if let Some(help) = &self.backtrace.help {
158            write!(
159                f,
160                "\n{INDENT     } |\n\
161            {INDENT     } = {help}",
162            )?;
163        }
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.verbosity(Verbosity::Medium);
170                printer = printer.lib_verbosity(Verbosity::Medium);
171                let trace = printer.format_trace_to_string(&self.backtrace.backtrace).map_err(|_| fmt::Error)?;
172                write!(f, "\n{trace}")?;
173            }
174            "full" => {
175                let mut printer = BacktracePrinter::default();
176                printer = printer.verbosity(Verbosity::Full);
177                printer = printer.lib_verbosity(Verbosity::Full);
178                let trace = printer.format_trace_to_string(&self.backtrace.backtrace).map_err(|_| fmt::Error)?;
179                write!(f, "\n{trace}")?;
180            }
181            _ => {}
182        }
183
184        Ok(())
185    }
186}
187
188impl std::error::Error for Formatted {
189    fn description(&self) -> &str {
190        &self.backtrace.message
191    }
192}