use proc_macro::Span;
#[cfg(feature = "pretty_errors")]
use proc_macro2::Span as Span2;
#[cfg(feature = "pretty_errors")]
use proc_macro2_diagnostics::{Diagnostic, Level};
#[derive(Debug)]
pub struct Error
{
msg: String,
#[cfg(feature = "pretty_errors")]
span: Span,
#[cfg(feature = "pretty_errors")]
hint: String,
}
impl Error
{
pub fn new(msg: impl Into<String>) -> Self
{
#[cfg(feature = "pretty_errors")]
{
Self {
msg: msg.into(),
span: Span::call_site(),
hint: "".to_string(),
}
}
#[cfg(not(feature = "pretty_errors"))]
{
Self { msg: msg.into() }
}
}
#[allow(unused_variables)]
#[allow(unused_mut)]
pub fn span(mut self, span: Span) -> Self
{
#[cfg(feature = "pretty_errors")]
{
self.span = span;
}
self
}
#[allow(unused_variables)]
#[allow(unused_mut)]
pub fn hint(mut self, hint: impl Into<String>) -> Self
{
#[cfg(feature = "pretty_errors")]
{
self.hint = hint.into();
}
self
}
pub fn get_span(&self) -> Span
{
#[cfg(feature = "pretty_errors")]
{
self.span
}
#[cfg(not(feature = "pretty_errors"))]
{
Span::call_site()
}
}
#[cfg(not(feature = "pretty_errors"))]
pub fn into_panic_message(self) -> String
{
self.msg
}
#[cfg(feature = "pretty_errors")]
pub fn into_diagnostic(self) -> Diagnostic
{
let mut diagnostic = Diagnostic::spanned(Span2::from(self.span), Level::Error, self.msg);
if !self.hint.is_empty()
{
diagnostic = diagnostic.help(self.hint);
}
diagnostic
}
}