use tree_sitter::Node;
use crate::analyze::{Diagnostic, DiagnosticSeverity};
pub fn tag_gap_diagnostics(root: Node, source: &[u8]) -> Vec<Diagnostic> {
let mut out = Vec::new();
walk(root, source, &mut out);
out
}
fn walk(node: Node, source: &[u8], out: &mut Vec<Diagnostic>) {
if node.kind() == "tagged_string" {
check(node, source, out);
}
let mut c = node.walk();
for child in node.children(&mut c) {
walk(child, source, out);
}
}
fn check(node: Node, _source: &[u8], out: &mut Vec<Diagnostic>) {
let Some(tag) = node.child_by_field_name("tag") else {
return;
};
let mut c = node.walk();
let children: Vec<Node> = node.children(&mut c).collect();
let Some(tag_idx) = children.iter().position(|n| n.id() == tag.id()) else {
return;
};
let mut gap: Option<(usize, usize, &str)> = None;
if tag_idx == 0 {
if let Some(open) = children[tag_idx + 1..].iter().find(|n| n.kind() == "`") {
if open.start_byte() > tag.end_byte() {
gap = Some((tag.end_byte(), open.start_byte(), "between the tag and the string"));
}
}
} else {
let fence = &children[tag_idx - 1];
if tag.start_byte() > fence.end_byte() {
gap = Some((fence.end_byte(), tag.start_byte(), "between the fence and the tag"));
} else {
let comments: Vec<&Node> = children[tag_idx + 1..]
.iter()
.take_while(|n| matches!(n.kind(), "comment" | "doc_comment"))
.collect();
if let Some(last) = comments.last() {
gap = Some((tag.end_byte(), last.end_byte(), "after the tag"));
}
}
}
if let Some((start, end, place)) = gap {
out.push(Diagnostic {
start_byte: start,
end_byte: end,
message: format!("whitespace or comment {place} of a tagged string"),
severity: DiagnosticSeverity::Warning,
code: Some("tagged-string-gap".into()),
help: Some(
"write the tag adjacent to the string: tag`content`, or ```tag on the fence line"
.into(),
),
});
}
}