Skip to main content

gram_data/
markdown.rs

1use crate::analyze;
2use crate::lint::LintOptions;
3use gram_diagnostics::Diagnostic;
4
5pub struct Snippet {
6    /// The extracted gram source text (fence delimiters excluded).
7    pub source: String,
8    /// 0-based line number of the opening fence (` ```gram `) in the host document.
9    pub fence_start_line: usize,
10}
11
12/// Extract all ` ```gram ` fenced blocks from a Markdown document.
13pub fn extract_snippets(doc_source: &str) -> Vec<Snippet> {
14    let mut snippets = Vec::new();
15    let mut in_fence = false;
16    let mut fence_start = 0usize;
17    let mut buf = String::new();
18
19    for (line_no, line) in doc_source.lines().enumerate() {
20        let trimmed = line.trim();
21        if !in_fence {
22            // Opening fence: ```gram or ```gram followed by optional whitespace
23            if is_gram_fence_open(trimmed) {
24                in_fence = true;
25                fence_start = line_no;
26                buf.clear();
27            }
28        } else {
29            // Closing fence: a line of only backticks (3+)
30            if is_fence_close(trimmed) {
31                snippets.push(Snippet {
32                    source: buf.clone(),
33                    fence_start_line: fence_start,
34                });
35                in_fence = false;
36            } else {
37                buf.push_str(line);
38                buf.push('\n');
39            }
40        }
41    }
42    snippets
43}
44
45/// Lint all ` ```gram ` snippets in a Markdown document.
46///
47/// Returns one `(Snippet, diagnostics)` pair per fenced block. Diagnostic ranges
48/// are relative to the snippet source. To map back to host-document line numbers
49/// add `snippet.fence_start_line + 1` to each diagnostic's line values.
50pub fn lint_markdown(doc_source: &str, _opts: &LintOptions) -> Vec<(Snippet, Vec<Diagnostic>)> {
51    extract_snippets(doc_source)
52        .into_iter()
53        .map(|snippet| {
54            let (_, raw) = analyze::analyze_source(&snippet.source);
55            let diags = raw
56                .iter()
57                .map(|d| analyze::to_public(&snippet.source, d))
58                .collect();
59            (snippet, diags)
60        })
61        .collect()
62}
63
64fn is_gram_fence_open(trimmed: &str) -> bool {
65    // Match ```gram or ~~~gram (with optional trailing whitespace)
66    for prefix in ["```", "~~~"] {
67        if let Some(rest) = trimmed.strip_prefix(prefix) {
68            let lang = rest.trim();
69            if lang.eq_ignore_ascii_case("gram") {
70                return true;
71            }
72        }
73    }
74    false
75}
76
77fn is_fence_close(trimmed: &str) -> bool {
78    (trimmed.starts_with("```") || trimmed.starts_with("~~~"))
79        && trimmed.chars().all(|c| c == '`' || c == '~')
80        && trimmed.len() >= 3
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn extracts_gram_fence() {
89        let md = "# Hello\n\n```gram\n(a)-[:KNOWS]->(b)\n```\n";
90        let snippets = extract_snippets(md);
91        assert_eq!(snippets.len(), 1);
92        assert_eq!(snippets[0].source.trim(), "(a)-[:KNOWS]->(b)");
93        assert_eq!(snippets[0].fence_start_line, 2);
94    }
95
96    #[test]
97    fn ignores_non_gram_fences() {
98        let md = "```cypher\nMATCH (n) RETURN n\n```\n\n```gram\n(a)\n```\n";
99        let snippets = extract_snippets(md);
100        assert_eq!(snippets.len(), 1);
101        assert_eq!(snippets[0].source.trim(), "(a)");
102    }
103
104    #[test]
105    fn multiple_fences() {
106        let md = "```gram\n(a)\n```\n\nSome text.\n\n```gram\n(b)\n```\n";
107        let snippets = extract_snippets(md);
108        assert_eq!(snippets.len(), 2);
109        assert_eq!(snippets[0].source.trim(), "(a)");
110        assert_eq!(snippets[1].source.trim(), "(b)");
111    }
112
113    #[test]
114    fn lint_valid_snippet_no_diagnostics() {
115        let md = "```gram\n(alice)-[:KNOWS]->(bob)\n```\n";
116        let results = lint_markdown(md, &LintOptions { strict: false });
117        assert_eq!(results.len(), 1);
118        assert!(results[0].1.is_empty());
119    }
120
121    #[test]
122    fn lint_invalid_snippet_has_diagnostics() {
123        let md = "```gram\n(((\n```\n";
124        let results = lint_markdown(md, &LintOptions { strict: false });
125        assert_eq!(results.len(), 1);
126        assert!(!results[0].1.is_empty());
127    }
128}