use super::document::{Document, DocumentStore};
use super::message::PublishDiagnosticsParams;
use super::types::*;
use std::sync::Arc;
use crate::diagnostics::check::check_buffer;
use crate::lexer::SourceFile;
const LEXER_DIAGNOSTIC_SOURCE: &str = "buildlang/lexer";
const PARSER_DIAGNOSTIC_SOURCE: &str = "buildlang/parser";
const TYPE_CHECKER_DIAGNOSTIC_SOURCE: &str = "buildlang/type-checker";
pub struct DiagnosticsProvider {
documents: Arc<DocumentStore>,
}
impl DiagnosticsProvider {
pub fn new(documents: Arc<DocumentStore>) -> Self {
Self { documents }
}
pub fn compute(&self, doc: &Document) -> PublishDiagnosticsParams {
let mut diagnostics = Vec::new();
self.check_syntax(&doc.content, &mut diagnostics);
self.check_brackets(&doc.content, doc, &mut diagnostics);
self.check_types(&doc.content, &mut diagnostics);
PublishDiagnosticsParams {
uri: doc.uri.clone(),
version: Some(doc.version),
diagnostics,
}
}
fn check_types(&self, content: &str, diagnostics: &mut Vec<Diagnostic>) {
let source_file = SourceFile::new("buffer", content.to_string());
for d in check_buffer(&source_file) {
diagnostics.push(to_lsp(d));
}
}
fn check_syntax(&self, content: &str, diagnostics: &mut Vec<Diagnostic>) {
for (line_num, line) in content.lines().enumerate() {
let line_num = line_num as u32;
let trimmed = line.trim();
if self.needs_semicolon(trimmed)
&& !trimmed.ends_with(';')
&& !trimmed.ends_with('{')
&& !trimmed.ends_with('}')
&& !trimmed.ends_with(',')
{
let col = line.len() as u32;
diagnostics.push(
Diagnostic::error(
Range::point(Position::new(line_num, col)),
"expected ';' at end of statement",
)
.with_code(1001),
);
}
if trimmed.contains(";;") {
if let Some(pos) = line.find(";;") {
diagnostics.push(
Diagnostic::warning(
Range::new(
Position::new(line_num, pos as u32),
Position::new(line_num, pos as u32 + 2),
),
"unnecessary double semicolon",
)
.with_tag(DiagnosticTag::Unnecessary),
);
}
}
if line.ends_with(' ') || line.ends_with('\t') {
let trimmed_len = line.trim_end().len() as u32;
diagnostics.push(
Diagnostic::hint(
Range::new(
Position::new(line_num, trimmed_len),
Position::new(line_num, line.len() as u32),
),
"trailing whitespace",
)
.with_tag(DiagnosticTag::Unnecessary),
);
}
}
}
fn needs_semicolon(&self, line: &str) -> bool {
let patterns = ["let ", "return ", "break", "continue", ") =", "= "];
for pattern in &patterns {
if line.contains(pattern) {
if !line.starts_with("fn ")
&& !line.starts_with("if ")
&& !line.starts_with("else")
&& !line.starts_with("match ")
&& !line.starts_with("for ")
&& !line.starts_with("while ")
&& !line.starts_with("loop")
&& !line.starts_with("//")
&& !line.starts_with("/*")
{
return true;
}
}
}
false
}
fn check_brackets(&self, content: &str, _doc: &Document, diagnostics: &mut Vec<Diagnostic>) {
let mut stack: Vec<(char, Position)> = Vec::new();
for (line_num, line) in content.lines().enumerate() {
let line_num = line_num as u32;
let mut in_string = false;
let mut in_char = false;
let mut escape_next = false;
for (col, c) in line.chars().enumerate() {
let col = col as u32;
if escape_next {
escape_next = false;
continue;
}
if c == '\\' {
escape_next = true;
continue;
}
if c == '"' && !in_char {
in_string = !in_string;
continue;
}
if c == '\'' && !in_string {
in_char = !in_char;
continue;
}
if in_string || in_char {
continue;
}
match c {
'(' | '[' | '{' => {
stack.push((c, Position::new(line_num, col)));
}
')' => {
if let Some((open, _)) = stack.pop() {
if open != '(' {
diagnostics.push(Diagnostic::error(
Range::point(Position::new(line_num, col)),
format!(
"mismatched bracket: expected closing for '{}', found ')'",
open
),
));
}
} else {
diagnostics.push(Diagnostic::error(
Range::point(Position::new(line_num, col)),
"unmatched closing parenthesis",
));
}
}
']' => {
if let Some((open, _)) = stack.pop() {
if open != '[' {
diagnostics.push(Diagnostic::error(
Range::point(Position::new(line_num, col)),
format!(
"mismatched bracket: expected closing for '{}', found ']'",
open
),
));
}
} else {
diagnostics.push(Diagnostic::error(
Range::point(Position::new(line_num, col)),
"unmatched closing bracket",
));
}
}
'}' => {
if let Some((open, _)) = stack.pop() {
if open != '{' {
diagnostics.push(Diagnostic::error(
Range::point(Position::new(line_num, col)),
format!(
"mismatched bracket: expected closing for '{}', found '}}'",
open
),
));
}
} else {
diagnostics.push(Diagnostic::error(
Range::point(Position::new(line_num, col)),
"unmatched closing brace",
));
}
}
_ => {}
}
}
}
for (open, pos) in stack {
let expected = match open {
'(' => ')',
'[' => ']',
'{' => '}',
_ => '?',
};
diagnostics.push(Diagnostic::error(
Range::point(pos),
format!("unclosed '{}', expected '{}'", open, expected),
));
}
}
fn check_common_issues(
&self,
content: &str,
_doc: &Document,
diagnostics: &mut Vec<Diagnostic>,
) {
for (line_num, line) in content.lines().enumerate() {
let line_num = line_num as u32;
let trimmed = line.trim();
for marker in &["TODO", "FIXME", "HACK", "XXX"] {
if let Some(pos) = line.to_uppercase().find(marker) {
if line[..pos].contains("//") || line[..pos].contains("/*") {
diagnostics.push(Diagnostic::hint(
Range::new(
Position::new(line_num, pos as u32),
Position::new(line_num, pos as u32 + marker.len() as u32),
),
format!("{} comment", marker),
));
}
}
}
if trimmed.contains("unwrap()") {
if let Some(pos) = line.find("unwrap()") {
diagnostics.push(Diagnostic::hint(
Range::new(
Position::new(line_num, pos as u32),
Position::new(line_num, pos as u32 + 8),
),
"consider using 'expect' or '?' instead of 'unwrap'",
));
}
}
if trimmed.contains("panic!(") && !self.is_in_test_function(content, line_num as usize)
{
if let Some(pos) = line.find("panic!(") {
diagnostics.push(Diagnostic::warning(
Range::new(
Position::new(line_num, pos as u32),
Position::new(line_num, pos as u32 + 7),
),
"consider using Result instead of panic!",
));
}
}
self.check_magic_numbers(line, line_num, diagnostics);
}
}
fn is_in_test_function(&self, content: &str, line_num: usize) -> bool {
let lines: Vec<&str> = content.lines().collect();
for i in (0..line_num).rev() {
let trimmed = lines[i].trim();
if trimmed.starts_with("fn ") {
if i > 0 && lines[i - 1].trim().contains("#[test]") {
return true;
}
return false;
}
}
false
}
fn check_magic_numbers(&self, line: &str, line_num: u32, diagnostics: &mut Vec<Diagnostic>) {
if line.trim().starts_with("//") {
return;
}
let allowed_numbers = ["0", "1", "2", "-1", "0.0", "1.0"];
let mut chars = line.chars().peekable();
let mut col = 0;
while let Some(c) = chars.next() {
if c.is_ascii_digit() {
let start = col;
let mut num_str = String::new();
num_str.push(c);
while let Some(&next) = chars.peek() {
if next.is_ascii_digit() || next == '.' || next == '_' {
num_str.push(chars.next().unwrap());
col += 1;
} else {
break;
}
}
let clean_num: String = num_str.chars().filter(|c| *c != '_').collect();
if !allowed_numbers.contains(&clean_num.as_str()) {
if let Ok(n) = clean_num.parse::<i64>() {
if n.abs() > 10 {
diagnostics.push(Diagnostic::hint(
Range::new(
Position::new(line_num, start as u32),
Position::new(line_num, col as u32 + 1),
),
"consider extracting magic number to a named constant",
));
}
}
}
}
col += 1;
}
}
fn check_unused_variables(
&self,
content: &str,
_doc: &Document,
diagnostics: &mut Vec<Diagnostic>,
) {
let mut declared_vars: Vec<(String, Position)> = Vec::new();
for (line_num, line) in content.lines().enumerate() {
let line_num = line_num as u32;
let trimmed = line.trim();
if let Some(rest) = trimmed
.strip_prefix("let ")
.or_else(|| trimmed.strip_prefix("let mut "))
{
let var_end = rest
.find(|c: char| c == ':' || c == '=' || c == ' ')
.unwrap_or(rest.len());
let var_name = rest[..var_end].trim().to_string();
if !var_name.starts_with('_') && !var_name.is_empty() {
if let Some(col) = line.find(&var_name) {
declared_vars.push((var_name, Position::new(line_num, col as u32)));
}
}
}
}
for (var_name, pos) in declared_vars {
let mut used = false;
let var_line = pos.line as usize;
for (line_num, line) in content.lines().enumerate() {
if line_num <= var_line {
continue;
}
let line_without_strings = remove_strings(line);
if contains_word(&line_without_strings, &var_name) {
used = true;
break;
}
}
if !used {
diagnostics.push(
Diagnostic::warning(
Range::new(
pos,
Position::new(pos.line, pos.character + var_name.len() as u32),
),
format!("unused variable: {}", var_name),
)
.with_tag(DiagnosticTag::Unnecessary)
.with_code(1002),
);
}
}
}
}
fn remove_strings(line: &str) -> String {
let mut result = String::new();
let mut in_string = false;
let mut escape_next = false;
for c in line.chars() {
if escape_next {
escape_next = false;
continue;
}
if c == '\\' {
escape_next = true;
continue;
}
if c == '"' {
in_string = !in_string;
continue;
}
if !in_string {
result.push(c);
}
}
result
}
fn contains_word(line: &str, word: &str) -> bool {
let bytes = line.as_bytes();
let word_bytes = word.as_bytes();
let mut i = 0;
while i <= bytes.len().saturating_sub(word_bytes.len()) {
if &bytes[i..i + word_bytes.len()] == word_bytes {
let before_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric() && bytes[i - 1] != b'_';
let after_ok = i + word_bytes.len() >= bytes.len()
|| (!bytes[i + word_bytes.len()].is_ascii_alphanumeric()
&& bytes[i + word_bytes.len()] != b'_');
if before_ok && after_ok {
return true;
}
}
i += 1;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_contains_word() {
assert!(contains_word("let x = foo;", "foo"));
assert!(!contains_word("let foobar = 1;", "foo"));
assert!(contains_word("foo + bar", "foo"));
assert!(contains_word("foo + bar", "bar"));
}
#[test]
fn test_remove_strings() {
assert_eq!(remove_strings(r#"let x = "hello";"#), "let x = ;");
assert_eq!(remove_strings(r#"let x = "foo\"bar";"#), "let x = ;");
}
#[test]
fn compiler_type_error_diagnostic_uses_type_checker_source() {
let documents = Arc::new(DocumentStore::new());
let provider = DiagnosticsProvider::new(documents.clone());
let doc = documents.open(TextDocumentItem {
uri: "file:///workspace/type_error.bld".to_string(),
language_id: "build".to_string(),
version: 1,
text: "const BAD: i32 = \"oops\";\nfn main() {}\n".to_string(),
});
let published = provider.compute(&doc);
assert!(
published.diagnostics.iter().any(|d| {
d.source.as_deref() == Some("buildlang/type-checker")
&& d.message.contains("type mismatch")
}),
"expected type-checker diagnostic in {:#?}",
published.diagnostics
);
}
}
pub(crate) fn to_lsp(d: crate::diagnostics::Diagnostic) -> Diagnostic {
let range = match &d.span {
Some(span) => Range {
start: Position {
line: span.line.saturating_sub(1) as u32,
character: span.column.saturating_sub(1) as u32,
},
end: Position {
line: span.end_line.saturating_sub(1) as u32,
character: span.end_column.saturating_sub(1) as u32,
},
},
None => Range {
start: Position {
line: 0,
character: 0,
},
end: Position {
line: 0,
character: 1,
},
},
};
let source = match &d.code[..4] {
"BL01" => LEXER_DIAGNOSTIC_SOURCE,
"BL02" => PARSER_DIAGNOSTIC_SOURCE,
_ => TYPE_CHECKER_DIAGNOSTIC_SOURCE,
};
let mut message = d.message;
for help in &d.help {
message.push_str("\n help: ");
message.push_str(help);
}
for note in &d.notes {
message.push_str("\n note: ");
message.push_str(note);
}
Diagnostic {
range,
severity: Some(DiagnosticSeverity::Error),
code: Some(DiagnosticCode::String(d.code.to_string())),
source: Some(source.to_string()),
message,
tags: Vec::new(),
related_information: Vec::new(),
}
}