use crate::span::{SourceMap, Span};
use serde::Serialize;
use std::fmt::Write as _;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticKind {
Error,
Warning,
Unchecked,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Fix {
pub span: Span,
pub replacement: String,
}
#[derive(Clone, Debug)]
pub struct Diagnostic {
pub id: String,
pub code: &'static str,
pub kind: DiagnosticKind,
pub span: Span,
pub message: String,
pub notes: Vec<String>,
pub fix: Option<Fix>,
pub callers: Vec<Span>,
}
#[derive(Debug, Default)]
pub struct Report {
pub templates: usize,
pub diagnostics: Vec<Diagnostic>,
pub php_calls: Vec<(Span, String)>,
}
impl Report {
pub fn is_clean(&self) -> bool {
!self
.diagnostics
.iter()
.any(|d| d.kind == DiagnosticKind::Error)
}
pub fn assert_clean(&self, sources: &SourceMap) {
assert!(self.is_clean(), "{}", self.render(sources));
}
pub(super) fn add(
&mut self,
sources: &SourceMap,
kind: DiagnosticKind,
code: &'static str,
span: Span,
message: String,
) -> usize {
if let Some(index) = self
.diagnostics
.iter()
.position(|d| d.code == code && d.span == span && d.message == message)
{
return index;
}
let name = sources.location(span).map_or("<unknown>", |loc| loc.name);
let source = sources.source(span.file).unwrap_or_default();
let fragment = span.slice(source).unwrap_or_default();
let before = source.get(..span.start as usize).unwrap_or_default();
let after = source.get(span.start as usize..).unwrap_or_default();
let prefix = before.rsplit(['\n', '\r']).next().unwrap_or_default();
let suffix = after.split(['\n', '\r']).next().unwrap_or_default();
let line = format!("{prefix}{suffix}");
let column = prefix
.len()
.saturating_sub(line.len() - line.trim_start().len());
let ordinal = before[..before.len() - prefix.len()]
.lines()
.filter(|other| other.trim() == line.trim())
.count();
let mut hash = 0xcbf29ce484222325_u64;
for byte in format!(
"{name}\0{code}\0{}\0{column}\0{fragment}\0{ordinal}\0{message}",
line.trim()
)
.bytes()
{
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
}
let id = format!("{code}-{hash:016x}");
self.diagnostics.push(Diagnostic {
id,
code,
kind,
span,
message,
notes: Vec::new(),
fix: None,
callers: Vec::new(),
});
self.diagnostics.len() - 1
}
pub fn render(&self, sources: &SourceMap) -> String {
let mut output = String::new();
for d in &self.diagnostics {
let kind = match d.kind {
DiagnosticKind::Error => "error",
DiagnosticKind::Warning => "warning",
DiagnosticKind::Unchecked => "unchecked",
};
let _ = writeln!(output, "{kind}[{}]: {}", d.id, d.message);
if let Some(loc) = sources.location(d.span) {
let _ = writeln!(output, " --> {}:{}:{}", loc.name, loc.line, loc.column);
let source = sources.source(d.span.file).unwrap_or_default();
if let Some(before) = source.get(..d.span.start as usize)
&& let Some(after) = source.get(d.span.start as usize..)
{
let prefix = before.rsplit(['\n', '\r']).next().unwrap_or_default();
let suffix = after.split(['\n', '\r']).next().unwrap_or_default();
let width = d
.span
.slice(source)
.unwrap_or_default()
.split(['\n', '\r'])
.next()
.unwrap_or_default()
.chars()
.count()
.max(1);
let indentation: String = prefix
.chars()
.map(|c| if c == '\t' { '\t' } else { ' ' })
.collect();
let _ = writeln!(
output,
" |\n{} | {prefix}{suffix}\n | {indentation}{}",
loc.line,
"^".repeat(width)
);
}
}
for note in &d.notes {
let _ = writeln!(output, " = note: {note}");
}
for &caller in &d.callers {
if let Some(loc) = sources.location(caller) {
let _ = writeln!(
output,
" = called from {}:{}:{}",
loc.name, loc.line, loc.column
);
}
}
if let Some(fix) = &d.fix {
let _ = writeln!(output, " = help: use `{}`", fix.replacement);
}
}
let counts = self
.diagnostics
.iter()
.fold([0; 3], |mut counts, diagnostic| {
let at = match diagnostic.kind {
DiagnosticKind::Error => 0,
DiagnosticKind::Warning => 1,
DiagnosticKind::Unchecked => 2,
};
counts[at] += 1;
counts
});
let [errors, warnings, unchecked] = counts;
if !self.diagnostics.is_empty() {
let _ = writeln!(
output,
"{errors} errors, {warnings} warnings, {unchecked} unchecked across {} templates",
self.templates
);
}
output
}
pub fn to_json(&self, sources: &SourceMap) -> serde_json::Value {
use serde_json::json;
let span = |span: Span| {
let loc = sources.location(span);
json!({
"file": loc.map(|loc| loc.name), "line": loc.map(|loc| loc.line),
"column": loc.map(|loc| loc.column), "start": span.start, "end": span.end,
})
};
json!({
"templates": self.templates,
"diagnostics": self.diagnostics.iter().map(|d| json!({
"id": d.id, "code": d.code, "kind": d.kind, "message": d.message, "location": span(d.span),
"notes": d.notes, "callers": d.callers.iter().copied().map(span).collect::<Vec<_>>(),
"fix": d.fix.as_ref().map(|fix| json!({"location": span(fix.span), "replacement": fix.replacement})),
})).collect::<Vec<_>>(),
"php_calls": self.php_calls.iter().map(|(at, name)| json!({"name": name, "location": span(*at)})).collect::<Vec<_>>(),
})
}
}