use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::Any;
use core::fmt;
use crate::source::{
LineColProvider, LineIndexCache, Source, SourceOrigin, SourceProvenance, SourceSpan,
};
use crate::token::TokenErrorKind;
pub use techy_derive::{DiagnosticInfo, ToDiagnosticValue};
pub trait DiagnosticInfo: Any + Clone + fmt::Display + fmt::Debug + Send + Sync {
const IDENTIFIER: &'static str;
fn identifier(&self) -> &str {
Self::IDENTIFIER
}
fn serializable_data(&self) -> DiagnosticValue {
DiagnosticValue::empty_map()
}
}
mod sealed {
pub trait Sealed {}
}
impl<T: DiagnosticInfo> sealed::Sealed for T {}
pub trait DiagnosticData:
Any + fmt::Display + fmt::Debug + Send + Sync + sealed::Sealed
{
fn identifier(&self) -> &str;
fn serializable_data(&self) -> DiagnosticValue;
fn clone_box(&self) -> Box<dyn DiagnosticData>;
}
impl<T: DiagnosticInfo> DiagnosticData for T {
fn identifier(&self) -> &str {
DiagnosticInfo::identifier(self)
}
fn serializable_data(&self) -> DiagnosticValue {
DiagnosticInfo::serializable_data(self)
}
fn clone_box(&self) -> Box<dyn DiagnosticData> {
Box::new(self.clone())
}
}
impl dyn DiagnosticData {
pub fn is<T: DiagnosticInfo>(&self) -> bool {
(self as &dyn Any).is::<T>()
}
pub fn downcast_ref<T: DiagnosticInfo>(&self) -> Option<&T> {
(self as &dyn Any).downcast_ref::<T>()
}
}
impl Clone for Box<dyn DiagnosticData> {
fn clone(&self) -> Self {
self.clone_box()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiagnosticValue {
Null,
Bool(bool),
Int(i64),
Str(String),
List(Vec<DiagnosticValue>),
Map(Vec<(String, DiagnosticValue)>),
}
impl DiagnosticValue {
pub fn empty_map() -> DiagnosticValue {
DiagnosticValue::Map(Vec::new())
}
}
pub trait ToDiagnosticValue {
fn to_diagnostic_value(&self) -> DiagnosticValue;
}
impl ToDiagnosticValue for bool {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Bool(*self)
}
}
macro_rules! int_to_diagnostic_value {
($($t:ty),*) => {$(
impl ToDiagnosticValue for $t {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Int(i64::from(*self))
}
}
)*};
}
int_to_diagnostic_value!(i8, i16, i32, i64, u8, u16, u32);
macro_rules! saturating_int_to_diagnostic_value {
($($t:ty),*) => {$(
impl ToDiagnosticValue for $t {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Int(i64::try_from(*self).unwrap_or(i64::MAX))
}
}
)*};
}
saturating_int_to_diagnostic_value!(u64, usize);
impl ToDiagnosticValue for isize {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Int(*self as i64)
}
}
impl ToDiagnosticValue for char {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Str(String::from(*self))
}
}
impl ToDiagnosticValue for str {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Str(String::from(self))
}
}
impl ToDiagnosticValue for String {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Str(self.clone())
}
}
impl<T: ToDiagnosticValue> ToDiagnosticValue for Option<T> {
fn to_diagnostic_value(&self) -> DiagnosticValue {
match self {
Some(value) => value.to_diagnostic_value(),
None => DiagnosticValue::Null,
}
}
}
impl<T: ToDiagnosticValue> ToDiagnosticValue for [T] {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::List(self.iter().map(T::to_diagnostic_value).collect())
}
}
impl<T: ToDiagnosticValue> ToDiagnosticValue for Vec<T> {
fn to_diagnostic_value(&self) -> DiagnosticValue {
self.as_slice().to_diagnostic_value()
}
}
impl<T: ToDiagnosticValue + ?Sized> ToDiagnosticValue for &T {
fn to_diagnostic_value(&self) -> DiagnosticValue {
(**self).to_diagnostic_value()
}
}
impl ToDiagnosticValue for DiagnosticValue {
fn to_diagnostic_value(&self) -> DiagnosticValue {
self.clone()
}
}
impl ToDiagnosticValue for crate::source::ResolveError {
fn to_diagnostic_value(&self) -> DiagnosticValue {
let mut chain: Vec<DiagnosticValue> = Vec::new();
let mut cause = core::error::Error::source(self);
while let Some(error) = cause {
chain.push(DiagnosticValue::Str(error.to_string()));
cause = error.source();
}
DiagnosticValue::Map(alloc::vec![
("reference".to_string(), DiagnosticValue::Str(self.reference().to_string())),
("message".to_string(), DiagnosticValue::Str(self.message().to_string())),
("cause_chain".to_string(), DiagnosticValue::List(chain)),
])
}
}
impl ToDiagnosticValue for Arc<dyn core::error::Error + Send + Sync + 'static> {
fn to_diagnostic_value(&self) -> DiagnosticValue {
let mut chain: Vec<DiagnosticValue> = Vec::new();
chain.push(DiagnosticValue::Str(self.to_string()));
let mut cause = core::error::Error::source(&**self);
while let Some(error) = cause {
chain.push(DiagnosticValue::Str(error.to_string()));
cause = error.source();
}
DiagnosticValue::List(chain)
}
}
#[derive(Debug, Clone)]
pub struct TraceFrame<O: SourceOrigin = Option<String>> {
title: String,
span: SourceSpan<O>,
}
impl<O: SourceOrigin> TraceFrame<O> {
pub fn new(title: impl Into<String>, span: SourceSpan<O>) -> TraceFrame<O> {
TraceFrame { title: title.into(), span }
}
pub fn title(&self) -> &str {
&self.title
}
pub fn span(&self) -> &SourceSpan<O> {
&self.span
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
Note,
Warning,
Error,
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Severity::Note => "note",
Severity::Warning => "warning",
Severity::Error => "error",
})
}
}
#[derive(Debug, Clone)]
pub struct Diagnostic<O: SourceOrigin = Option<String>> {
severity: Severity,
data: Box<dyn DiagnosticData>,
span: SourceSpan<O>,
frames: Vec<TraceFrame<O>>,
}
impl<O: SourceOrigin> Diagnostic<O> {
pub fn new(
severity: Severity,
condition: impl DiagnosticInfo,
span: SourceSpan<O>,
) -> Self {
Diagnostic { severity, data: Box::new(condition), span, frames: Vec::new() }
}
pub fn error(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> Self {
Diagnostic::new(Severity::Error, condition, span)
}
pub fn warning(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> Self {
Diagnostic::new(Severity::Warning, condition, span)
}
pub fn note(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> Self {
Diagnostic::new(Severity::Note, condition, span)
}
pub(crate) fn from_parts(
severity: Severity,
data: Box<dyn DiagnosticData>,
span: SourceSpan<O>,
frames: Vec<TraceFrame<O>>,
) -> Self {
Diagnostic { severity, data, span, frames }
}
pub fn severity(&self) -> Severity {
self.severity
}
pub fn data(&self) -> &dyn DiagnosticData {
&*self.data
}
pub fn identifier(&self) -> &str {
self.data.identifier()
}
pub fn message(&self) -> String {
self.data.to_string()
}
pub fn span(&self) -> &SourceSpan<O> {
&self.span
}
pub fn frames(&self) -> &[TraceFrame<O>] {
&self.frames
}
pub fn render(&self) -> String {
self.render_with(&mut LineIndexCache::new())
}
pub fn render_with(&self, line_cols: &mut impl LineColProvider<O>) -> String {
render_report(line_cols, &self.to_string(), &self.span, &self.frames)
}
}
impl<O: SourceOrigin> fmt::Display for Diagnostic<O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.severity, self.data)
}
}
#[derive(Debug, Clone)]
pub struct Diagnostics<O: SourceOrigin = Option<String>> {
items: Vec<Diagnostic<O>>,
limit: usize,
suppressed: usize,
error_count: usize,
}
impl<O: SourceOrigin> Diagnostics<O> {
pub const DEFAULT_LIMIT: usize = 1000;
pub fn new() -> Self {
Diagnostics::with_limit(Diagnostics::<O>::DEFAULT_LIMIT)
}
pub fn with_limit(limit: usize) -> Self {
Diagnostics { items: Vec::new(), limit, suppressed: 0, error_count: 0 }
}
pub fn from_parts(
items: Vec<Diagnostic<O>>,
limit: usize,
suppressed: usize,
error_count: usize,
) -> Result<Self, InconsistentDiagnosticCounts> {
let retained_errors =
items.iter().filter(|diagnostic| diagnostic.severity == Severity::Error).count();
let consistent = items.len() <= limit
&& (suppressed == 0 || items.len() == limit)
&& retained_errors <= error_count
&& error_count <= retained_errors.saturating_add(suppressed);
if !consistent {
return Err(InconsistentDiagnosticCounts {
retained: items.len(),
retained_errors,
limit,
suppressed,
error_count,
});
}
Ok(Diagnostics { items, limit, suppressed, error_count })
}
pub fn push(&mut self, diagnostic: Diagnostic<O>) {
if diagnostic.severity == Severity::Error {
self.error_count += 1;
}
if self.items.len() < self.limit {
self.items.push(diagnostic);
} else {
self.suppressed += 1;
}
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty() && self.suppressed == 0
}
pub fn limit(&self) -> usize {
self.limit
}
pub fn suppressed(&self) -> usize {
self.suppressed
}
pub fn has_errors(&self) -> bool {
self.error_count > 0
}
pub fn error_count(&self) -> usize {
self.error_count
}
pub fn iter(&self) -> core::slice::Iter<'_, Diagnostic<O>> {
self.items.iter()
}
pub fn with_identifier<'a>(
&'a self,
identifier: &'a str,
) -> impl Iterator<Item = &'a Diagnostic<O>> {
self.items.iter().filter(move |d| d.identifier() == identifier)
}
pub fn conditions<T: DiagnosticInfo>(&self) -> impl Iterator<Item = &T> {
self.items.iter().filter_map(|d| d.data().downcast_ref::<T>())
}
pub fn as_slice(&self) -> &[Diagnostic<O>] {
&self.items
}
pub fn sorted_by_position(&self) -> Vec<&Diagnostic<O>> {
let mut sources: Vec<&Arc<Source<O>>> = Vec::new();
let mut keyed: Vec<(usize, usize, usize)> =
Vec::with_capacity(self.items.len());
for (arrival, diagnostic) in self.items.iter().enumerate() {
let source = diagnostic.span().source();
let source_index = sources
.iter()
.position(|known| Arc::ptr_eq(known, source))
.unwrap_or_else(|| {
sources.push(source);
sources.len() - 1
});
keyed.push((source_index, diagnostic.span().start(), arrival));
}
keyed.sort_unstable();
keyed.into_iter().map(|(_, _, arrival)| &self.items[arrival]).collect()
}
pub fn render_all(&self) -> String {
self.render_all_with(&mut LineIndexCache::new())
}
pub fn render_all_with(&self, line_cols: &mut impl LineColProvider<O>) -> String {
let mut out = String::new();
for (i, diagnostic) in self.items.iter().enumerate() {
if i > 0 {
out.push_str("\n\n");
}
out.push_str(&render_report(
line_cols,
&diagnostic.to_string(),
&diagnostic.span,
&diagnostic.frames,
));
}
if self.suppressed > 0 {
if !out.is_empty() {
out.push_str("\n\n");
}
out.push_str(&format!(
"… and {} more diagnostics (retention limit of {} reached)",
self.suppressed, self.limit,
));
}
out
}
}
impl<O: SourceOrigin> Default for Diagnostics<O> {
fn default() -> Self {
Diagnostics::new()
}
}
impl<O: SourceOrigin> IntoIterator for Diagnostics<O> {
type Item = Diagnostic<O>;
type IntoIter = alloc::vec::IntoIter<Diagnostic<O>>;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
impl<'a, O: SourceOrigin> IntoIterator for &'a Diagnostics<O> {
type Item = &'a Diagnostic<O>;
type IntoIter = core::slice::Iter<'a, Diagnostic<O>>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct InconsistentDiagnosticCounts {
pub retained: usize,
pub retained_errors: usize,
pub limit: usize,
pub suppressed: usize,
pub error_count: usize,
}
impl fmt::Display for InconsistentDiagnosticCounts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let InconsistentDiagnosticCounts {
retained,
retained_errors,
limit,
suppressed,
error_count,
} = *self;
write!(
f,
"the diagnostics collection's counts are inconsistent: {retained} diagnostic{} \
supplied ({retained_errors} of error severity) under a retention limit of \
{limit}, with {suppressed} suppressed and {error_count} error{} in all — ",
if retained == 1 { "" } else { "s" },
if error_count == 1 { "" } else { "s" },
)?;
if retained > limit {
write!(f, "more diagnostics were supplied than the retention limit allows")
} else if suppressed > 0 && retained != limit {
write!(
f,
"diagnostics were suppressed although the retention limit was not reached"
)
} else if retained_errors > error_count {
write!(f, "more of the supplied diagnostics are errors than were reported in all")
} else {
write!(
f,
"more errors were reported in all than the supplied errors plus the \
suppressed diagnostics can account for"
)
}
}
}
impl core::error::Error for InconsistentDiagnosticCounts {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Recovery {
Strict,
Tolerant,
}
#[derive(Debug, Clone)]
pub struct ParseError<O: SourceOrigin = Option<String>> {
data: Box<dyn DiagnosticData>,
span: SourceSpan<O>,
frames: Vec<TraceFrame<O>>,
}
impl<O: SourceOrigin> ParseError<O> {
pub fn new(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> ParseError<O> {
ParseError { data: Box::new(condition), span, frames: Vec::new() }
}
pub fn from_token_error(kind: TokenErrorKind, span: SourceSpan<O>) -> ParseError<O> {
ParseError { data: kind.into_condition(), span, frames: Vec::new() }
}
pub(crate) fn from_parts(
data: Box<dyn DiagnosticData>,
span: SourceSpan<O>,
frames: Vec<TraceFrame<O>>,
) -> ParseError<O> {
ParseError { data, span, frames }
}
pub fn with_frames(mut self, frames: Vec<TraceFrame<O>>) -> ParseError<O> {
self.frames = frames;
self
}
pub fn data(&self) -> &dyn DiagnosticData {
&*self.data
}
pub fn identifier(&self) -> &str {
self.data.identifier()
}
pub fn message(&self) -> String {
self.data.to_string()
}
pub fn span(&self) -> &SourceSpan<O> {
&self.span
}
pub fn frames(&self) -> &[TraceFrame<O>] {
&self.frames
}
pub fn render(&self) -> String {
self.render_with(&mut LineIndexCache::new())
}
pub fn render_with(&self, line_cols: &mut impl LineColProvider<O>) -> String {
render_report(line_cols, &format!("error: {}", self.data), &self.span, &self.frames)
}
}
impl<O: SourceOrigin> fmt::Display for ParseError<O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.data, f)
}
}
impl<O: SourceOrigin> core::error::Error for ParseError<O> {}
#[derive(Debug, Clone, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.hooks.hook-failed",
message = "extension hook reported a failure: {detail}"
)]
pub struct HookFailed {
pub detail: String,
pub cause: Option<Arc<dyn core::error::Error + Send + Sync + 'static>>,
}
impl HookFailed {
pub fn with_cause(
mut self,
cause: impl core::error::Error + Send + Sync + 'static,
) -> Self {
self.cause = Some(Arc::new(cause));
self
}
}
fn render_report<O: SourceOrigin>(
line_cols: &mut impl LineColProvider<O>,
headline: &str,
span: &SourceSpan<O>,
frames: &[TraceFrame<O>],
) -> String {
let mut msg = String::from(headline);
msg.push_str("\n at: ");
msg.push_str(&format_position_with(span, line_cols));
let traceback = format_traceback_with(frames, line_cols);
if !traceback.is_empty() {
msg.push('\n');
msg.push_str(&traceback);
}
for provenance in span.source().provenance_chain() {
match provenance {
SourceProvenance::Primary => {}
SourceProvenance::Resolved { reference, triggered_at } => {
msg.push_str(&format!(
"\n included from {} ({})",
format_position_with(triggered_at, line_cols),
reference,
));
}
SourceProvenance::Synthesized { description, triggered_at } => {
msg.push_str(&format!(
"\n synthesized from {} ({})",
format_position_with(triggered_at, line_cols),
description,
));
}
}
}
msg
}
pub fn format_position<O: SourceOrigin>(span: &SourceSpan<O>) -> String {
format_position_with(span, &mut LineIndexCache::new())
}
pub fn format_position_with<O: SourceOrigin>(
span: &SourceSpan<O>,
line_cols: &mut impl LineColProvider<O>,
) -> String {
let source = span.source();
let pos_str = match line_cols.line_col(source, span.start()) {
Some((line, col)) => format!("@ (line {}, col {})", line, col),
None => format!("@ char pos {} (no line info)", span.start()),
};
match source.origin().label() {
Some(label) => format!("{} [{}]", pos_str, label),
None => pos_str,
}
}
pub fn format_traceback<O: SourceOrigin>(frames: &[TraceFrame<O>]) -> String {
format_traceback_with(frames, &mut LineIndexCache::new())
}
pub fn format_traceback_with<O: SourceOrigin>(
frames: &[TraceFrame<O>],
line_cols: &mut impl LineColProvider<O>,
) -> String {
if frames.is_empty() {
return String::new();
}
let mut result = String::from("Open blocks:");
for frame in frames {
result.push_str("\n ");
result.push_str(&format_position_with(&frame.span, line_cols));
result.push_str(": ");
result.push_str(&frame.title);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::source::Source;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq)]
struct TestCondition {
detail: String,
}
impl TestCondition {
fn new(detail: &str) -> TestCondition {
TestCondition { detail: detail.to_string() }
}
}
impl fmt::Display for TestCondition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl DiagnosticInfo for TestCondition {
const IDENTIFIER: &'static str = "test.error.test-condition";
}
#[derive(Debug, Clone, PartialEq, Eq, crate::error::DiagnosticInfo)]
#[diagnostic(
id = "test.error.other-condition",
message = "other condition",
no_constructor
)]
struct OtherCondition;
#[derive(Debug, Clone)]
struct AdapterCondition {
identifier: String,
detail: String,
}
impl fmt::Display for AdapterCondition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl DiagnosticInfo for AdapterCondition {
const IDENTIFIER: &'static str = "test.error.adapter";
fn identifier(&self) -> &str {
&self.identifier
}
}
#[test]
fn an_adapter_condition_reports_its_per_instance_identifier() {
let source = arc_source("Hello");
let diagnostic = Diagnostic::error(
AdapterCondition {
identifier: "pylang.custom.my-condition".to_string(),
detail: "adapter-carried condition".to_string(),
},
SourceSpan::new(&source, 0..1),
);
assert_eq!(diagnostic.identifier(), "pylang.custom.my-condition");
assert_eq!(diagnostic.clone().identifier(), "pylang.custom.my-condition");
assert_eq!(AdapterCondition::IDENTIFIER, "test.error.adapter");
let condition = diagnostic.data().downcast_ref::<AdapterCondition>().unwrap();
assert_eq!(condition.detail, "adapter-carried condition");
}
#[test]
fn ordinary_conditions_still_answer_their_const_identifier() {
let ordinary = TestCondition::new("x");
assert_eq!(DiagnosticInfo::identifier(&ordinary), TestCondition::IDENTIFIER);
let source = arc_source("Hello");
let diagnostic =
Diagnostic::error(TestCondition::new("x"), SourceSpan::new(&source, 0..1));
assert_eq!(diagnostic.identifier(), TestCondition::IDENTIFIER);
}
fn origin(url: &str) -> Option<String> {
Some(url.to_string())
}
fn arc_source(content: &str) -> Arc<Source> {
Arc::new(Source::new(content))
}
#[test]
fn diagnostic_render_includes_line_info() {
let source = arc_source("Hello\n\\unknown\nworld");
let span = SourceSpan::new(&source, 6..14);
let diagnostic = Diagnostic::error(TestCondition::new("unknown macro"), span);
let rendered = diagnostic.render();
assert!(rendered.contains("error: unknown macro"));
assert!(rendered.contains("line 2"));
}
#[test]
fn sorted_by_position_is_source_major_span_start_minor_and_stable() {
let first = arc_source("first source content");
let second = arc_source("second source content");
let mut diagnostics: Diagnostics = Diagnostics::new();
for (source, range, tag) in [
(&first, 10..12, "f10"),
(&second, 5..6, "s5"),
(&first, 0..2, "f0"),
(&first, 10..11, "f10-later"), (&second, 0..1, "s0"),
] {
diagnostics.push(Diagnostic::error(
TestCondition::new(tag),
SourceSpan::new(source, range),
));
}
let tags: Vec<String> = diagnostics
.sorted_by_position()
.into_iter()
.map(|diagnostic| diagnostic.message())
.collect();
assert_eq!(tags, ["f0", "f10", "f10-later", "s0", "s5"]);
assert_eq!(diagnostics.iter().next().unwrap().message(), "f10");
}
#[test]
fn diagnostic_accessors() {
let source = arc_source("Hello\nWorld\nTest");
let span = SourceSpan::new(&source, 10..15);
let diagnostic = Diagnostic::error(TestCondition::new("test"), span);
assert_eq!(diagnostic.span().start(), 10);
assert_eq!(diagnostic.span().end(), 15);
assert_eq!(diagnostic.severity(), Severity::Error);
assert_eq!(diagnostic.message(), "test");
assert!(diagnostic.frames().is_empty());
assert_eq!(diagnostic.identifier(), TestCondition::IDENTIFIER);
assert!(diagnostic.data().is::<TestCondition>());
let condition = diagnostic.data().downcast_ref::<TestCondition>().unwrap();
assert_eq!(condition.detail, "test");
assert!(diagnostic.data().downcast_ref::<OtherCondition>().is_none());
}
#[test]
fn diagnostic_clone_preserves_the_payload() {
let source = arc_source("Hello");
let diagnostic =
Diagnostic::error(TestCondition::new("boom"), SourceSpan::new(&source, 0..1));
let clone = diagnostic.clone();
assert_eq!(clone.identifier(), TestCondition::IDENTIFIER);
assert_eq!(clone.data().downcast_ref::<TestCondition>().unwrap().detail, "boom");
}
#[test]
fn serializable_data_defaults_to_an_empty_map() {
let condition = TestCondition::new("x");
assert_eq!(
DiagnosticInfo::serializable_data(&condition),
DiagnosticValue::empty_map()
);
let data: Box<dyn DiagnosticData> = Box::new(condition);
assert_eq!(data.serializable_data(), DiagnosticValue::Map(Vec::new()));
}
#[test]
fn diagnostic_render_with_origin() {
let source: Arc<Source> = Arc::new(
Source::new("Hello\n\\unknown\nworld").with_origin(origin("test.tex")),
);
let span = SourceSpan::new(&source, 6..14);
let diagnostic = Diagnostic::error(TestCondition::new("unknown macro"), span);
let rendered = diagnostic.render();
assert!(rendered.contains("line 2"));
assert!(rendered.contains("[test.tex]"));
}
#[test]
fn diagnostic_render_walks_provenance_chain() {
let document: Arc<Source> = Arc::new(
Source::new(r"\input{main.tex}").with_origin(origin("document.tex")),
);
let main: Arc<Source> = Arc::new(Source::resolved(
"\\mycommand\n",
"main.tex",
SourceSpan::entire(&document),
));
let expanded: Arc<Source> = Arc::new(Source::synthesized(
"expansion text",
"macro expansion",
SourceSpan::new(&main, 0..10),
));
let diagnostic =
Diagnostic::error(TestCondition::new("boom"), SourceSpan::new(&expanded, 0..9));
let rendered = diagnostic.render();
assert!(rendered.contains("error: boom"));
assert!(rendered.contains("synthesized from"));
assert!(rendered.contains("(macro expansion)"));
assert!(rendered.contains("included from"));
assert!(rendered.contains("(main.tex)"));
assert!(rendered.contains("[document.tex]"));
}
#[test]
fn diagnostics_collection() {
let source = arc_source("Hello");
let mut diagnostics: Diagnostics = Diagnostics::new();
assert!(diagnostics.is_empty());
assert!(!diagnostics.has_errors());
diagnostics.push(Diagnostic::warning(
TestCondition::new("odd"),
SourceSpan::new(&source, 0..1),
));
assert!(!diagnostics.has_errors());
diagnostics.push(Diagnostic::error(
TestCondition::new("bad"),
SourceSpan::new(&source, 1..2),
));
assert_eq!(diagnostics.len(), 2);
assert!(diagnostics.has_errors());
let severities: Vec<Severity> = diagnostics.iter().map(|d| d.severity()).collect();
assert_eq!(severities, vec![Severity::Warning, Severity::Error]);
}
#[test]
fn diagnostics_identifier_filtering_and_typed_access() {
let source = arc_source("Hello");
let mut diagnostics: Diagnostics = Diagnostics::new();
diagnostics
.push(Diagnostic::error(TestCondition::new("a"), SourceSpan::new(&source, 0..1)));
diagnostics.push(Diagnostic::error(OtherCondition, SourceSpan::new(&source, 1..2)));
diagnostics
.push(Diagnostic::error(TestCondition::new("b"), SourceSpan::new(&source, 2..3)));
assert_eq!(diagnostics.with_identifier(TestCondition::IDENTIFIER).count(), 2);
assert_eq!(diagnostics.with_identifier(OtherCondition::IDENTIFIER).count(), 1);
assert_eq!(diagnostics.with_identifier("test.error.nope").count(), 0);
let details: Vec<&str> = diagnostics
.conditions::<TestCondition>()
.map(|c| c.detail.as_str())
.collect();
assert_eq!(details, ["a", "b"]);
}
#[test]
fn diagnostics_default_limit_applies() {
let diagnostics: Diagnostics = Diagnostics::new();
assert_eq!(diagnostics.limit(), Diagnostics::<Option<String>>::DEFAULT_LIMIT);
assert_eq!(diagnostics.suppressed(), 0);
}
#[test]
fn diagnostics_limit_counts_suppressed_pushes() {
let source = arc_source("abcd");
let mut diagnostics: Diagnostics = Diagnostics::with_limit(2);
for i in 0..4 {
diagnostics.push(Diagnostic::error(
TestCondition::new("boom"),
SourceSpan::new(&source, i..i + 1),
));
}
assert_eq!(diagnostics.len(), 2);
assert_eq!(diagnostics.suppressed(), 2);
assert!(!diagnostics.is_empty());
assert!(diagnostics.has_errors());
assert_eq!(diagnostics.iter().count(), 2);
let rendered = diagnostics.render_all();
assert!(rendered
.contains("… and 2 more diagnostics (retention limit of 2 reached)"));
}
#[test]
fn has_errors_sees_errors_beyond_the_limit() {
let source = arc_source("ab");
let mut diagnostics: Diagnostics = Diagnostics::with_limit(1);
diagnostics.push(Diagnostic::warning(
TestCondition::new("odd"),
SourceSpan::new(&source, 0..1),
));
assert!(!diagnostics.has_errors());
diagnostics.push(Diagnostic::error(
TestCondition::new("bad"),
SourceSpan::new(&source, 1..2),
));
assert_eq!(diagnostics.len(), 1);
assert!(diagnostics.has_errors());
}
#[test]
fn from_parts_restores_a_collection_whose_diagnostics_were_dropped() {
let source = arc_source("abcd");
let mut original: Diagnostics = Diagnostics::with_limit(2);
for i in 0..4 {
original.push(Diagnostic::error(
TestCondition::new("boom"),
SourceSpan::new(&source, i..i + 1),
));
}
let items: Vec<Diagnostic> = original.iter().cloned().collect();
let rebuilt = Diagnostics::from_parts(
items,
original.limit(),
original.suppressed(),
original.error_count(),
)
.unwrap();
assert_eq!(rebuilt.len(), original.len());
assert_eq!(rebuilt.limit(), 2);
assert_eq!(rebuilt.suppressed(), 2);
assert_eq!(rebuilt.error_count(), 4);
assert!(rebuilt.has_errors());
assert_eq!(rebuilt.render_all(), original.render_all());
}
#[test]
fn from_parts_rejects_counts_that_contradict_one_another() {
let source = arc_source("ab");
let items: Vec<Diagnostic> = vec![
Diagnostic::error(TestCondition::new("bad"), SourceSpan::new(&source, 0..1)),
Diagnostic::warning(TestCondition::new("odd"), SourceSpan::new(&source, 1..2)),
];
let refuse = |limit, suppressed, error_count| {
Diagnostics::from_parts(items.clone(), limit, suppressed, error_count).unwrap_err()
};
assert_eq!(
refuse(1, 0, 1),
InconsistentDiagnosticCounts {
retained: 2,
retained_errors: 1,
limit: 1,
suppressed: 0,
error_count: 1,
}
);
assert_eq!(
refuse(5, 1, 1),
InconsistentDiagnosticCounts {
retained: 2,
retained_errors: 1,
limit: 5,
suppressed: 1,
error_count: 1,
}
);
assert_eq!(
refuse(5, 0, 0),
InconsistentDiagnosticCounts {
retained: 2,
retained_errors: 1,
limit: 5,
suppressed: 0,
error_count: 0,
}
);
assert_eq!(
refuse(2, 1, 3),
InconsistentDiagnosticCounts {
retained: 2,
retained_errors: 1,
limit: 2,
suppressed: 1,
error_count: 3,
}
);
assert!(refuse(1, 0, 1).to_string().contains("more diagnostics were supplied"));
assert!(refuse(5, 1, 1).to_string().contains("although the retention limit was not"));
assert!(refuse(5, 0, 0).to_string().contains("are errors than were reported in all"));
assert!(refuse(2, 1, 3).to_string().contains("more errors were reported in all"));
let one = vec![Diagnostic::error(TestCondition::new("bad"), SourceSpan::new(&source, 0..1))];
let message = Diagnostics::from_parts(one, 0, 0, 1).unwrap_err().to_string();
assert!(message.contains("1 diagnostic supplied"), "{message}");
assert!(message.contains("1 error in all"), "{message}");
assert!(refuse(1, 0, 1).to_string().contains("2 diagnostics supplied"));
assert!(Diagnostics::from_parts(items, 2, 1, 2).is_ok());
}
#[test]
fn render_all_matches_the_per_diagnostic_renders() {
let document: Arc<Source> = Arc::new(
Source::new("Hello\n\\input{main.tex}").with_origin(origin("document.tex")),
);
let main: Arc<Source> = Arc::new(Source::resolved(
"\\bad\nmore\n",
"main.tex",
SourceSpan::new(&document, 6..22),
));
let mut diagnostics: Diagnostics = Diagnostics::new();
diagnostics.push(Diagnostic::error(
TestCondition::new("first"),
SourceSpan::new(&main, 0..4),
));
diagnostics.push(Diagnostic::warning(
TestCondition::new("second"),
SourceSpan::new(&main, 5..9),
));
diagnostics.push(Diagnostic::error(
TestCondition::new("third"),
SourceSpan::new(&document, 0..5),
));
let separate: Vec<String> = diagnostics.iter().map(|d| d.render()).collect();
assert_eq!(diagnostics.render_all(), separate.join("\n\n"));
assert!(!diagnostics.render_all().contains("… and"));
}
#[test]
fn format_traceback_single_frame() {
let source = arc_source("Hello\nWorld\nTest");
let frames =
vec![TraceFrame::new("environment ‘document’", SourceSpan::new(&source, 6..11))];
let traceback = format_traceback(&frames);
assert_eq!(traceback, "Open blocks:\n @ (line 2, col 1): environment ‘document’");
}
#[test]
fn format_traceback_multiple_frames_innermost_first() {
let source = arc_source("Hello\nWorld\nTest\nMore");
let frames = vec![
TraceFrame::new("callable ‘\\textbf’", SourceSpan::new(&source, 12..16)),
TraceFrame::new("environment ‘document’", SourceSpan::new(&source, 6..11)),
TraceFrame::new("callable ‘\\section’", SourceSpan::new(&source, 0..5)),
];
let traceback = format_traceback(&frames);
assert_eq!(
traceback,
"Open blocks:\n @ (line 3, col 1): callable ‘\\textbf’\n @ (line 2, col 1): environment ‘document’\n @ (line 1, col 1): callable ‘\\section’"
);
}
#[test]
fn format_traceback_empty_frames() {
let frames: Vec<TraceFrame> = vec![];
assert_eq!(format_traceback(&frames), "");
}
#[test]
fn format_traceback_with_origin() {
let source: Arc<Source> = Arc::new(
Source::new("Hello\nWorld\nTest").with_origin(origin("test.tex")),
);
let frames =
vec![TraceFrame::new("environment ‘document’", SourceSpan::new(&source, 6..11))];
let traceback = format_traceback(&frames);
assert_eq!(
traceback,
"Open blocks:\n @ (line 2, col 1) [test.tex]: environment ‘document’"
);
}
#[test]
fn render_appends_the_traceback() {
let source = arc_source("Hello\nWorld");
let diagnostic = Diagnostic::from_parts(
Severity::Error,
Box::new(TestCondition::new("boom")),
SourceSpan::new(&source, 6..7),
vec![TraceFrame::new("group ‘{’", SourceSpan::new(&source, 0..1))],
);
let rendered = diagnostic.render();
assert!(rendered.contains("error: boom"));
assert!(rendered.contains("Open blocks:\n @ (line 1, col 1): group ‘{’"));
}
#[test]
fn parse_error_carries_the_condition() {
let source = arc_source("Hello");
let err: ParseError =
ParseError::new(TestCondition::new("boom"), SourceSpan::new(&source, 0..2));
assert_eq!(err.identifier(), TestCondition::IDENTIFIER);
assert_eq!(err.message(), "boom");
assert_eq!(err.data().downcast_ref::<TestCondition>().unwrap().detail, "boom");
assert_eq!(err.to_string(), "boom");
assert!(err.frames().is_empty());
assert!(err.render().contains("error: boom"));
assert!(err.render().contains("line 1"));
}
#[derive(Debug)]
struct UnderlyingIo;
impl fmt::Display for UnderlyingIo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("disk unavailable")
}
}
impl core::error::Error for UnderlyingIo {}
#[derive(Debug)]
struct EmbeddingFailure {
source: UnderlyingIo,
}
impl fmt::Display for EmbeddingFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("embedding call failed")
}
}
impl core::error::Error for EmbeddingFailure {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
Some(&self.source)
}
}
#[test]
fn hook_failed_constructs_and_renders() {
let plain = HookFailed::new("state seed unavailable", None);
assert_eq!(HookFailed::IDENTIFIER, "core.hooks.hook-failed");
assert_eq!(DiagnosticInfo::identifier(&plain), HookFailed::IDENTIFIER);
assert_eq!(
plain.to_string(),
"extension hook reported a failure: state seed unavailable"
);
assert!(plain.cause.is_none());
let arc: Arc<dyn core::error::Error + Send + Sync> = Arc::new(UnderlyingIo);
let positional = HookFailed::new("boom", Some(arc));
assert_eq!(positional.cause.as_ref().unwrap().to_string(), "disk unavailable");
}
#[test]
fn hook_failed_cause_chain_is_reachable_through_a_parse_error() {
let source = arc_source("Hello");
let condition = HookFailed::new("embedding call failed", None)
.with_cause(EmbeddingFailure { source: UnderlyingIo });
let err: ParseError =
ParseError::new(condition, SourceSpan::new(&source, 0..1));
assert_eq!(err.identifier(), "core.hooks.hook-failed");
let condition = err.data().downcast_ref::<HookFailed>().unwrap();
let cause = condition.cause.as_ref().unwrap();
assert_eq!(cause.to_string(), "embedding call failed");
let hop = core::error::Error::source(&**cause).unwrap();
assert_eq!(hop.to_string(), "disk unavailable");
assert!(hop.source().is_none());
let clone = condition.clone();
assert!(Arc::ptr_eq(cause, clone.cause.as_ref().unwrap()));
}
#[test]
fn hook_failed_serializable_data_projects_the_cause_chain() {
let plain = HookFailed::new("boom", None);
assert_eq!(
DiagnosticInfo::serializable_data(&plain),
DiagnosticValue::Map(vec![
("detail".to_string(), DiagnosticValue::Str("boom".to_string())),
("cause".to_string(), DiagnosticValue::Null),
])
);
let chained =
HookFailed::new("boom", None).with_cause(EmbeddingFailure { source: UnderlyingIo });
assert_eq!(
DiagnosticInfo::serializable_data(&chained),
DiagnosticValue::Map(vec![
("detail".to_string(), DiagnosticValue::Str("boom".to_string())),
(
"cause".to_string(),
DiagnosticValue::List(vec![
DiagnosticValue::Str("embedding call failed".to_string()),
DiagnosticValue::Str("disk unavailable".to_string()),
])
),
])
);
}
#[test]
fn the_with_variants_match_their_transient_shorthands() {
let document: Arc<Source> = Arc::new(
Source::new("Hello\n\\input{main.tex}").with_origin(origin("document.tex")),
);
let main: Arc<Source> = Arc::new(Source::resolved(
"\\bad\nmore\n",
"main.tex",
SourceSpan::new(&document, 6..22),
));
let mut diagnostics: Diagnostics = Diagnostics::new();
diagnostics.push(Diagnostic::from_parts(
Severity::Error,
Box::new(TestCondition::new("boom")),
SourceSpan::new(&main, 0..4),
vec![TraceFrame::new("group ‘{’", SourceSpan::new(&document, 6..7))],
));
let error: ParseError =
ParseError::new(TestCondition::new("halt"), SourceSpan::new(&main, 5..9));
let mut cache = crate::source::LineIndexCache::new();
for _ in 0..2 {
assert_eq!(diagnostics.render_all_with(&mut cache), diagnostics.render_all());
let diagnostic = diagnostics.iter().next().unwrap();
assert_eq!(diagnostic.render_with(&mut cache), diagnostic.render());
assert_eq!(error.render_with(&mut cache), error.render());
assert_eq!(
format_position_with(diagnostic.span(), &mut cache),
format_position(diagnostic.span())
);
assert_eq!(
format_traceback_with(diagnostic.frames(), &mut cache),
format_traceback(diagnostic.frames())
);
}
}
#[test]
fn format_position_char_pos_fallback() {
let content = "a\n".repeat(DEFAULT_MAX_TEST_LEN);
let source = arc_source(&content);
let span = SourceSpan::new(&source, 42..43);
let formatted = format_position(&span);
assert_eq!(formatted, "@ char pos 42 (no line info)");
}
const DEFAULT_MAX_TEST_LEN: usize = 300_000;
#[derive(Debug, Clone, PartialEq, Eq, crate::error::DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "test.error.derived-condition", message = "derived: {detail}")]
struct DerivedCondition {
detail: String,
}
#[test]
fn derive_works_in_crate() {
let condition = DerivedCondition::new("boom");
assert_eq!(DerivedCondition::IDENTIFIER, "test.error.derived-condition");
assert_eq!(condition.to_string(), "derived: boom");
assert_eq!(
DiagnosticInfo::serializable_data(&condition),
DiagnosticValue::Map(vec![(
"detail".to_string(),
DiagnosticValue::Str("boom".to_string())
)])
);
}
}