pub mod check;
pub mod codes;
use serde::Serialize;
use crate::lexer::{LexerError, SourceFile, Span};
use crate::parser::ParseError;
use crate::types::TypeErrorWithSpan;
pub const SCHEMA_ID: &str = "buildlang.diagnostics/v1";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Applicability {
MachineApplicable,
MaybeIncorrect,
HasPlaceholders,
Unspecified,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEdit {
pub span: Span,
pub replacement: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fix {
pub message: String,
pub edits: Vec<TextEdit>,
pub machine_applicable: bool,
}
impl Fix {
pub fn insert(
message: impl Into<String>,
at: Span,
text: impl Into<String>,
exact: bool,
) -> Self {
let point = Span::new(at.start, at.start, at.source_id);
Self {
message: message.into(),
edits: vec![TextEdit {
span: point,
replacement: text.into(),
}],
machine_applicable: exact,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SuggestionEdit {
pub span: DiagnosticSpan,
pub replacement: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Suggestion {
pub message: String,
pub applicability: Applicability,
pub widens_authority: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub edits: Vec<SuggestionEdit>,
}
impl Suggestion {
pub fn new(message: impl Into<String>, applicability: Applicability, widens: bool) -> Self {
let applicability = if widens && applicability == Applicability::MachineApplicable {
Applicability::MaybeIncorrect
} else {
applicability
};
Self {
message: message.into(),
applicability,
widens_authority: widens,
edits: Vec::new(),
}
}
pub fn from_fix(code: &str, fix: &Fix, file: &SourceFile) -> Self {
let widens = suggestion_widens_authority(code, &fix.message)
|| fix
.edits
.iter()
.any(|e| suggestion_widens_authority(code, &e.replacement));
let edits: Option<Vec<SuggestionEdit>> = fix
.edits
.iter()
.map(|e| {
resolve_point_or_range(e.span, file).map(|span| SuggestionEdit {
span,
replacement: e.replacement.clone(),
})
})
.collect();
let applicability = match (&edits, fix.machine_applicable) {
(Some(_), true) => Applicability::MachineApplicable,
(Some(_), false) => Applicability::MaybeIncorrect,
(None, _) => Applicability::Unspecified,
};
let mut s = Self::new(fix.message.clone(), applicability, widens);
s.edits = edits.unwrap_or_default();
s
}
pub fn from_text(code: &str, text: &str) -> Self {
let widens = suggestion_widens_authority(code, text);
let applicability = if widens {
Applicability::MaybeIncorrect
} else if text.contains("...") || text.contains('<') {
Applicability::HasPlaceholders
} else {
Applicability::Unspecified
};
Self::new(text, applicability, widens)
}
}
pub fn suggestion_widens_authority(code: &str, text: &str) -> bool {
matches!(code, "BL0401" | "BL0402" | "BL0403" | "BL0382")
|| text.contains("unsafe")
|| text.contains("~ ")
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DiagnosticSpan {
pub line: usize,
pub column: usize,
pub end_line: usize,
pub end_column: usize,
pub byte_start: u32,
pub byte_end: u32,
}
impl DiagnosticSpan {
pub fn resolve(span: Span, file: &SourceFile) -> Option<Self> {
if span.end.0 == 0 && span.start.0 == 0 {
return None;
}
let (line, column) = line_col(file, span.start);
let end = span.end.max(span.start);
let (end_line, end_column) = line_col(file, end);
Some(Self {
line,
column,
end_line,
end_column,
byte_start: span.start.0,
byte_end: end.0,
})
}
}
fn resolve_point_or_range(span: Span, file: &SourceFile) -> Option<DiagnosticSpan> {
if span.source_id != file.id || span.end.0 as usize > file.source().len() {
return None;
}
let (line, column) = line_col(file, span.start);
let end = span.end.max(span.start);
let (end_line, end_column) = line_col(file, end);
Some(DiagnosticSpan {
line,
column,
end_line,
end_column,
byte_start: span.start.0,
byte_end: end.0,
})
}
fn line_col(file: &SourceFile, pos: crate::lexer::BytePos) -> (usize, usize) {
let line = file.lookup_line(pos);
let start = file.line_start(line).unwrap_or(pos);
(line + 1, pos.0.saturating_sub(start.0) as usize + 1)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Error,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Diagnostic {
pub code: &'static str,
pub severity: Severity,
pub message: String,
pub file: String,
pub span: Option<DiagnosticSpan>,
pub help: Vec<String>,
pub notes: Vec<String>,
pub suggestions: Vec<Suggestion>,
}
impl Diagnostic {
pub fn bare(code: &'static str, file: &str, message: impl Into<String>) -> Self {
Self {
code,
severity: Severity::Error,
message: message.into(),
file: file.to_string(),
span: None,
help: Vec::new(),
notes: Vec::new(),
suggestions: Vec::new(),
}
}
fn with_advice(
mut self,
explicit_help: Option<&str>,
suggestion: Option<&str>,
fix: Option<&Fix>,
) -> Self {
for text in help_lines_with_fix(explicit_help, suggestion, fix) {
self.suggestions
.push(Suggestion::from_text(self.code, &text));
self.help.push(text);
}
self
}
fn with_fix(mut self, fix: Option<&Fix>, file: &SourceFile) -> Self {
if let Some(fix) = fix {
let exact = Suggestion::from_fix(self.code, fix, file);
if exact.edits.is_empty() {
return self;
}
self.suggestions.retain(|s| s.message != exact.message);
self.suggestions.insert(0, exact);
}
self
}
pub fn from_lexer(err: &LexerError, file: &SourceFile) -> Self {
let code = codes::lexer_code(&err.kind);
let mut d = Self::bare(code, file.name(), err.message());
d.span = DiagnosticSpan::resolve(err.span, file);
d.with_advice(err.help.as_deref(), err.kind.help(), None)
}
pub fn from_parse(err: &ParseError, file: &SourceFile) -> Self {
let code = codes::parse_code(&err.kind);
let mut d = Self::bare(code, file.name(), err.message());
d.span = DiagnosticSpan::resolve(err.span, file);
d.notes = err.notes.clone();
d.with_advice(err.help.as_deref(), err.kind.suggestion(), err.fix.as_ref())
.with_fix(err.fix.as_ref(), file)
}
pub fn from_type(err: &TypeErrorWithSpan, file: &SourceFile) -> Self {
let code = codes::type_code(&err.error);
let mut d = Self::bare(code, file.name(), err.error.to_string());
d.span = DiagnosticSpan::resolve(err.span, file);
d.notes = err.notes.clone();
let suggestion = err.error.suggestion();
d.with_advice(err.help.as_deref(), suggestion.as_deref(), err.fix.as_ref())
.with_fix(err.fix.as_ref(), file)
}
}
pub fn help_lines(explicit: Option<&str>, suggestion: Option<&str>) -> Vec<String> {
let mut out = Vec::new();
if let Some(h) = explicit {
out.push(h.to_string());
}
if let Some(s) = suggestion {
if explicit != Some(s) {
out.push(s.to_string());
}
}
out
}
pub fn help_lines_with_fix(
explicit: Option<&str>,
suggestion: Option<&str>,
fix: Option<&Fix>,
) -> Vec<String> {
let mut out = help_lines(explicit, suggestion);
if let Some(fix) = fix {
if !out.iter().any(|h| h == &fix.message) {
out.push(fix.message.clone());
}
}
out
}
#[derive(Debug, Clone, Serialize)]
pub struct Report {
pub schema: &'static str,
pub compiler_version: &'static str,
pub file: String,
pub ok: bool,
pub error_count: usize,
pub diagnostics: Vec<Diagnostic>,
}
impl Report {
pub fn new(file: impl Into<String>, diagnostics: Vec<Diagnostic>) -> Self {
Self {
schema: SCHEMA_ID,
compiler_version: crate::VERSION,
file: file.into(),
ok: diagnostics.is_empty(),
error_count: diagnostics.len(),
diagnostics,
}
}
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).expect("diagnostic report serializes")
}
}
#[cfg(test)]
mod tests;