use std::fmt;
use thiserror::Error;
use crate::{Diagnostic, DiagnosticReport, Source};
pub type DiagnosticResult<T> = Result<T, DiagnosticReport>;
#[derive(Debug, Error)]
#[error("{}", self.error)]
pub struct DiagnosticError {
#[source]
error: Box<dyn std::error::Error + Send + Sync + 'static>,
code: String,
}
impl DiagnosticError {
pub fn inner(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
&*self.error
}
}
impl Diagnostic for DiagnosticError {
fn code<'a>(&'a self) -> Box<dyn std::fmt::Display + 'a> {
Box::new(&self.code)
}
}
pub trait IntoDiagnostic<T, E> {
fn into_diagnostic(self, code: impl fmt::Display) -> Result<T, DiagnosticError>;
}
impl<T, E: std::error::Error + Send + Sync + 'static> IntoDiagnostic<T, E> for Result<T, E> {
fn into_diagnostic(self, code: impl fmt::Display) -> Result<T, DiagnosticError> {
self.map_err(|e| DiagnosticError {
error: Box::new(e),
code: format!("{}", code),
})
}
}
#[derive(Debug)]
pub struct NamedSource {
source: Box<dyn Source + Send + Sync + 'static>,
name: String,
}
impl NamedSource {
pub fn new(name: impl AsRef<str>, source: impl Source + Send + Sync + 'static) -> Self {
Self {
source: Box::new(source),
name: name.as_ref().to_string(),
}
}
pub fn inner(&self) -> &(dyn Source + Send + Sync + 'static) {
&*self.source
}
}
impl Source for NamedSource {
fn read_span<'a>(
&'a self,
span: &crate::SourceSpan,
) -> Result<Box<dyn crate::SpanContents + 'a>, crate::MietteError> {
self.source.read_span(span)
}
fn name(&self) -> Option<String> {
Some(self.name.clone())
}
}