badness 0.5.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
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
//! End-to-end tests for the lint driver (`linter::lint_document`): the public
//! entry both the CLI and the language server call. Exercises rule collection,
//! cross-rule ordering, and `% badness-ignore` suppression over realistic
//! multi-line documents — complementing the focused per-rule unit tests in
//! `src/linter/`.

use std::path::{Path, PathBuf};

use badness::linter::{Severity, lint_document};
use badness::parser::{parse, reconstruct};
use badness::project::labels::{document_label_names, is_document_root};
use badness::project::{FileFacts, IncludeGraph, ResolvedLabels, collect_include_edge_keys};
use badness::semantic::SemanticModel;
use badness::syntax::SyntaxNode;

/// Lint `src` through the public driver, as the CLI does.
fn lint(src: &str) -> Vec<(&'static str, Severity)> {
    let root = SyntaxNode::new_root(parse(src).green);
    let model = SemanticModel::build(&root);
    lint_document(Path::new("doc.tex"), &root, &model, None, None)
        .into_iter()
        .map(|d| (d.rule, d.severity))
        .collect()
}

/// Lint a whole `(path, source)` project through the driver exactly as the CLI's
/// `run_lint` does: build every model first, resolve labels across the include
/// graph, then lint each file with the shared resolution. Returns
/// `(path, rule, message)` for every finding.
fn lint_project(files: &[(&str, &str)]) -> Vec<(String, &'static str, String)> {
    let parsed: Vec<(PathBuf, SyntaxNode, SemanticModel)> = files
        .iter()
        .map(|(path, src)| {
            let root = SyntaxNode::new_root(parse(src).green);
            let model = SemanticModel::build(&root);
            (PathBuf::from(path), root, model)
        })
        .collect();

    let facts: Vec<FileFacts> = parsed
        .iter()
        .map(|(path, root, _)| FileFacts {
            path: path.clone(),
            include_edges: collect_include_edge_keys(root, path.parent()),
        })
        .collect();
    let label_inputs: Vec<_> = parsed
        .iter()
        .map(|(path, root, model)| {
            (
                path.clone(),
                document_label_names(model),
                is_document_root(root),
            )
        })
        .collect();
    let resolved = ResolvedLabels::build(&label_inputs, &IncludeGraph::build(&facts, None));

    let mut out = Vec::new();
    for (path, root, model) in &parsed {
        for d in lint_document(path, root, model, Some(&resolved), None) {
            out.push((path.display().to_string(), d.rule, d.message));
        }
    }
    out
}

fn rules_only(findings: &[(String, &'static str, String)]) -> Vec<&'static str> {
    findings.iter().map(|(_, rule, _)| *rule).collect()
}

/// Lint a `.tex` source against a set of `(bib_path, bib_source)` bibliographies,
/// exactly as the CLI's `run_lint` assembles cross-file citation resolution.
/// Returns the rule ids of every finding for the `.tex` file (`doc.tex`).
fn lint_with_bib(tex: &str, bibs: &[(&str, &str)]) -> Vec<&'static str> {
    use badness::project::{CiteFileFacts, ResolvedCitations, collect_bib_resource_targets};
    use smol_str::SmolStr;
    use std::collections::HashMap;

    let tex_path = PathBuf::from("doc.tex");
    let root = SyntaxNode::new_root(parse(tex).green);
    let model = SemanticModel::build(&root);

    let bib_keys: HashMap<PathBuf, Vec<SmolStr>> = bibs
        .iter()
        .map(|(path, src)| {
            let bib_model =
                badness::bib::semantic::Model::build(&badness::bib::parse(src).syntax());
            (
                PathBuf::from(path),
                bib_model.entries().iter().map(|e| e.key.clone()).collect(),
            )
        })
        .collect();

    let facts = vec![FileFacts {
        path: tex_path.clone(),
        include_edges: collect_include_edge_keys(&root, tex_path.parent()),
    }];
    let graph = IncludeGraph::build(&facts, None);
    let cite_facts = vec![CiteFileFacts {
        path: tex_path.clone(),
        bib_targets: collect_bib_resource_targets(&root, tex_path.parent()),
        nocite_all: model.has_wildcard_nocite(),
        is_document_root: is_document_root(&root),
    }];
    let citations = ResolvedCitations::build(&cite_facts, &graph, &bib_keys);

    lint_document(&tex_path, &root, &model, None, Some(&citations))
        .into_iter()
        .map(|d| d.rule)
        .collect()
}

#[test]
fn cross_file_undefined_citation_is_flagged() {
    let tex = "\\documentclass{article}\n\\addbibresource{refs.bib}\n\\begin{document}\n\\cite{missing}\n\\end{document}\n";
    let bib = "@article{present, title = {T}}\n";
    let rules = lint_with_bib(tex, &[("refs.bib", bib)]);
    assert!(rules.contains(&"undefined-citation"), "{rules:?}");
}

#[test]
fn cross_file_resolved_citation_is_silent() {
    let tex = "\\documentclass{article}\n\\addbibresource{refs.bib}\n\\begin{document}\n\\cite{present}\n\\end{document}\n";
    let bib = "@article{present, title = {T}}\n";
    let rules = lint_with_bib(tex, &[("refs.bib", bib)]);
    assert!(!rules.contains(&"undefined-citation"), "{rules:?}");
}

#[test]
fn citation_gating_holds_for_fragment_and_wildcard() {
    let bib = "@article{present, title = {T}}\n";
    // No \documentclass → rootless fragment → not flagged even if the key is absent.
    let fragment = "\\addbibresource{refs.bib}\n\\cite{missing}\n";
    assert!(!lint_with_bib(fragment, &[("refs.bib", bib)]).contains(&"undefined-citation"));

    // \nocite{*} pulls in every entry → nothing is undefined.
    let wildcard = "\\documentclass{article}\n\\addbibresource{refs.bib}\n\\nocite{*}\n\\begin{document}\n\\cite{missing}\n\\end{document}\n";
    assert!(!lint_with_bib(wildcard, &[("refs.bib", bib)]).contains(&"undefined-citation"));
}

#[test]
fn bibliography_command_resolves_keys() {
    // The legacy `\bibliography{refs}` form (default `.bib`) resolves too.
    let tex = "\\documentclass{article}\n\\begin{document}\n\\cite{present}\n\\bibliography{refs}\n\\end{document}\n";
    let bib = "@article{present, title = {T}}\n";
    let rules = lint_with_bib(tex, &[("refs.bib", bib)]);
    assert!(!rules.contains(&"undefined-citation"), "{rules:?}");
}

#[test]
fn reports_both_rules_in_document_order() {
    let src = "\\section{Intro}\n\\label{a}\n{\\bf bold}\n\\label{a}\n";
    assert_eq!(
        lint(src),
        vec![
            ("deprecated-command", Severity::Warning),
            ("duplicate-label", Severity::Warning),
        ]
    );
}

#[test]
fn clean_document_has_no_findings() {
    let src = "\\section{Intro}\n\\label{a}\\ref{a}\n\\textbf{ok}\n";
    assert!(lint(src).is_empty());
}

#[test]
fn node_ignore_suppresses_only_the_next_block() {
    let src = "\
% badness-ignore deprecated-command: legacy macro
{\\bf one}

{\\it two}
";
    // The first switch is suppressed; the second still fires.
    assert_eq!(lint(src), vec![("deprecated-command", Severity::Warning)]);
}

#[test]
fn file_ignore_silences_a_rule_everywhere() {
    let src = "\
% badness-ignore-file deprecated-command: legacy file
{\\bf one}
{\\it two}
\\label{a}\\label{a}
";
    // Every deprecated switch is gone; the duplicate label still reports.
    assert_eq!(lint(src), vec![("duplicate-label", Severity::Warning)]);
}

#[test]
fn file_ignore_all_silences_everything() {
    let src = "\
% badness-ignore-file: vendored
{\\bf one}
\\label{a}\\label{a}
";
    assert!(lint(src).is_empty());
}

#[test]
fn stylistic_rules_collected_in_document_order() {
    // An obsolete environment, a `$$` display, and a reversed `\left`/`\right`
    // pair — all surface, sorted by position.
    let src = "\
\\begin{eqnarray}a&=&b\\end{eqnarray}
$$x = y$$
$\\left) a \\right| $
";
    assert_eq!(
        lint(src),
        vec![
            ("obsolete-environment", Severity::Warning),
            ("dollar-display-math", Severity::Warning),
            ("mismatched-delimiter", Severity::Warning),
        ]
    );
}

#[test]
fn modern_constructs_have_no_findings() {
    let src = "\
\\begin{align}a &= b\\end{align}
\\[x = y\\]
$\\left( a \\right] $
";
    assert!(lint(src).is_empty(), "got: {:?}", lint(src));
}

#[test]
fn node_ignore_silences_a_stylistic_rule() {
    let src = "\
% badness-ignore dollar-display-math: legacy snippet
$$x = y$$
";
    assert!(lint(src).is_empty(), "got: {:?}", lint(src));
}

// --- Cross-file lints (driver + resolver) -------------------------------------

#[test]
fn well_formed_project_has_no_cross_file_findings() {
    // main declares the document and references a label defined in the chapter
    // it `\input`s — everything resolves, nothing fires.
    let findings = lint_project(&[
        (
            "main.tex",
            "\\documentclass{article}\n\\input{chap}\n\\ref{a}\n",
        ),
        ("chap.tex", "\\label{a}\n"),
    ]);
    assert!(
        findings.is_empty(),
        "expected clean project, got: {findings:?}"
    );
}

#[test]
fn cross_file_duplicate_label_is_reported_in_both_files() {
    // The same key defined in two files of one document is a cross-file dupe;
    // each file's definition is flagged, naming the other.
    let findings = lint_project(&[
        (
            "main.tex",
            "\\documentclass{article}\n\\input{chap}\n\\label{dup}\n",
        ),
        ("chap.tex", "\\label{dup}\n"),
    ]);
    assert_eq!(
        rules_only(&findings),
        vec!["duplicate-label", "duplicate-label"]
    );
    assert!(
        findings
            .iter()
            .any(|(p, _, m)| p == "main.tex" && m.contains("`chap.tex`"))
    );
    assert!(
        findings
            .iter()
            .any(|(p, _, m)| p == "chap.tex" && m.contains("`main.tex`"))
    );
}

#[test]
fn undefined_ref_fires_in_a_closed_rooted_document() {
    let findings = lint_project(&[(
        "main.tex",
        "\\documentclass{article}\n\\label{a}\\ref{a}\\ref{ghost}\n",
    )]);
    assert_eq!(rules_only(&findings), vec!["undefined-ref"]);
    assert!(findings[0].2.contains("ghost"));
}

#[test]
fn undefined_ref_is_silent_for_a_bare_fragment() {
    // No `\documentclass`: the label may live in an unanalyzed main document, so
    // the ref is not flagged.
    let findings = lint_project(&[("chap.tex", "\\ref{elsewhere}\n")]);
    assert!(findings.is_empty(), "expected silence, got: {findings:?}");
}

#[test]
fn independent_documents_do_not_cross_contaminate() {
    // Two standalone documents, each defining `\label{intro}`: separate include
    // components, so neither is a cross-file duplicate and each ref resolves
    // within its own document.
    let findings = lint_project(&[
        (
            "one.tex",
            "\\documentclass{article}\n\\label{intro}\\ref{intro}\n",
        ),
        (
            "two.tex",
            "\\documentclass{article}\n\\label{intro}\\ref{intro}\n",
        ),
    ]);
    assert!(
        findings.is_empty(),
        "expected no collisions, got: {findings:?}"
    );
}

// ---------------------------------------------------------------------------
// Autofixes (`lint --fix`). The engine and the `dollar-display-math` swap.
// ---------------------------------------------------------------------------

use badness::formatter::{FormatStyle, format_with_style};
use badness::linter::{apply_fixes, check_document};
use badness::parser::LatexFlavor;

/// Apply every available fix (including unsafe) to `text` at a fixpoint, exactly
/// as the CLI's `fix_file` does, and return the rewritten text.
fn fix_to_fixpoint(text: &str) -> String {
    let path = Path::new("doc.tex");
    let mut content = text.to_owned();
    for _ in 0..10 {
        let fixes: Vec<_> = check_document(path, &content, LatexFlavor::Document)
            .into_iter()
            .filter_map(|d| d.fix)
            .collect();
        if fixes.is_empty() {
            break;
        }
        let out = apply_fixes(&content, &fixes, true);
        if out.applied == 0 {
            break;
        }
        content = out.output;
    }
    content
}

/// Tenet 1: a fix is a textual edit judged on correctness, not formatting.
/// Applying every fix to fixpoint must leave a tree that still parses cleanly
/// and is still lossless. A fix does *not* owe line-width or format-idempotence
/// (layout is the formatter's job; the pipeline is fix-then-format).
fn assert_fix_is_correct(input: &str) {
    let style = FormatStyle::default();
    let clean = format_with_style(input, style).expect("input should format");
    let fixed = fix_to_fixpoint(&clean);

    assert!(
        parse(&fixed).errors.is_empty(),
        "fixed output must parse cleanly:\n{fixed:?}"
    );
    assert_eq!(
        reconstruct(&fixed),
        fixed,
        "fix broke losslessness (tenet 1).\nfrom:\n{clean}\n--- after fixes ---\n{fixed}"
    );
}

#[test]
fn dollar_display_fix_rewrites_to_bracket_form() {
    assert_eq!(fix_to_fixpoint("$$x = y$$\n"), "\\[x = y\\]\n");
}

#[test]
fn dollar_display_fix_clears_the_finding() {
    // After the swap, re-linting the rewritten document is clean.
    let fixed = fix_to_fixpoint("$$a + b$$\n\n$$c$$\n");
    assert_eq!(fixed, "\\[a + b\\]\n\n\\[c\\]\n");
    let remaining: Vec<_> = check_document(Path::new("doc.tex"), &fixed, LatexFlavor::Document)
        .into_iter()
        .filter(|d| d.rule == "dollar-display-math")
        .collect();
    assert!(
        remaining.is_empty(),
        "expected a clean re-lint, got: {remaining:?}"
    );
}

#[test]
fn dollar_display_fix_is_correct() {
    for case in ["$$x = y$$\n", "$$\n  a + b\n$$\n", "\\[x = y\\]\n", "$x$\n"] {
        assert_fix_is_correct(case);
    }
}

#[test]
fn missing_nbsp_fix_is_correct() {
    // The tie fix is `Unsafe` (it alters line-breaking); `fix_to_fixpoint`
    // applies unsafe fixes, so this exercises parse-clean + losslessness on it.
    for case in ["Figure \\ref{x}\n", "see \\cite{a}\n", "Eq. \\eqref{z}\n"] {
        assert_fix_is_correct(case);
    }
}

#[test]
fn missing_nbsp_fix_clears_the_finding() {
    let fixed = fix_to_fixpoint("Figure \\ref{x}\n");
    assert_eq!(fixed, "Figure~\\ref{x}\n");
    let remaining: Vec<_> = check_document(Path::new("doc.tex"), &fixed, LatexFlavor::Document)
        .into_iter()
        .filter(|d| d.rule == "missing-nonbreaking-space")
        .collect();
    assert!(
        remaining.is_empty(),
        "expected a clean re-lint, got: {remaining:?}"
    );
}

#[test]
fn missing_nbsp_skipped_without_unsafe_opt_in() {
    // The CLI's plain `--fix` (no `--unsafe-fixes`) must not insert the tie.
    let src = "Figure \\ref{x}\n";
    let fixes: Vec<_> = check_document(Path::new("doc.tex"), src, LatexFlavor::Document)
        .into_iter()
        .filter_map(|d| d.fix)
        .collect();
    let out = apply_fixes(src, &fixes, false);
    assert_eq!(out.output, src, "unsafe tie fix must be skipped");
}