use std::{
fmt::{self, Display},
fs,
panic::Location,
};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use crate::MietteError;
pub trait Diagnostic: std::error::Error {
fn code<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
None
}
fn severity(&self) -> Option<Severity> {
None
}
fn help<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
None
}
fn url<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
None
}
fn source_code(&self) -> Option<&dyn SourceCode> {
None
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
None
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
None
}
fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
None
}
}
macro_rules! box_error_impls {
($($box_type:ty),*) => {
$(
impl std::error::Error for $box_type {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
(**self).source()
}
fn cause(&self) -> Option<&dyn std::error::Error> {
self.source()
}
}
)*
}
}
box_error_impls! {
Box<dyn Diagnostic>,
Box<dyn Diagnostic + Send>,
Box<dyn Diagnostic + Send + Sync>
}
macro_rules! box_borrow_impls {
($($box_type:ty),*) => {
$(
impl std::borrow::Borrow<dyn Diagnostic> for $box_type {
fn borrow(&self) -> &(dyn Diagnostic + 'static) {
self.as_ref()
}
}
)*
}
}
box_borrow_impls! {
Box<dyn Diagnostic + Send>,
Box<dyn Diagnostic + Send + Sync>
}
impl<T: Diagnostic + Send + Sync + 'static> From<T>
for Box<dyn Diagnostic + Send + Sync + 'static>
{
fn from(diag: T) -> Self {
Box::new(diag)
}
}
impl<T: Diagnostic + Send + Sync + 'static> From<T> for Box<dyn Diagnostic + Send + 'static> {
fn from(diag: T) -> Self {
Box::<dyn Diagnostic + Send + Sync>::from(diag)
}
}
impl<T: Diagnostic + Send + Sync + 'static> From<T> for Box<dyn Diagnostic + 'static> {
fn from(diag: T) -> Self {
Box::<dyn Diagnostic + Send + Sync>::from(diag)
}
}
impl From<&str> for Box<dyn Diagnostic> {
fn from(s: &str) -> Self {
From::from(String::from(s))
}
}
impl<'a> From<&str> for Box<dyn Diagnostic + Send + Sync + 'a> {
fn from(s: &str) -> Self {
From::from(String::from(s))
}
}
impl From<String> for Box<dyn Diagnostic> {
fn from(s: String) -> Self {
let err1: Box<dyn Diagnostic + Send + Sync> = From::from(s);
let err2: Box<dyn Diagnostic> = err1;
err2
}
}
impl From<String> for Box<dyn Diagnostic + Send + Sync> {
fn from(s: String) -> Self {
struct StringError(String);
impl std::error::Error for StringError {}
impl Diagnostic for StringError {}
impl Display for StringError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
impl fmt::Debug for StringError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
Box::new(StringError(s))
}
}
impl From<Box<dyn std::error::Error + Send + Sync>> for Box<dyn Diagnostic + Send + Sync> {
fn from(s: Box<dyn std::error::Error + Send + Sync>) -> Self {
#[derive(thiserror::Error)]
#[error(transparent)]
struct BoxedDiagnostic(Box<dyn std::error::Error + Send + Sync>);
impl fmt::Debug for BoxedDiagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl Diagnostic for BoxedDiagnostic {}
Box::new(BoxedDiagnostic(s))
}
}
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Default)]
pub enum Severity {
Advice,
Warning,
#[default]
Error,
}
#[cfg(feature = "serde")]
#[test]
fn test_serialize_severity() {
use serde_json::json;
assert_eq!(json!(Severity::Advice), json!("Advice"));
assert_eq!(json!(Severity::Warning), json!("Warning"));
assert_eq!(json!(Severity::Error), json!("Error"));
}
#[cfg(feature = "serde")]
#[test]
fn test_deserialize_severity() {
use serde_json::json;
let severity: Severity = serde_json::from_value(json!("Advice")).unwrap();
assert_eq!(severity, Severity::Advice);
let severity: Severity = serde_json::from_value(json!("Warning")).unwrap();
assert_eq!(severity, Severity::Warning);
let severity: Severity = serde_json::from_value(json!("Error")).unwrap();
assert_eq!(severity, Severity::Error);
}
pub trait SourceCode: Send + Sync {
fn read_span<'a>(
&'a self,
span: &SourceSpan,
context_lines_before: usize,
context_lines_after: usize,
) -> Result<Box<dyn SpanContents<'a> + 'a>, MietteError>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LabeledSpan {
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
label: Option<String>,
span: SourceSpan,
primary: bool,
}
impl LabeledSpan {
pub const fn new(label: Option<String>, offset: ByteOffset, len: usize) -> Self {
Self {
label,
span: SourceSpan::new(SourceOffset(offset), len),
primary: false,
}
}
pub fn new_with_span(label: Option<String>, span: impl Into<SourceSpan>) -> Self {
Self {
label,
span: span.into(),
primary: false,
}
}
pub fn new_primary_with_span(label: Option<String>, span: impl Into<SourceSpan>) -> Self {
Self {
label,
span: span.into(),
primary: true,
}
}
pub fn set_label(&mut self, label: Option<String>) {
self.label = label;
}
pub fn at(span: impl Into<SourceSpan>, label: impl Into<String>) -> Self {
Self::new_with_span(Some(label.into()), span)
}
pub fn at_offset(offset: ByteOffset, label: impl Into<String>) -> Self {
Self::new(Some(label.into()), offset, 0)
}
pub fn underline(span: impl Into<SourceSpan>) -> Self {
Self::new_with_span(None, span)
}
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
pub const fn inner(&self) -> &SourceSpan {
&self.span
}
pub const fn offset(&self) -> usize {
self.span.offset()
}
pub const fn len(&self) -> usize {
self.span.len()
}
pub const fn is_empty(&self) -> bool {
self.span.is_empty()
}
pub const fn primary(&self) -> bool {
self.primary
}
}
#[cfg(feature = "serde")]
#[test]
fn test_serialize_labeled_span() {
use serde_json::json;
assert_eq!(
json!(LabeledSpan::new(None, 0, 0)),
json!({
"span": { "offset": 0, "length": 0, },
"primary": false,
})
);
assert_eq!(
json!(LabeledSpan::new(Some("label".to_string()), 0, 0)),
json!({
"label": "label",
"span": { "offset": 0, "length": 0, },
"primary": false,
})
);
}
#[cfg(feature = "serde")]
#[test]
fn test_deserialize_labeled_span() {
use serde_json::json;
let span: LabeledSpan = serde_json::from_value(json!({
"label": null,
"span": { "offset": 0, "length": 0, },
"primary": false,
}))
.unwrap();
assert_eq!(span, LabeledSpan::new(None, 0, 0));
let span: LabeledSpan = serde_json::from_value(json!({
"span": { "offset": 0, "length": 0, },
"primary": false
}))
.unwrap();
assert_eq!(span, LabeledSpan::new(None, 0, 0));
let span: LabeledSpan = serde_json::from_value(json!({
"label": "label",
"span": { "offset": 0, "length": 0, },
"primary": false
}))
.unwrap();
assert_eq!(span, LabeledSpan::new(Some("label".to_string()), 0, 0));
}
pub trait SpanContents<'a> {
fn data(&self) -> &'a [u8];
fn span(&self) -> &SourceSpan;
fn name(&self) -> Option<&str> {
None
}
fn line(&self) -> usize;
fn column(&self) -> usize;
fn line_count(&self) -> usize;
fn language(&self) -> Option<&str> {
None
}
}
#[derive(Clone, Debug)]
pub struct MietteSpanContents<'a> {
data: &'a [u8],
span: SourceSpan,
line: usize,
column: usize,
line_count: usize,
name: Option<String>,
language: Option<String>,
}
impl<'a> MietteSpanContents<'a> {
pub const fn new(
data: &'a [u8],
span: SourceSpan,
line: usize,
column: usize,
line_count: usize,
) -> MietteSpanContents<'a> {
MietteSpanContents {
data,
span,
line,
column,
line_count,
name: None,
language: None,
}
}
pub const fn new_named(
name: String,
data: &'a [u8],
span: SourceSpan,
line: usize,
column: usize,
line_count: usize,
) -> MietteSpanContents<'a> {
MietteSpanContents {
data,
span,
line,
column,
line_count,
name: Some(name),
language: None,
}
}
pub fn with_language(mut self, language: impl Into<String>) -> Self {
self.language = Some(language.into());
self
}
}
impl<'a> SpanContents<'a> for MietteSpanContents<'a> {
fn data(&self) -> &'a [u8] {
self.data
}
fn span(&self) -> &SourceSpan {
&self.span
}
fn line(&self) -> usize {
self.line
}
fn column(&self) -> usize {
self.column
}
fn line_count(&self) -> usize {
self.line_count
}
fn name(&self) -> Option<&str> {
self.name.as_deref()
}
fn language(&self) -> Option<&str> {
self.language.as_deref()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SourceSpan {
offset: SourceOffset,
length: usize,
}
impl SourceSpan {
pub const fn new(start: SourceOffset, length: usize) -> Self {
Self {
offset: start,
length,
}
}
pub const fn offset(&self) -> usize {
self.offset.offset()
}
pub const fn len(&self) -> usize {
self.length
}
pub const fn is_empty(&self) -> bool {
self.length == 0
}
}
impl From<(ByteOffset, usize)> for SourceSpan {
fn from((start, len): (ByteOffset, usize)) -> Self {
Self {
offset: start.into(),
length: len,
}
}
}
impl From<(SourceOffset, usize)> for SourceSpan {
fn from((start, len): (SourceOffset, usize)) -> Self {
Self::new(start, len)
}
}
impl From<std::ops::Range<ByteOffset>> for SourceSpan {
fn from(range: std::ops::Range<ByteOffset>) -> Self {
Self {
offset: range.start.into(),
length: range.len(),
}
}
}
impl From<SourceOffset> for SourceSpan {
fn from(offset: SourceOffset) -> Self {
Self { offset, length: 0 }
}
}
impl From<ByteOffset> for SourceSpan {
fn from(offset: ByteOffset) -> Self {
Self {
offset: offset.into(),
length: 0,
}
}
}
#[cfg(feature = "serde")]
#[test]
fn test_serialize_source_span() {
use serde_json::json;
assert_eq!(
json!(SourceSpan::from(0)),
json!({ "offset": 0, "length": 0})
);
}
#[cfg(feature = "serde")]
#[test]
fn test_deserialize_source_span() {
use serde_json::json;
let span: SourceSpan = serde_json::from_value(json!({ "offset": 0, "length": 0})).unwrap();
assert_eq!(span, SourceSpan::from(0));
}
pub type ByteOffset = usize;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SourceOffset(ByteOffset);
impl SourceOffset {
pub const fn offset(&self) -> ByteOffset {
self.0
}
pub fn from_location(source: impl AsRef<str>, loc_line: usize, loc_col: usize) -> Self {
let mut line = 0usize;
let mut col = 0usize;
let mut offset = 0usize;
for char in source.as_ref().chars() {
if line + 1 >= loc_line && col + 1 >= loc_col {
break;
}
if char == '\n' {
col = 0;
line += 1;
} else {
col += 1;
}
offset += char.len_utf8();
}
SourceOffset(offset)
}
#[track_caller]
pub fn from_current_location() -> Result<(String, Self), MietteError> {
let loc = Location::caller();
Ok((
loc.file().into(),
fs::read_to_string(loc.file())
.map(|txt| Self::from_location(txt, loc.line() as usize, loc.column() as usize))?,
))
}
}
impl From<ByteOffset> for SourceOffset {
fn from(bytes: ByteOffset) -> Self {
SourceOffset(bytes)
}
}
#[test]
fn test_source_offset_from_location() {
let source = "f\n\noo\r\nbar";
assert_eq!(SourceOffset::from_location(source, 1, 1).offset(), 0);
assert_eq!(SourceOffset::from_location(source, 1, 2).offset(), 1);
assert_eq!(SourceOffset::from_location(source, 2, 1).offset(), 2);
assert_eq!(SourceOffset::from_location(source, 3, 1).offset(), 3);
assert_eq!(SourceOffset::from_location(source, 3, 2).offset(), 4);
assert_eq!(SourceOffset::from_location(source, 3, 3).offset(), 5);
assert_eq!(SourceOffset::from_location(source, 3, 4).offset(), 6);
assert_eq!(SourceOffset::from_location(source, 4, 1).offset(), 7);
assert_eq!(SourceOffset::from_location(source, 4, 2).offset(), 8);
assert_eq!(SourceOffset::from_location(source, 4, 3).offset(), 9);
assert_eq!(SourceOffset::from_location(source, 4, 4).offset(), 10);
assert_eq!(
SourceOffset::from_location(source, 5, 1).offset(),
source.len()
);
}
#[cfg(feature = "serde")]
#[test]
fn test_serialize_source_offset() {
use serde_json::json;
assert_eq!(json!(SourceOffset::from(0)), 0);
}
#[cfg(feature = "serde")]
#[test]
fn test_deserialize_source_offset() {
let offset: SourceOffset = serde_json::from_str("0").unwrap();
assert_eq!(offset, SourceOffset::from(0));
}