rust-llm-tidy-cli 0.6.0

CLI for linting and tidying Rust, C#, and documentation source.
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! C# lint tests: the XML doc dialect over the same lint codes as Rust.
//!
//! The lint tests run the built CLI binary with `--include lints` on a
//! fixture in `tests/fixtures/doc/csharp/`; the JSON record tests also
//! cover `--include reorder` over `tests/fixtures/reorder/csharp/`.
//!
//! The shared runner helpers live in `mod.rs`.

use super::{assert_has_diagnostic, manifest_dir, reorder_fixture_dir, run_command};

// ── DOC001: missing doc comments ──────────────────────────────────

/// DOC001 flags every undocumented non-private member kind and skips
/// private, unmodified, and documented members.
#[test]
fn csharp_doc001_flags_undocumented_non_private_members() {
    let (stderr, exit) = run_csharp_fixture("doc001_missing_docs.cs");
    assert_ne!(exit, 0, "DOC001 errors must fail the run");

    for name in [
        "Undocumented",
        "Guarded",
        "Cached",
        "Shape",
        "Kind",
        "Notify",
        "Changed",
        "Alpha",
    ] {
        assert_has_diagnostic(&stderr, "DOC001", Some(name));
    }
    for clean in [
        "Hidden",
        "InternalDefault",
        "Documented",
        "IBehavior",
        "Apply",
    ] {
        assert!(
            !stderr.contains(&format!("`{clean}`")),
            "`{clean}` must not be flagged:\n{stderr}"
        );
    }
    assert_eq!(
        stderr.matches("DOC001").count(),
        8,
        "expected exactly 8 DOC001 findings:\n{stderr}"
    );
}

// ── DOC002: missing `<exception>` tag ────────────────────────────

/// DOC002 recursion: a caller with no `throw` of its own is flagged
/// for calling a same-file thrower, transitively; the private thrower,
/// framework calls, and tagged callers stay silent. Findings keep
/// document order and error severity.
#[test]
fn csharp_doc002_errors_on_indirect_throwers() {
    let (stderr, exit) = run_csharp_fixture("doc002_indirect_exception.cs");

    assert_ne!(exit, 0, "DOC002 errors must fail the run:\n{stderr}");
    assert!(
        stderr.contains("error[DOC002]"),
        "DOC002 carries error severity:\n{stderr}"
    );
    assert_has_diagnostic(&stderr, "DOC002", Some("Load"));
    assert_has_diagnostic(&stderr, "DOC002", Some("LoadTwice"));
    assert!(
        !stderr.contains("`Validate`")
            && !stderr.contains("`Parse`")
            && !stderr.contains("`LoadGuarded`"),
        "private throwers, framework calls, and tagged callers pass:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("DOC002").count(),
        2,
        "expected exactly 2 DOC002 findings:\n{stderr}"
    );
    let direct = stderr.find("(fn `Load`)").expect("Load must be named");
    let transitive = stderr
        .find("(fn `LoadTwice`)")
        .expect("LoadTwice must be named");
    assert!(
        direct < transitive,
        "findings stay in document order:\n{stderr}"
    );
}

/// DOC002 errors on the documented non-private thrower without an
/// `<exception>` tag; the tagged and private throwers pass.
#[test]
fn csharp_doc002_errors_on_untagged_throwers() {
    let (stderr, exit) = run_csharp_fixture("doc002_missing_exception.cs");

    assert_ne!(exit, 0, "DOC002 errors must fail the run:\n{stderr}");
    assert_has_diagnostic(&stderr, "DOC002", Some("Untagged"));
    assert!(
        stderr.contains("error[DOC002]"),
        "DOC002 carries error severity:\n{stderr}"
    );
    assert!(
        !stderr.contains("`Tagged`") && !stderr.contains("`Hidden`"),
        "tagged and private throwers pass:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("DOC002").count(),
        1,
        "expected exactly 1 DOC002 finding:\n{stderr}"
    );
}

/// A loose caller has no foreign facts; vague tags warn without failing a
/// paired invocation.
#[test]
fn csharp_doc002_should_degrade_for_loose_files_and_keep_doc003_warning_exit() {
    let caller = super::temp_file("cs");
    let helper = super::temp_file("cs");
    std::fs::write(
        &caller,
        "class A {\n/// <summary>Loads a value.</summary>\npublic void Load() { T.Helper(); }\n}",
    )
    .unwrap();
    std::fs::write(&helper, "class T { void Helper() { throw new E(); } }").unwrap();

    let loose = run_command(&["--include", "lints"], &caller);
    std::fs::write(
        &caller,
        "class A {\n/// <exception>Failure.</exception>\npublic void Load() { T.Helper(); }\n}",
    )
    .unwrap();
    let paired = std::process::Command::new(super::binary())
        .args(["--no-config", "--include", "lints"])
        .arg(&caller)
        .arg(&helper)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&paired.stderr);
    std::fs::remove_file(caller).unwrap();
    std::fs::remove_file(helper).unwrap();

    assert!(loose.status.success());
    assert!(loose.stderr.is_empty());
    assert!(paired.status.success(), "{stderr}");
    assert_eq!(stderr.matches("warning[DOC003]").count(), 1, "{stderr}");
    assert_eq!(stderr.matches("warning[").count(), 1, "{stderr}");
    assert!(!stderr.contains("error["), "{stderr}");
}

/// Explicit file pairs and project-scoped single inputs report the same
/// cross-file error.
#[test]
fn csharp_doc002_should_find_project_throwers_from_single_or_multiple_inputs() {
    let root = manifest_dir().join("tests/fixtures/doc/csharp/doc002_cross_file");
    let caller = root.join("caller/Caller.cs");
    let thrower = root.join("thrower/Thrower.cs");

    for multiple in [false, true] {
        let mut command = std::process::Command::new(super::binary());
        command
            .args(["--no-config", "--include", "lints"])
            .arg(&caller);
        if multiple {
            command.arg(&thrower);
        }

        let output = command.output().unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr);

        assert!(!output.status.success(), "{stderr}");
        assert_eq!(stderr.matches("error[DOC002]").count(), 1, "{stderr}");
        assert_eq!(stderr.matches("(fn `Load`)").count(), 1, "{stderr}");
        assert_eq!(stderr.matches("error[").count(), 1, "{stderr}");
        assert!(!stderr.contains("warning["), "{stderr}");
    }
}

/// Real member movement preserves the same current-source lint records as a
/// fresh lint pass.
#[test]
fn csharp_doc002_should_refresh_diagnostic_positions_after_reorder() {
    let caller = super::temp_file("cs");
    let helper = super::temp_file("cs");
    let source = "class A\n{\n    /// <summary>Loads first.</summary>\n    public void First() { T.Helper(); }\n    /// <summary>Loads second.</summary>\n    public void Second() { First(); }\n}\n";
    std::fs::write(&caller, source).unwrap();
    std::fs::write(&helper, "class T { void Helper() { throw new E(); } }").unwrap();
    let run = |include| {
        std::process::Command::new(super::binary())
            .args(["--no-config", "--output-mode", "json", "--include", include])
            .arg(&caller)
            .arg(&helper)
            .output()
            .unwrap()
    };

    let combined = std::process::Command::new(super::binary())
        .args([
            "--no-config",
            "--output-mode",
            "json",
            "--include",
            "reorder",
            "--include",
            "lints",
        ])
        .arg(&caller)
        .arg(&helper)
        .output()
        .unwrap();
    let current = std::fs::read_to_string(&caller).unwrap();
    let fresh = run("lints");
    let diagnostics = |output: &[u8]| {
        let records: Vec<serde_json::Value> = serde_json::from_slice(output).unwrap();
        records
            .into_iter()
            .filter(|record| record["code"] == "DOC002")
            .collect::<Vec<_>>()
    };
    let combined_records = diagnostics(&combined.stdout);
    let fresh_records = diagnostics(&fresh.stdout);
    std::fs::remove_file(&caller).unwrap();
    std::fs::remove_file(&helper).unwrap();

    assert_ne!(current, source);
    assert!(current.find("void Second").unwrap() < current.find("void First").unwrap());
    assert_eq!(combined.status.code(), fresh.status.code());
    assert!(!combined.status.success());
    assert_eq!(combined_records.len(), 2);
    assert_eq!(combined_records, fresh_records);
    assert_eq!(combined_records[0]["line"], 3);
    assert_eq!(combined_records[1]["line"], 5);
}

// ── DOC003: vague `<exception>` cref ─────────────────────────────

/// DOC003 warns when `<exception>` tags carry no concrete `cref`.
#[test]
fn csharp_doc003_warns_on_vague_exception_crefs() {
    let (stderr, exit) = run_csharp_fixture("doc003_vague_exception.cs");

    assert_eq!(exit, 0, "DOC003 warnings must not fail the run");
    assert_has_diagnostic(&stderr, "DOC003", Some("Vague"));
    assert!(
        !stderr.contains("`Concrete`"),
        "a concrete cref passes:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("DOC003").count(),
        1,
        "expected exactly 1 DOC003 finding:\n{stderr}"
    );
}

// ── DOC004: missing `<param>` tag ────────────────────────────────

/// DOC004 warns on the parameterized member without `<param>` tags.
#[test]
fn csharp_doc004_warns_on_missing_param_tags() {
    let (stderr, exit) = run_csharp_fixture("doc004_missing_param.cs");

    assert_eq!(exit, 0, "DOC004 warnings must not fail the run");
    assert_has_diagnostic(&stderr, "DOC004", Some("Greet"));
    assert!(
        !stderr.contains("`Greeted`") && !stderr.contains("`NoArgs`"),
        "tagged and parameterless members pass:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("DOC004").count(),
        1,
        "expected exactly 1 DOC004 finding:\n{stderr}"
    );
}

// ── DOC005: undocumented parameter ────────────────────────────────

/// DOC005 names the parameter the `<param>` tags omitted.
#[test]
fn csharp_doc005_names_the_undocumented_param() {
    let (stderr, exit) = run_csharp_fixture("doc005_undocumented_param.cs");

    assert_eq!(exit, 0, "DOC005 warnings must not fail the run");
    assert_has_diagnostic(&stderr, "DOC005", Some("Build"));
    assert!(
        stderr.contains("`format`"),
        "DOC005 must name the omitted parameter:\n{stderr}"
    );
    assert!(
        !stderr.contains("`Built`"),
        "fully documented members pass:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("DOC005").count(),
        1,
        "expected exactly 1 DOC005 finding:\n{stderr}"
    );
}

// ── DOC006: doc-comment placeholders ──────────────────────────────

/// DOC006 warns on TODO/FIXME/TBD placeholder markers in C# doc comments.
#[test]
fn csharp_doc006_warns_on_placeholders() {
    let (stderr, exit) = run_csharp_fixture("doc006_placeholders.cs");

    assert_eq!(exit, 0, "DOC006 warnings must not fail the run");
    for name in ["Todo", "Fixme", "Tbd"] {
        assert_has_diagnostic(&stderr, "DOC006", Some(name));
    }
    assert!(
        !stderr.contains("`Done`"),
        "described members pass:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("DOC006").count(),
        3,
        "expected exactly 3 DOC006 findings:\n{stderr}"
    );
}

// ── JSON records ─────────────────────────────────────────────────

/// `--include reorder --output-mode json --dry-run` on a `.cs` file
/// records the would-be using hoist and member reorder with
/// `severity: "success"` and no title, exactly like the Rust reorder
/// records.
#[test]
fn csharp_json_dry_run_records_the_member_reorder() {
    let path = reorder_fixture_dir()
        .join("csharp")
        .join("reorder_cs_before.cs");
    let output = run_command(
        &["--include", "reorder", "--output-mode", "json", "--dry-run"],
        &path,
    );

    assert!(
        output.status.success(),
        "JSON dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let records: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout must parse as JSON: {e}\n{stdout}"));
    let array = records.as_array().expect("output must be an array");
    assert_eq!(
        array.len(),
        2,
        "expected the using hoist and the member reorder:\n{stdout}"
    );
    for rec in array {
        assert_eq!(rec["severity"], "success");
        assert_eq!(rec["code"], "REORDER");
        assert!(
            rec["title"].is_null(),
            "change records carry no title:\n{stdout}"
        );
    }
    assert!(
        array
            .iter()
            .any(|r| r["item_kind"] == "class" && r["item_name"] == "OrderService"),
        "one record names the reordered class:\n{stdout}"
    );
    assert!(
        array.iter().any(|r| r["item_kind"] == "using"),
        "one record names the hoisted using:\n{stdout}"
    );
}

/// `--output-mode json` on a `.cs` file emits the documented lint record
/// shape: the same field set as Rust findings, with the friendly title.
#[test]
fn csharp_json_output_matches_the_documented_record_shape() {
    let path = csharp_fixture_dir().join("doc004_missing_param.cs");
    let output = run_command(&["--include", "lints", "--output-mode", "json"], &path);

    assert!(
        output.status.success(),
        "warnings-only JSON run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let findings: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout must parse as JSON: {e}\n{stdout}"));
    let array = findings.as_array().expect("output must be an array");
    assert_eq!(
        array.len(),
        1,
        "expected exactly the DOC004 finding:\n{stdout}"
    );

    let keys: std::collections::BTreeSet<&str> = array[0]
        .as_object()
        .expect("the finding is an object")
        .keys()
        .map(String::as_str)
        .collect();
    assert_eq!(
        keys,
        [
            "path",
            "line",
            "severity",
            "code",
            "message",
            "item_kind",
            "item_name",
            "title",
        ]
        .into_iter()
        .collect(),
        "C# findings carry exactly the documented fields: {stdout}"
    );
    assert_eq!(array[0]["severity"], "warning");
    assert_eq!(array[0]["code"], "DOC004");
    assert_eq!(array[0]["title"], "missing `# Arguments` section");
    assert_eq!(array[0]["item_kind"], "fn");
    assert_eq!(array[0]["item_name"], "Greet");
    assert!(array[0]["line"].as_u64().is_some_and(|l| l >= 1));
}

// ── TEST001: test-function naming ─────────────────────────────────

/// TEST001 flags marker-attributed methods with discouraged names and
/// passes the behavioral name.
#[test]
fn csharp_test001_flags_discouraged_names() {
    let (stderr, _exit) = run_csharp_fixture("test001_test_naming.cs");

    for name in ["Test1", "Test_foo", "Case_1", "Test"] {
        assert_has_diagnostic(&stderr, "TEST001", Some(name));
    }
    assert!(
        !stderr
            .lines()
            .any(|l| l.contains("TEST001") && l.contains("ShouldReturnZeroWhenEmpty")),
        "the behavioral name passes:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("TEST001").count(),
        4,
        "expected exactly 4 TEST001 findings:\n{stderr}"
    );
}

// ── Text budgets ─────────────────────────────────────────────────

/// C# text budgets fire with original file lines: TEXT001 errors on an
/// over-budget summary paragraph at its first prose line, and TEXT002
/// warns on a line whose tag-stripped inner text exceeds 80 chars.
#[test]
fn csharp_text_budgets_fire_with_original_lines() {
    let (stderr, exit) = run_csharp_fixture("text-001_text-002_text_budgets.cs");

    assert_ne!(exit, 0, "the TEXT001 error must fail the run:\n{stderr}");
    assert!(
        stderr.contains(":10: error[TEXT001]"),
        "TEXT001 must report at the summary's first prose line:\n{stderr}"
    );
    assert!(
        stderr.contains(":19: warning[TEXT002]"),
        "TEXT002 must report at the over-long measured line:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("TEXT001").count(),
        1,
        "expected exactly 1 TEXT001 finding:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("TEXT002").count(),
        1,
        "expected exactly 1 TEXT002 finding:\n{stderr}"
    );
    assert!(
        !stderr.contains("DOC001") && !stderr.contains("DOC004"),
        "the fixture is otherwise documented:\n{stderr}"
    );
}

/// C# text checks stay quiet on the probe classes: idiomatic XML docs,
/// long `cref`/`name` attribute values, `<code>`/`<example>` blocks, and
/// verbatim string content produce no TEXT001/TEXT002 findings.
#[test]
fn csharp_text_probes_stay_quiet() {
    let (stderr, exit) = run_csharp_fixture("doc_text_quiet_probes.cs");

    assert_eq!(
        exit, 0,
        "the probe fixture must be clean across every C# lint"
    );
    assert!(
        stderr.is_empty(),
        "idiomatic docs and string content must stay unmeasured:\n{stderr}"
    );
}

// ── Helpers ───────────────────────────────────────────────────────

/// Run `rust-llm-tidy --include lints` on a C# fixture and return its
/// (stderr, exit_code).
fn run_csharp_fixture(name: &str) -> (String, i32) {
    let path = csharp_fixture_dir().join(name);
    let output = run_command(&["--include", "lints"], &path);
    (
        String::from_utf8_lossy(&output.stderr).to_string(),
        output.status.code().unwrap_or(-1),
    )
}

/// The directory holding the C# lint fixtures.
fn csharp_fixture_dir() -> std::path::PathBuf {
    manifest_dir()
        .join("tests")
        .join("fixtures")
        .join("doc")
        .join("csharp")
}