This commit is contained in:
2026-03-24 13:40:27 +00:00
parent 8c02f505d0
commit 836b280998
10 changed files with 268 additions and 238 deletions
@@ -3,30 +3,30 @@ use crate::common::spans::Span;
use serde::{Serialize, Serializer};
#[derive(Debug, Clone, PartialEq)]
pub enum DiagnosticLevel {
pub enum Severity {
Error,
Warning,
}
impl Serialize for DiagnosticLevel {
impl Serialize for Severity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
DiagnosticLevel::Error => serializer.serialize_str("error"),
DiagnosticLevel::Warning => serializer.serialize_str("warning"),
Severity::Error => serializer.serialize_str("error"),
Severity::Warning => serializer.serialize_str("warning"),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Diagnostic {
#[serde(rename = "severity")]
pub level: DiagnosticLevel,
pub code: Option<String>,
pub severity: Severity,
pub code: String,
pub message: String,
pub span: Option<Span>,
pub span: Span,
pub related: Vec<(String, Span)>,
}
#[derive(Debug, Clone, Serialize)]
@@ -45,13 +45,14 @@ impl DiagnosticBundle {
self.diagnostics.push(diagnostic);
}
pub fn error(message: String, span: Option<Span>) -> Self {
pub fn error(code: &str, message: String, span: Span) -> Self {
let mut bundle = Self::new();
bundle.push(Diagnostic {
level: DiagnosticLevel::Error,
code: None,
severity: Severity::Error,
code: code.to_string(),
message,
span,
related: Vec::new(),
});
bundle
}
@@ -59,10 +60,11 @@ impl DiagnosticBundle {
pub fn has_errors(&self) -> bool {
self.diagnostics
.iter()
.any(|d| matches!(d.level, DiagnosticLevel::Error))
.any(|d| matches!(d.severity, Severity::Error))
}
/// Serializes the diagnostic bundle to canonical JSON, resolving file IDs via FileManager.
/// The output is deterministic: diagnostics are sorted by (file_id, start, end, code).
pub fn to_json(&self, file_manager: &FileManager) -> String {
#[derive(Serialize)]
struct CanonicalSpan {
@@ -73,30 +75,67 @@ impl DiagnosticBundle {
#[derive(Serialize)]
struct CanonicalDiag {
severity: DiagnosticLevel,
severity: Severity,
code: String,
message: String,
span: Option<CanonicalSpan>,
span: CanonicalSpan,
related: Vec<(String, CanonicalSpan)>,
}
let canonical_diags: Vec<CanonicalDiag> = self.diagnostics.iter().map(|d| {
let canonical_span = d.span.and_then(|s| {
file_manager.get_path(s.file_id).map(|p| {
CanonicalSpan {
file: p.file_name().unwrap().to_string_lossy().to_string(),
start: s.start,
end: s.end,
}
})
});
let mut diags = self.diagnostics.clone();
diags.sort_by(|a, b| {
(a.span.file_id, a.span.start, a.span.end, &a.code)
.cmp(&(b.span.file_id, b.span.start, b.span.end, &b.code))
});
CanonicalDiag {
severity: d.level.clone(),
code: d.code.clone().unwrap_or_else(|| "E_UNKNOWN".to_string()),
message: d.message.clone(),
span: canonical_span,
}
}).collect();
let canonical_diags: Vec<CanonicalDiag> = diags
.iter()
.map(|d| {
let s = d.span;
let file = if s.file_id == usize::MAX {
"<virtual>".to_string()
} else {
file_manager
.get_path(s.file_id)
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
.unwrap_or_else(|| format!("file_{}", s.file_id))
};
let canonical_span = CanonicalSpan {
file,
start: s.start,
end: s.end,
};
let related = d
.related
.iter()
.map(|(msg, sp)| {
let file = if sp.file_id == usize::MAX {
"<virtual>".to_string()
} else {
file_manager
.get_path(sp.file_id)
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
.unwrap_or_else(|| format!("file_{}", sp.file_id))
};
let rsp = CanonicalSpan {
file,
start: sp.start,
end: sp.end,
};
(msg.clone(), rsp)
})
.collect();
CanonicalDiag {
severity: d.severity.clone(),
code: d.code.clone(),
message: d.message.clone(),
span: canonical_span,
related,
}
})
.collect();
serde_json::to_string_pretty(&canonical_diags).unwrap()
}
@@ -109,66 +148,3 @@ impl From<Diagnostic> for DiagnosticBundle {
bundle
}
}
#[cfg(test)]
mod tests {
use crate::common::files::FileManager;
use crate::frontends::pbs::PbsFrontend;
use crate::frontends::Frontend;
use std::fs;
use tempfile::tempdir;
fn get_diagnostics(code: &str) -> String {
let mut file_manager = FileManager::new();
let temp_dir = tempdir().unwrap();
let file_path = temp_dir.path().join("main.pbs");
fs::write(&file_path, code).unwrap();
let frontend = PbsFrontend;
match frontend.compile_to_ir(&file_path, &mut file_manager) {
Ok(_) => "[]".to_string(),
Err(bundle) => bundle.to_json(&file_manager),
}
}
#[test]
fn test_golden_parse_error() {
let code = "fn main() { let x = ; }";
let json = get_diagnostics(code);
assert!(json.contains("E_PARSE_UNEXPECTED_TOKEN"));
assert!(json.contains("Expected expression"));
}
#[test]
fn test_golden_lex_error() {
let code = "fn main() { let x = \"hello ; }";
let json = get_diagnostics(code);
assert!(json.contains("E_LEX_UNTERMINATED_STRING"));
}
#[test]
fn test_golden_resolve_error() {
let code = "fn main() { let x = undefined_var; }";
let json = get_diagnostics(code);
assert!(json.contains("E_RESOLVE_UNDEFINED"));
}
#[test]
fn test_golden_type_error() {
let code = "fn main() { let x: int = \"hello\"; }";
let json = get_diagnostics(code);
assert!(json.contains("E_TYPE_MISMATCH"));
}
#[test]
fn test_golden_namespace_collision() {
let code = "
declare struct Foo {}
fn main() {
let Foo = 1;
}
";
let json = get_diagnostics(code);
assert!(json.contains("E_RESOLVE_NAMESPACE_COLLISION"));
}
}