use crate::{Backtraced, INDENT};
use leo_span::{Span, with_session_globals};
use backtrace::Backtrace;
use color_backtrace::{BacktracePrinter, Verbosity};
use colored::Colorize;
use std::fmt;
#[derive(Clone, Debug, Default, Hash, PartialEq)]
pub struct Formatted {
pub span: Span,
pub backtrace: Backtraced,
}
impl Formatted {
#[allow(clippy::too_many_arguments)]
pub fn new_from_span<S>(
message: S,
help: Option<String>,
code: i32,
code_identifier: i8,
type_: String,
error: bool,
span: Span,
backtrace: Backtrace,
) -> Self
where
S: ToString,
{
Self {
span,
backtrace: Backtraced::new_from_backtrace(
message.to_string(),
help,
code,
code_identifier,
type_,
error,
backtrace,
),
}
}
pub fn exit_code(&self) -> i32 {
self.backtrace.exit_code()
}
pub fn error_code(&self) -> String {
self.backtrace.error_code()
}
pub fn warning_code(&self) -> String {
self.backtrace.warning_code()
}
}
impl fmt::Display for Formatted {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Some(source_file) = with_session_globals(|s| s.source_map.find_source_file(self.span.lo)) else {
return write!(f, "Can't find source file");
};
let line_contents = source_file.line_contents(self.span);
let (kind, code) =
if self.backtrace.error { ("Error", self.error_code()) } else { ("Warning", self.warning_code()) };
let message = format!("{kind} [{code}]: {message}", message = self.backtrace.message,);
if std::env::var("NOCOLOR").unwrap_or_default().trim().to_owned().is_empty() {
if self.backtrace.error {
writeln!(f, "{}", message.bold().red())?;
} else {
writeln!(f, "{}", message.bold().yellow())?;
}
} else {
writeln!(f, "{message}")?;
};
writeln!(
f,
"{indent }--> {path}:{line_start}:{start}",
indent = INDENT,
path = &source_file.name,
line_start = line_contents.line + 1,
start = line_contents.start + 1,
)?;
write!(f, "{line_contents}")?;
if let Some(help) = &self.backtrace.help {
writeln!(
f,
"{INDENT } |\n\
{INDENT } = {help}",
)?;
}
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.verbosity(Verbosity::Medium);
printer = printer.lib_verbosity(Verbosity::Medium);
let trace = printer.format_trace_to_string(&self.backtrace.backtrace).map_err(|_| fmt::Error)?;
write!(f, "\n{trace}")?;
}
"full" => {
let mut printer = BacktracePrinter::default();
printer = printer.verbosity(Verbosity::Full);
printer = printer.lib_verbosity(Verbosity::Full);
let trace = printer.format_trace_to_string(&self.backtrace.backtrace).map_err(|_| fmt::Error)?;
write!(f, "\n{trace}")?;
}
_ => {}
}
Ok(())
}
}
impl std::error::Error for Formatted {
fn description(&self) -> &str {
&self.backtrace.message
}
}