gram-data 0.7.1

Unified gram CLI and library for validating gram notation
Documentation
//! Tagged strings whose tag does not touch the string.
//!
//! The documented forms are adjacent: `` tag`content` `` and a fence with the
//! tag directly after the backticks. The grammar is more permissive, because
//! extras (whitespace, comments) can float between tokens, so this rule flags
//! the loose forms instead of rejecting them at parse time.

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;
    };

    // (start, end) of the first gap found, plus a description of where it is.
    let mut gap: Option<(usize, usize, &str)> = None;

    if tag_idx == 0 {
        // `tag` followed by an opening backtick.
        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 {
        // Opening fence, then the tag, then a newline.
        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 {
            // Trailing blanks before the newline are harmless; a comment is not.
            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(),
            ),
        });
    }
}