badness 0.14.0

A language server, formatter, and linter for LaTeX
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
//! `hard-coded-reference`: a literal cross-reference like `Figure 3`, `Table~1`,
//! or `Section 2` written in prose instead of `\ref`/`\cref` to a `\label`
//! (textidote sh:hcfig/hctab/hcsec).
//!
//! Hard-coding the number defeats LaTeX's automatic numbering: renumbering a
//! float or reordering sections silently breaks the reference, and the reader
//! loses the hyperlink. The convention is `\cref{fig:x}` (or `Figure~\ref{fig:x}`)
//! so the number tracks the target.
//!
//! **Report-only, heuristic.** The rule ships no autofix: the correct rewrite
//! needs the *label* the number refers to, which is nowhere in the text, so
//! there is nothing to synthesize (tenet 1 -- a fix owes correctness by
//! construction, and we cannot meet that here). It only reports the finding.
//!
//! To stay out of false positives the shape is deliberately narrow:
//!
//! - The reference word is a **capitalized** member of a curated list
//!   ([`REFERENCE_WORDS`]) matched exactly as a whole `WORD` token, so plurals
//!   (`Figures`), lowercase (`figure`), and glued forms (`(Figure`) are left
//!   alone -- conservative by design (false negatives beat false positives).
//! - It must be followed, across a single space or a tie `~` (never a paragraph
//!   break), by a `WORD` that is an **arabic number** (leading digit, no ASCII
//!   letters), so `Figure~\ref{x}` (a command follows) and `Figure three` (a
//!   word) never match.
//!
//! The rule reads only `WORD` tokens and skips math, so comments, `\verb`, and
//! verbatim (which never lex as `WORD`) are untouched. Three more shapes are gated
//! out as false positives: a citation locator (`\cite[Section~8.1]{…}`, via
//! [`super::in_key_argument`]) references *external* work, an environment title
//! (`\begin{thm}[Conway's Theorem 0]`, via [`in_environment_title`]) is a proper
//! name, and an `\item[…]` label (`\item[Part 3.]`, via [`in_item_label`]) is a
//! description-list caption — none is a cross-reference into this document.

use std::path::PathBuf;

use crate::linter::diagnostic::{Diagnostic, Severity};
use crate::syntax::{SyntaxElement, SyntaxKind, SyntaxToken};

use super::{Example, Rule, RuleContext};

const EXAMPLES: &[Example] = &[
    Example {
        caption: "A hard-coded figure number instead of a cross-reference:",
        source: "See Figure 3 for the results.\n",
    },
    Example {
        caption: "Even tied with `~`, the number is still hard-coded:",
        source: "Table~1 lists the parameters.\n",
    },
];

/// Capitalized reference words (and dotted abbreviations) that, when followed by
/// a bare number, signal a hard-coded cross-reference. Matched exactly against a
/// whole `WORD` token, so only these spellings fire.
const REFERENCE_WORDS: &[&str] = &[
    "Figure",
    "Fig.",
    "Table",
    "Tab.",
    "Section",
    "Sec.",
    "Chapter",
    "Chap.",
    "Equation",
    "Eq.",
    "Appendix",
    "Algorithm",
    "Alg.",
    "Listing",
    "Theorem",
    "Lemma",
    "Definition",
    "Corollary",
    "Proposition",
];

pub struct HardCodedReference;

impl Rule for HardCodedReference {
    fn id(&self) -> &'static str {
        "hard-coded-reference"
    }

    fn default_severity(&self) -> Severity {
        Severity::Warning
    }

    fn description(&self) -> &'static str {
        "Flag a literal cross-reference written in prose -- `Figure 3`, `Table~1`, \
         `Section 2` -- instead of `\\ref`/`\\cref` to a `\\label` (textidote \
         sh:hcfig/hctab/hcsec). Hard-coding the number defeats LaTeX's automatic \
         numbering: renumbering a float or reordering sections silently breaks the \
         reference and drops the hyperlink. The rule is **report-only** -- the \
         correct rewrite needs the label the number refers to, which is not in the \
         text, so no autofix is offered. To stay conservative it fires only for a \
         capitalized reference word (`Figure`, `Table`, `Section`, `Eq.`, ...) \
         matched as a whole word and directly followed, across one space or a tie \
         `~`, by an arabic number; plurals, lowercase, `Figure~\\ref{x}`, and \
         `Figure three` are left alone. It also skips a citation locator \
         (`\\cite[Section~8.1]{...}`, a reference into external work), an \
         environment title (`\\begin{thm}[Conway's Theorem 0]`, a proper name), and \
         an `\\item[label]` description-list caption (`\\item[Part 3.]`). It never \
         touches math, comments, or verbatim."
    }

    fn examples(&self) -> &'static [Example] {
        EXAMPLES
    }

    fn interests(&self) -> &'static [SyntaxKind] {
        &[SyntaxKind::WORD]
    }

    fn check(&self, el: &SyntaxElement, ctx: &RuleContext<'_>, sink: &mut Vec<Diagnostic>) {
        let Some(word) = el.as_token() else {
            return;
        };
        let kw = word.text();
        if !REFERENCE_WORDS.contains(&kw) {
            return;
        }
        // A citation locator (`\cite[Section~8.1]{…}`) points into *external* work,
        // an environment title (`\begin{thm}[Conway's Theorem 0]`) is a proper name,
        // and an `\item[…]` label (`\item[Part 3.]`) is a description-list caption —
        // none is a hard-coded cross-reference into this document, so the number
        // there is not ours to track with a `\label`.
        if super::in_key_argument(word) || in_environment_title(word) || in_item_label(word) {
            return;
        }
        // A `.` in math is not sentence punctuation, and a reference word there is
        // not prose; skip math entirely.
        if ctx.in_math(usize::from(word.text_range().start())) {
            return;
        }
        // The separator between the word and the number: either a tie `~`, or a
        // run of trivia (spaces/tabs/newlines) with no paragraph break. A blank
        // line (a second `NEWLINE`) means the number starts a new paragraph, so it
        // never reaches the numeric token below and is rejected.
        let Some(first) = word.next_token() else {
            return;
        };
        let (number, tie) = if first.kind() == SyntaxKind::TILDE {
            (first.next_token(), true)
        } else {
            // Skip a same-paragraph gap: one WHITESPACE and/or a single NEWLINE.
            let mut tok = Some(first);
            let mut newlines = 0;
            while let Some(t) = &tok {
                match t.kind() {
                    SyntaxKind::WHITESPACE => {}
                    SyntaxKind::NEWLINE => newlines += 1,
                    _ => break,
                }
                if newlines >= 2 {
                    return; // paragraph break
                }
                tok = t.next_token();
            }
            (tok, false)
        };
        let Some(number) = number else {
            return;
        };
        if number.kind() != SyntaxKind::WORD {
            return;
        }
        let Some(num_len) = numeric_ref_len(number.text()) else {
            return;
        };

        // Span the whole phrase, from the reference word through the number's
        // leading digit run (trailing punctuation like a comma or sentence period
        // is left out).
        let start = usize::from(word.text_range().start());
        let end = usize::from(number.text_range().start()) + num_len;
        let sep_display = if tie { "~" } else { " " };
        let phrase = format!("{kw}{sep_display}{}", &number.text()[..num_len]);
        sink.push(Diagnostic {
            rule: self.id(),
            severity: self.default_severity(),
            path: PathBuf::new(),
            start,
            end,
            message: format!(
                "hard-coded reference `{phrase}`; use `\\ref`/`\\cref` to a `\\label` so the number stays in sync"
            ),
            fix: None,
            related: Vec::new(),
        });
    }
}

/// Whether `tok` sits inside the optional `[title]` of a `\begin{env}[...]` — an
/// environment title such as a theorem's proper name
/// (`\begin{thm}[Conway's Theorem 0]`), not a cross-reference. The `[...]` attaches
/// to the `\begin` opener, so the `OPTIONAL`'s parent is the `BEGIN` node (the arms
/// of a nested group would leave `BEGIN` as an ancestor, so match the `OPTIONAL`
/// directly). Distinct from [`super::in_key_argument`], whose `OPTIONAL`/`GROUP`
/// hangs off a `COMMAND`.
fn in_environment_title(tok: &SyntaxToken) -> bool {
    tok.parent_ancestors().any(|node| {
        node.kind() == SyntaxKind::OPTIONAL
            && node.parent().is_some_and(|p| p.kind() == SyntaxKind::BEGIN)
    })
}

/// Whether `tok` sits inside the optional `[label]` of an `\item` — a
/// description-list caption such as `\item[Part 3.]`, not a cross-reference into
/// this document. The `[...]` attaches to the `\item` opener, so the `OPTIONAL`'s
/// parent is the `COMMAND` node named `item` (mirrors [`in_environment_title`],
/// whose `OPTIONAL` hangs off a `BEGIN`; and [`super::in_key_argument`], which
/// keys the same shape on the command name).
fn in_item_label(tok: &SyntaxToken) -> bool {
    tok.parent_ancestors().any(|node| {
        node.kind() == SyntaxKind::OPTIONAL
            && node.parent().is_some_and(|p| {
                p.kind() == SyntaxKind::COMMAND
                    && crate::ast::command_name(&p).is_some_and(|n| n == "item")
            })
    })
}

/// Byte length of the numeric reference at the start of `text`, or `None` if the
/// token is not a bare arabic number. Qualifies when the first character is an
/// ASCII digit and the token contains no ASCII letters (so `3rd`, `v3`, and `3x3`
/// are rejected); the returned length covers the leading run of digits and
/// interior dots (`3.2`), trimming any trailing dot so a sentence period stays
/// out of the span.
fn numeric_ref_len(text: &str) -> Option<usize> {
    let bytes = text.as_bytes();
    if !bytes.first().is_some_and(u8::is_ascii_digit) {
        return None;
    }
    if bytes.iter().any(u8::is_ascii_alphabetic) {
        return None;
    }
    let run = bytes
        .iter()
        .take_while(|&&b| b.is_ascii_digit() || b == b'.')
        .count();
    Some(text[..run].trim_end_matches('.').len())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse;
    use crate::semantic::SemanticModel;
    use crate::syntax::SyntaxNode;

    fn findings(src: &str) -> Vec<Diagnostic> {
        let root = SyntaxNode::new_root(parse(src).green);
        let model = SemanticModel::build(&root);
        let ctx = RuleContext::new(
            std::path::Path::new("x.tex"),
            &root,
            &model,
            None,
            None,
            None,
        );
        let mut out = Vec::new();
        for el in root.descendants_with_tokens() {
            if HardCodedReference.interests().contains(&el.kind()) {
                HardCodedReference.check(&el, &ctx, &mut out);
            }
        }
        out
    }

    #[test]
    fn flags_figure_number() {
        let src = "See Figure 3 here\n";
        let out = findings(src);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].rule, "hard-coded-reference");
        // Span covers `Figure 3` (bytes 4..12), not the trailing text.
        assert_eq!(&src[out[0].start..out[0].end], "Figure 3");
        // No autofix: report-only.
        assert!(out[0].fix.is_none());
    }

    #[test]
    fn flags_tie_separated_number() {
        let src = "Table~1 lists them\n";
        let out = findings(src);
        assert_eq!(out.len(), 1);
        assert_eq!(&src[out[0].start..out[0].end], "Table~1");
    }

    #[test]
    fn flags_dotted_abbreviation() {
        assert_eq!(findings("as in Fig. 3 above\n").len(), 1);
        assert_eq!(findings("see Eq.~2 for this\n").len(), 1);
    }

    #[test]
    fn ref_command_is_left_alone() {
        assert!(findings("Figure~\\ref{fig:x} shows\n").is_empty());
        assert!(findings("see Figure \\ref{fig:x}\n").is_empty());
    }

    #[test]
    fn lowercase_word_is_left_alone() {
        // Capitalization is the convention for a named reference; stay conservative.
        assert!(findings("in figure 3 we plot\n").is_empty());
    }

    #[test]
    fn plural_and_glued_forms_are_left_alone() {
        assert!(findings("Figures 3 and 4\n").is_empty());
        assert!(findings("(Figure 3)\n").is_empty());
    }

    #[test]
    fn spelled_out_number_is_left_alone() {
        assert!(findings("Figure three shows\n").is_empty());
    }

    #[test]
    fn bare_reference_word_is_left_alone() {
        assert!(findings("the Figure shows a plot\n").is_empty());
    }

    #[test]
    fn subpart_and_version_numbers_are_left_alone() {
        // `3a` (subfigure) and `v3` carry a letter, so they are not bare numbers.
        assert!(findings("Figure 3a shows\n").is_empty());
    }

    #[test]
    fn trailing_punctuation_stays_out_of_span() {
        let src = "See Figure 3, which\n";
        let out = findings(src);
        assert_eq!(out.len(), 1);
        // The comma is left out of the span.
        assert_eq!(&src[out[0].start..out[0].end], "Figure 3");
    }

    #[test]
    fn decimal_number_is_flagged() {
        let src = "See Section 3.2 for\n";
        let out = findings(src);
        assert_eq!(out.len(), 1);
        assert_eq!(&src[out[0].start..out[0].end], "Section 3.2");
    }

    #[test]
    fn paragraph_break_is_left_alone() {
        // The number starts a new paragraph, not a reference.
        assert!(findings("Figure\n\n3\n").is_empty());
    }

    #[test]
    fn single_line_break_is_flagged() {
        // Wrapped source: `Figure` and `3` on adjacent lines is still a reference.
        assert_eq!(findings("see Figure\n3 here\n").len(), 1);
    }

    #[test]
    fn math_is_left_alone() {
        assert!(findings("$Section 2$\n").is_empty());
    }

    #[test]
    fn flags_each_occurrence() {
        assert_eq!(findings("Figure 3 and Table 4\n").len(), 2);
    }

    #[test]
    fn citation_locator_is_left_alone() {
        // `\cite[Section~8.1]{…}` points into external work, not this document.
        assert!(findings("see \\cite[Section~8.1]{knuth}\n").is_empty());
        assert!(findings("\\cite[Chapter 3]{smith}\n").is_empty());
    }

    #[test]
    fn environment_title_is_left_alone() {
        // A theorem title is a proper name, not a cross-reference.
        assert!(findings("\\begin{thm}[Conway's Theorem 0]\n").is_empty());
        assert!(findings("\\begin{lemma}[Lemma 2 restated]\n").is_empty());
    }

    #[test]
    fn reference_outside_title_still_flagged() {
        // The gates are narrow: prose after the environment opener still fires.
        assert_eq!(findings("\\begin{thm}[Main]\nSee Figure 3 here\n").len(), 1);
    }

    #[test]
    fn item_label_is_left_alone() {
        // A description-list label is a caption, not a cross-reference. The gate is
        // general, not Part-specific — a reference word in the label is also spared.
        assert!(findings("\\item[Part 3.] text\n").is_empty());
        assert!(findings("\\item[Section 2 recap] text\n").is_empty());
    }

    #[test]
    fn reference_in_item_body_still_flagged() {
        // The gate is scoped to the `[label]`; prose after it still fires.
        assert_eq!(findings("\\item[Note] See Figure 3 here\n").len(), 1);
    }

    #[test]
    fn part_no_longer_flagged() {
        // "Part" is too ambiguous (course names, external divisions) and was
        // demoted; a genuine reference word still fires so the demotion is narrow.
        assert!(findings("The Part 3 course is a prerequisite.\n").is_empty());
        assert_eq!(findings("See Section 3 here.\n").len(), 1);
    }
}