panache 2.61.0

An LSP, formatter, and linter for Markdown, Quarto, and R Markdown
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use std::collections::HashSet;
use std::path::Path;

use crate::config::Config;
use crate::linter::diagnostics::{Diagnostic, Location};
use crate::linter::rules::{DiagnosticCode, LintContext, Requirement, Rule, RuleMeta};
use crate::syntax::{
    AstNode, FootnoteReference, ImageLink, Link, SyntaxKind, SyntaxNode, UnresolvedReference,
};
use crate::utils::normalize_label;

pub struct UnusedDefinitionsRule;

impl Rule for UnusedDefinitionsRule {
    fn name(&self) -> &str {
        "unused-definitions"
    }

    fn metadata(&self) -> RuleMeta {
        RuleMeta {
            name: "unused-definitions",
            default_on: true,
            requires: Requirement::Always,
            auto_fix: false,
            codes: const {
                &[
                    DiagnosticCode::warning("unused-definition-label"),
                    DiagnosticCode::warning("unused-footnote-id"),
                ]
            },
        }
    }

    fn node_interests(&self) -> &'static [SyntaxKind] {
        &[
            SyntaxKind::LINK,
            SyntaxKind::IMAGE_LINK,
            SyntaxKind::UNRESOLVED_REFERENCE,
            SyntaxKind::FOOTNOTE_REFERENCE,
        ]
    }

    fn check(&self, cx: &LintContext) -> Vec<Diagnostic> {
        let (tree, input, config, metadata) = (cx.tree, cx.input, cx.config, cx.metadata);
        let db = crate::salsa::SalsaDb::default();
        let index = crate::salsa::symbol_usage_index_from_tree(&db, tree, &config.extensions);
        let mut used = collect_usage_labels(
            cx.nodes(SyntaxKind::LINK)
                .iter()
                .chain(cx.nodes(SyntaxKind::IMAGE_LINK).iter())
                .chain(cx.nodes(SyntaxKind::UNRESOLVED_REFERENCE).iter())
                .chain(cx.nodes(SyntaxKind::FOOTNOTE_REFERENCE).iter())
                .cloned(),
        );

        if let Some(metadata) = metadata {
            extend_usage_labels_from_project(&mut used, metadata, config);
        }

        let mut diagnostics = Vec::new();
        for (label, ranges) in index.reference_definition_entries() {
            if used.reference_labels.contains(label) {
                continue;
            }
            for range in ranges {
                diagnostics.push(Diagnostic::warning(
                    Location::from_range(label_bracket_range(input, *range), input),
                    "unused-definition-label",
                    format!("Reference definition '[{}]' is never used", label),
                ));
            }
        }

        for (id, ranges) in index.footnote_definition_entries() {
            if used.footnote_ids.contains(id) {
                continue;
            }
            for range in ranges {
                diagnostics.push(Diagnostic::warning(
                    Location::from_range(label_bracket_range(input, *range), input),
                    "unused-footnote-id",
                    format!("Footnote '[^{}]' is never used", id),
                ));
            }
        }

        diagnostics
    }
}

#[derive(Default)]
struct UsageLabels {
    reference_labels: HashSet<String>,
    footnote_ids: HashSet<String>,
}

/// Collect reference/footnote usage labels from a stream of candidate nodes.
///
/// Driven off pre-bucketed nodes for the local document (one shared walk) and
/// off `other_tree.descendants()` for project sibling files; both feed the same
/// per-node classifiers so the logic stays single-sourced.
fn collect_usage_labels(nodes: impl Iterator<Item = SyntaxNode>) -> UsageLabels {
    let mut reference_labels: HashSet<String> = HashSet::new();
    let mut footnote_ids: HashSet<String> = HashSet::new();

    for node in nodes {
        match node.kind() {
            SyntaxKind::LINK => {
                if let Some(label) = Link::cast(node).and_then(usage_label_from_link) {
                    reference_labels.insert(label);
                }
            }
            // Reference-style images (`![alt][label]`, collapsed `![label][]`,
            // shortcut `![label]`) resolve to `IMAGE_LINK` rather than `LINK`,
            // so they count as usages of the label they reference too.
            SyntaxKind::IMAGE_LINK => {
                if let Some(label) = ImageLink::cast(node).and_then(usage_label_from_image) {
                    reference_labels.insert(label);
                }
            }
            // Bracket-shape patterns whose label didn't resolve as a refdef
            // still count as a usage of the label they reference — so a
            // `[GitHub]` shortcut counts as using the `[github]:` definition
            // even if that definition lives in another file.
            SyntaxKind::UNRESOLVED_REFERENCE => {
                if let Some(label) =
                    UnresolvedReference::cast(node).and_then(usage_label_from_unresolved)
                {
                    reference_labels.insert(label);
                }
            }
            SyntaxKind::FOOTNOTE_REFERENCE => {
                if let Some(footnote) = FootnoteReference::cast(node) {
                    let id = normalize_label(&footnote.id());
                    if !id.is_empty() {
                        footnote_ids.insert(id);
                    }
                }
            }
            _ => {}
        }
    }

    UsageLabels {
        reference_labels,
        footnote_ids,
    }
}

/// Narrow a definition's full-node range down to just its `[label]` (or
/// `[^id]`) bracket span, so the diagnostic underlines the label rather than
/// the whole definition line (destination URL or footnote body included).
///
/// Falls back to the original range if no bracket pair is found. Honors
/// backslash escapes so an escaped `\]` inside the label doesn't close it.
fn label_bracket_range(input: &str, range: rowan::TextRange) -> rowan::TextRange {
    let start: usize = range.start().into();
    let end: usize = range.end().into();
    let Some(slice) = input.get(start..end) else {
        return range;
    };
    let Some(open) = slice.find('[') else {
        return range;
    };
    let bytes = slice.as_bytes();
    let mut i = open + 1;
    let mut escaped = false;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' if !escaped => escaped = true,
            b']' if !escaped => {
                let abs_start = (start + open) as u32;
                let abs_end = (start + i + 1) as u32;
                return rowan::TextRange::new(abs_start.into(), abs_end.into());
            }
            _ => escaped = false,
        }
        i += 1;
    }
    range
}

fn usage_label_from_link(link: Link) -> Option<String> {
    if link
        .syntax()
        .ancestors()
        .any(|ancestor| ancestor.kind() == SyntaxKind::REFERENCE_DEFINITION)
    {
        return None;
    }
    if link.dest().is_some() {
        return None;
    }
    if let Some(link_ref) = link.reference() {
        let label = normalize_label(&link_ref.label());
        if !label.is_empty() {
            return Some(label);
        }
    }
    // Match on the raw label source, not rendered text: a shortcut label may
    // parse as inline structure (e.g. a code span `` [`insta`] ``) that
    // `text_content` drops, which would fail to match the definition's label.
    link.text()
        .map(|text| normalize_label(&text.raw_label()))
        .filter(|label| !label.is_empty())
}

fn usage_label_from_image(image: ImageLink) -> Option<String> {
    if image
        .syntax()
        .ancestors()
        .any(|ancestor| ancestor.kind() == SyntaxKind::REFERENCE_DEFINITION)
    {
        return None;
    }
    if image.dest().is_some() {
        return None;
    }
    if let Some(link_ref) = image.reference() {
        let label = normalize_label(&link_ref.label());
        if !label.is_empty() {
            return Some(label);
        }
    }
    image
        .alt()
        .map(|alt| normalize_label(&alt.text()))
        .filter(|label| !label.is_empty())
}

fn usage_label_from_unresolved(unresolved: UnresolvedReference) -> Option<String> {
    if let Some(label) = unresolved.label() {
        let normalized = normalize_label(&label);
        if !normalized.is_empty() {
            return Some(normalized);
        }
    }
    let normalized = normalize_label(&unresolved.text());
    if normalized.is_empty() {
        None
    } else {
        Some(normalized)
    }
}

fn extend_usage_labels_from_project(
    usage: &mut UsageLabels,
    metadata: &crate::metadata::DocumentMetadata,
    config: &Config,
) {
    let doc_path = metadata
        .source_path
        .canonicalize()
        .unwrap_or_else(|_| metadata.source_path.clone());
    let project_root = crate::includes::find_bookdown_root(&doc_path)
        .or_else(|| crate::includes::find_quarto_root(&doc_path));
    let Some(project_root) = project_root else {
        return;
    };
    let is_bookdown = crate::includes::find_bookdown_root(&doc_path).is_some();

    for path in crate::includes::find_project_documents(&project_root, config, is_bookdown) {
        extend_usage_labels_from_file(usage, &path, config);
    }
}

fn extend_usage_labels_from_file(usage: &mut UsageLabels, path: &Path, config: &Config) {
    if let Ok(other_input) = std::fs::read_to_string(path) {
        let other_tree = crate::parser::parse(&other_input, Some(config.clone()));
        let other_usage = collect_usage_labels(other_tree.descendants());
        usage.reference_labels.extend(other_usage.reference_labels);
        usage.footnote_ids.extend(other_usage.footnote_ids);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Flavor;
    use std::fs;
    use tempfile::TempDir;

    fn parse_and_lint(input: &str) -> Vec<Diagnostic> {
        let config = Config::default();
        let tree = crate::parser::parse(input, Some(config.clone()));
        let rule = UnusedDefinitionsRule;
        rule.check_tree(&tree, input, &config, None)
    }

    #[test]
    fn reports_unused_reference_definition() {
        let input =
            "[used]: https://example.com\n[unused]: https://example.org\n\nSee [x][used].\n";
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "unused-definition-label");
        assert!(diagnostics[0].message.contains("[unused]"));
    }

    #[test]
    fn reports_unused_footnote_definition() {
        let input = "Text with footnote[^1].\n\n[^1]: Used.\n[^2]: Unused.\n";
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "unused-footnote-id");
        assert!(diagnostics[0].message.contains("[^2]"));
    }

    #[test]
    fn accepts_definition_used_by_full_reference_image() {
        let input = "![This is an image][image-path]\n\n[image-path]: https://example.com/i.png\n";
        let diagnostics = parse_and_lint(input);
        assert!(
            diagnostics.is_empty(),
            "full reference image should count as a usage: {diagnostics:?}"
        );
    }

    #[test]
    fn accepts_definition_used_by_collapsed_reference_image() {
        let input = "![image-path][]\n\n[image-path]: https://example.com/i.png\n";
        let diagnostics = parse_and_lint(input);
        assert!(
            diagnostics.is_empty(),
            "collapsed reference image should count as a usage: {diagnostics:?}"
        );
    }

    #[test]
    fn accepts_definition_used_by_shortcut_reference_image() {
        let input = "![image-path]\n\n[image-path]: https://example.com/i.png\n";
        let diagnostics = parse_and_lint(input);
        assert!(
            diagnostics.is_empty(),
            "shortcut reference image should count as a usage: {diagnostics:?}"
        );
    }

    #[test]
    fn accepts_definitions_used_by_reference_image_inside_reference_link() {
        let input = "[![example][example-badge]][example-url]\n\n[example-badge]: https://example.com\n[example-url]: https://example.com\n";
        let diagnostics = parse_and_lint(input);
        assert!(
            diagnostics.is_empty(),
            "reference image nested inside a reference link should count both labels as used: {diagnostics:?}"
        );
    }

    #[test]
    fn still_reports_unused_definition_with_only_inline_image() {
        let input = "![alt](https://example.com/i.png)\n\n[unused]: https://example.org\n";
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "unused-definition-label");
        assert!(diagnostics[0].message.contains("[unused]"));
    }

    #[test]
    fn accepts_used_shortcut_reference_definition() {
        let input = "See [Label].\n\n[Label]: https://example.com\n";
        let diagnostics = parse_and_lint(input);
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn accepts_shortcut_reference_with_code_span_label() {
        // `[`insta`]` is a shortcut reference link whose label is a code span.
        // Its raw label matches the `[`insta`]:` definition, so the definition
        // is used, not unused. The usage side must compare on raw label text,
        // not rendered text (which would drop the code span and mismatch).
        let input = "[`insta`]\n\n[`insta`]: https://insta.rs/\n";
        let diagnostics = parse_and_lint(input);
        assert!(
            diagnostics.is_empty(),
            "code-span shortcut label should count as a usage: {diagnostics:?}"
        );
    }

    #[test]
    fn unused_definition_span_covers_only_the_label() {
        let input = "[unused]: https://example.org\n";
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 1);
        let range = diagnostics[0].location.range;
        assert_eq!(
            &input[range], "[unused]",
            "span should cover only the label"
        );
    }

    #[test]
    fn unused_footnote_span_covers_only_the_label() {
        let input = "[^2]: Unused.\n";
        let diagnostics = parse_and_lint(input);
        assert_eq!(diagnostics.len(), 1);
        let range = diagnostics[0].location.range;
        assert_eq!(&input[range], "[^2]", "span should cover only the label");
    }

    #[test]
    fn does_not_report_unused_definition_when_used_in_project_document() {
        let temp = TempDir::new().expect("tempdir");
        let root = temp.path();
        let doc1 = root.join("1-one.Rmd");
        let doc2 = root.join("2-two.Rmd");
        fs::write(root.join("_bookdown.yml"), "").expect("write _bookdown.yml");
        fs::write(&doc1, "[shared]: https://example.com\n").expect("write doc1");
        fs::write(&doc2, "See [x][shared].\n").expect("write doc2");

        let input = fs::read_to_string(&doc1).expect("read doc1");
        let mut config = Config {
            flavor: Flavor::RMarkdown,
            extensions: crate::config::Extensions::for_flavor(Flavor::RMarkdown),
            ..Default::default()
        };
        config.extensions.bookdown_references = true;
        let tree = crate::parser::parse(&input, Some(config.clone()));
        let metadata = crate::metadata::extract_project_metadata(&tree, &doc1).expect("metadata");

        let rule = UnusedDefinitionsRule;
        let diagnostics = rule.check_tree(&tree, &input, &config, Some(&metadata));
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn reports_unused_definition_when_not_used_in_project_document() {
        let temp = TempDir::new().expect("tempdir");
        let root = temp.path();
        let doc1 = root.join("1-one.Rmd");
        let doc2 = root.join("2-two.Rmd");
        fs::write(root.join("_bookdown.yml"), "").expect("write _bookdown.yml");
        fs::write(&doc1, "[shared]: https://example.com\n").expect("write doc1");
        fs::write(&doc2, "Plain text.\n").expect("write doc2");

        let input = fs::read_to_string(&doc1).expect("read doc1");
        let mut config = Config {
            flavor: Flavor::RMarkdown,
            extensions: crate::config::Extensions::for_flavor(Flavor::RMarkdown),
            ..Default::default()
        };
        config.extensions.bookdown_references = true;
        let tree = crate::parser::parse(&input, Some(config.clone()));
        let metadata = crate::metadata::extract_project_metadata(&tree, &doc1).expect("metadata");

        let rule = UnusedDefinitionsRule;
        let diagnostics = rule.check_tree(&tree, &input, &config, Some(&metadata));
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "unused-definition-label");
    }

    #[test]
    fn falls_back_to_local_behavior_without_project_root() {
        let temp = TempDir::new().expect("tempdir");
        let doc = temp.path().join("standalone.qmd");
        fs::write(&doc, "[alone]: https://example.com\n").expect("write doc");

        let input = fs::read_to_string(&doc).expect("read doc");
        let config = Config::default();
        let tree = crate::parser::parse(&input, Some(config.clone()));
        let metadata = crate::metadata::extract_project_metadata(&tree, &doc).expect("metadata");

        let rule = UnusedDefinitionsRule;
        let diagnostics = rule.check_tree(&tree, &input, &config, Some(&metadata));
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].code, "unused-definition-label");
    }
}