use serde::Serialize;
use techy::error::Severity;
use techy::serialize::SerialValue;
use techy::source::LineIndexCache;
use crate::dump::json::{from_serde, to_json_pretty};
use crate::lang::origin::{FlmDiagnostic, FlmDiagnostics, FlmOrigin};
pub struct DiagExpect<'a> {
identifier: String,
candidates: Vec<&'a FlmDiagnostic>,
steps: Vec<String>,
}
pub fn expect<'a>(
diagnostics: impl IntoIterator<Item = &'a FlmDiagnostic>,
identifier: &str,
) -> DiagExpect<'a> {
let all: Vec<&'a FlmDiagnostic> = diagnostics.into_iter().collect();
let candidates: Vec<&'a FlmDiagnostic> =
all.iter().copied().filter(|diagnostic| diagnostic.identifier() == identifier).collect();
if candidates.is_empty() {
let present: Vec<&str> = all.iter().map(|diagnostic| diagnostic.identifier()).collect();
panic!(
"expected a diagnostic with the identifier `{identifier}`; the identifiers present \
are {present:?}"
);
}
DiagExpect { identifier: String::from(identifier), candidates, steps: Vec::new() }
}
pub trait ExpectDiag {
fn expect(&self, identifier: &str) -> DiagExpect<'_>;
fn expect_none(&self, identifier: &str);
}
impl ExpectDiag for FlmDiagnostics {
fn expect(&self, identifier: &str) -> DiagExpect<'_> {
expect(self.iter(), identifier)
}
fn expect_none(&self, identifier: &str) {
expect_none(self.iter(), identifier);
}
}
impl ExpectDiag for [FlmDiagnostic] {
fn expect(&self, identifier: &str) -> DiagExpect<'_> {
expect(self.iter(), identifier)
}
fn expect_none(&self, identifier: &str) {
expect_none(self.iter(), identifier);
}
}
impl ExpectDiag for Vec<FlmDiagnostic> {
fn expect(&self, identifier: &str) -> DiagExpect<'_> {
expect(self.iter(), identifier)
}
fn expect_none(&self, identifier: &str) {
expect_none(self.iter(), identifier);
}
}
pub fn expect_none<'a>(diagnostics: impl IntoIterator<Item = &'a FlmDiagnostic>, identifier: &str) {
let found: Vec<&'a FlmDiagnostic> = diagnostics
.into_iter()
.filter(|diagnostic| diagnostic.identifier() == identifier)
.collect();
if !found.is_empty() {
panic!(
"expected no diagnostic with the identifier `{identifier}`, found:\n{}",
describe(&found)
);
}
}
fn describe(diagnostics: &[&FlmDiagnostic]) -> String {
let mut lines = LineIndexCache::<FlmOrigin>::new();
diagnostics
.iter()
.map(|diagnostic| {
let span = diagnostic.span();
let position = match lines.line_col(span.source(), span.start()) {
Some((line, col)) => format!("{line}:{col}"),
None => format!("byte {}", span.start()),
};
let data = SerialValue::from(diagnostic.data().serializable_data());
format!(
" {} ({}) at {position} covering {:?}, {} traceback frame(s), data {}",
diagnostic.identifier(),
diagnostic.severity(),
span.content(),
diagnostic.frames().len(),
to_json_pretty(&data).unwrap_or_else(|_| format!("{data:?}"))
)
})
.collect::<Vec<_>>()
.join("\n")
}
impl<'a> DiagExpect<'a> {
pub fn identifier(&self) -> &str {
&self.identifier
}
pub fn diagnostics(&self) -> &[&'a FlmDiagnostic] {
&self.candidates
}
fn narrow(
mut self,
step: String,
mut keep: impl FnMut(&FlmDiagnostic) -> bool,
) -> DiagExpect<'a> {
let before = std::mem::take(&mut self.candidates);
self.candidates = before.iter().copied().filter(|diagnostic| keep(diagnostic)).collect();
if self.candidates.is_empty() {
panic!(
"no diagnostic with the identifier `{}` {}{}; the candidates were:\n{}",
self.identifier,
self.steps.iter().map(|step| format!("{step}, ")).collect::<String>(),
step,
describe(&before)
);
}
self.steps.push(step);
self
}
pub fn at(self, text: &str) -> DiagExpect<'a> {
let expected = String::from(text);
self.narrow(format!("covering {text:?}"), move |diagnostic| {
diagnostic.span().content() == expected
})
}
pub fn at_line_col(self, line: usize, col: usize) -> DiagExpect<'a> {
let mut lines = LineIndexCache::<FlmOrigin>::new();
self.narrow(format!("at {line}:{col}"), move |diagnostic| {
let span = diagnostic.span();
lines.line_col(span.source(), span.start()) == Some((line, col))
})
}
pub fn severity(self, severity: Severity) -> DiagExpect<'a> {
self.narrow(format!("of severity {severity}"), move |diagnostic| {
diagnostic.severity() == severity
})
}
pub fn frames(self, count: usize) -> DiagExpect<'a> {
self.narrow(format!("with {count} traceback frame(s)"), move |diagnostic| {
diagnostic.frames().len() == count
})
}
pub fn data<V: Serialize>(self, expected: V) -> DiagExpect<'a> {
let expected = from_serde(&expected).unwrap_or_else(|error| {
panic!("the expected data is not a serializable value: {error}")
});
let shown = to_json_pretty(&expected).unwrap_or_else(|_| format!("{expected:?}"));
let expected = canonical(expected);
self.narrow(format!("with data {shown}"), move |diagnostic| {
canonical(SerialValue::from(diagnostic.data().serializable_data())) == expected
})
}
pub fn count(self, count: usize) -> DiagExpect<'a> {
if self.candidates.len() != count {
panic!(
"expected {count} diagnostic(s) with the identifier `{}` {}, found {}:\n{}",
self.identifier,
self.steps.join(", "),
self.candidates.len(),
describe(&self.candidates)
);
}
self
}
pub fn once(self) -> &'a FlmDiagnostic {
self.count(1).candidates[0]
}
}
impl std::fmt::Debug for DiagExpect<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DiagExpect")
.field("identifier", &self.identifier)
.field("candidates", &self.candidates.len())
.field("steps", &self.steps)
.finish()
}
}
fn canonical(value: SerialValue) -> SerialValue {
match value {
SerialValue::List(items) => SerialValue::List(items.into_iter().map(canonical).collect()),
SerialValue::Map(entries) => {
let mut entries: Vec<(String, SerialValue)> =
entries.into_iter().map(|(key, value)| (key, canonical(value))).collect();
entries.sort_by(|a, b| a.0.cmp(&b.0));
SerialValue::Map(entries)
}
other => other,
}
}
#[cfg(test)]
mod tests {
use super::*;
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::source::{Source, SourceSpan};
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "test.two-fields", message = "{zeta} {alpha}")]
struct TwoFields {
zeta: String,
alpha: String,
}
fn diagnostic() -> FlmDiagnostic {
let source = std::sync::Arc::new(Source::new("x").with_origin(FlmOrigin::none()));
let condition = TwoFields { zeta: "z".into(), alpha: "a".into() };
Diagnostic::error(condition, SourceSpan::new(&source, 0..1))
}
#[test]
fn data_matches_a_map_whose_entries_are_in_another_order() {
let diagnostic = diagnostic();
expect([&diagnostic], "test.two-fields")
.data(serde_json::json!({ "alpha": "a", "zeta": "z" }))
.once();
}
#[test]
fn canonical_sorts_map_entries_recursively_and_keeps_list_order() {
let value = SerialValue::List(vec![
SerialValue::Map(vec![
("b".into(), SerialValue::Int(2)),
("a".into(), SerialValue::Map(vec![("y".into(), SerialValue::Null)])),
]),
SerialValue::Int(1),
]);
let expected = SerialValue::List(vec![
SerialValue::Map(vec![
("a".into(), SerialValue::Map(vec![("y".into(), SerialValue::Null)])),
("b".into(), SerialValue::Int(2)),
]),
SerialValue::Int(1),
]);
assert_eq!(canonical(value), expected);
}
}