cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
Documentation
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! Raw-source-text scanning for the three `G3` rules (see todo.md §3.G G3)
//! that `syn` cannot see: `conversational-artifact`, `restating-comment`,
//! `step-comment-inflation`. `syn` discards regular `//`/`/* */` comments
//! entirely during parsing — only `///`/`//!` doc comments survive, desugared
//! into `#[doc = "..."]` attributes — so there is no AST node a `Visit`
//! implementation could hook into for a plain comment. This module instead
//! runs a small line-by-line scanner over the original source text,
//! independent of `syn::parse_file`, and is invoked once per file from
//! [`crate::rules::slop::analyze_file`] alongside the `syn`-based [`crate::rules::slop`]
//! checks.
//!
//! Two accepted v1 limitations, both documented again at their point of use
//! below: [`extract_comments`] does not handle nested `/* /* */ */` block
//! comments (Rust's own lexer nests them; this heuristic scanner doesn't),
//! and consecutive `//` lines are never joined into one logical comment
//! block — each line is scanned independently.

use std::path::Path;

use crate::finding::{Finding, Location, Origin, Severity};
use crate::rules::slop::ItemSpan;

/// One `//`/`///`/`//!` or `/* */`/`/** */`/`/*! */` comment, as found by
/// [`extract_comments`]. `pub(crate)`: also read by [`crate::rules::security`]'s
/// `unsafe-surface` detector, which needs the same raw-source-text comment
/// spans to find a `// SAFETY:` comment adjacent to an `unsafe { .. }` block
/// — `syn` discards plain comments just as it does here, so that detector
/// reuses this scanner rather than duplicating it.
pub(crate) struct CommentSpan {
    pub(crate) start_line: usize,
    pub(crate) end_line: usize,
    pub(crate) text: String,
    pub(crate) is_doc: bool,
}

/// Which comment marker [`find_comment_start`] found.
#[derive(PartialEq, Eq)]
enum CommentMarker {
    Line,
    Block,
}

/// Finds the earliest `//` or `/*` in `text` that isn't inside a string
/// literal. `in_string` is tracked with a simple unescaped-`"` toggle (a
/// backslash-count-parity check), not full Rust string-literal lexing — good
/// enough to keep `"http://example.com"` from being mistaken for a line
/// comment, not a general-purpose lexer.
fn find_comment_start(text: &str) -> Option<(usize, CommentMarker)> {
    let bytes = text.as_bytes();
    let mut in_string = false;
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if c == b'"' {
            let mut backslashes = 0;
            let mut j = i;
            while j > 0 && bytes[j - 1] == b'\\' {
                backslashes += 1;
                j -= 1;
            }
            if backslashes % 2 == 0 {
                in_string = !in_string;
            }
            i += 1;
            continue;
        }
        if !in_string && c == b'/' && i + 1 < bytes.len() {
            if bytes[i + 1] == b'/' {
                return Some((i, CommentMarker::Line));
            }
            if bytes[i + 1] == b'*' {
                return Some((i, CommentMarker::Block));
            }
        }
        i += 1;
    }
    None
}

/// Single left-to-right, line-by-line scan of `source`, carrying an
/// `in_block_comment` flag across lines so a `/* ... */` that spans multiple
/// lines is still returned as one [`CommentSpan`]. Does NOT handle nested
/// `/* /* */ */` block comments — the first `*/` closes the outermost
/// comment, unlike `rustc`'s own nesting lexer. This is an accepted v1
/// limitation of a heuristic scanner, not a parser. `pub(crate)`: see
/// [`CommentSpan`].
pub(crate) fn extract_comments(source: &str) -> Vec<CommentSpan> {
    let mut spans = Vec::new();
    let mut in_block_comment = false;
    let mut block_start_line = 0usize;
    let mut block_is_doc = false;
    let mut block_text = String::new();

    for (idx, line) in source.lines().enumerate() {
        let line_no = idx + 1;
        let mut rest = line;

        loop {
            if in_block_comment {
                if let Some(end) = rest.find("*/") {
                    let before = rest[..end].trim();
                    if !before.is_empty() {
                        block_text.push(' ');
                        block_text.push_str(before);
                    }
                    spans.push(CommentSpan {
                        start_line: block_start_line,
                        end_line: line_no,
                        text: block_text.trim().to_string(),
                        is_doc: block_is_doc,
                    });
                    in_block_comment = false;
                    block_text.clear();
                    rest = &rest[end + 2..];
                    continue;
                }
                let trimmed = rest.trim();
                if !trimmed.is_empty() {
                    block_text.push(' ');
                    block_text.push_str(trimmed);
                }
                break;
            }

            match find_comment_start(rest) {
                Some((pos, CommentMarker::Line)) => {
                    let marker = &rest[pos..];
                    let is_doc = (marker.starts_with("///") && !marker.starts_with("////"))
                        || marker.starts_with("//!");
                    spans.push(CommentSpan {
                        start_line: line_no,
                        end_line: line_no,
                        text: rest[pos + 2..].trim().to_string(),
                        is_doc,
                    });
                    break;
                }
                Some((pos, CommentMarker::Block)) => {
                    let marker = &rest[pos..];
                    block_is_doc = marker.starts_with("/**") || marker.starts_with("/*!");
                    block_start_line = line_no;
                    in_block_comment = true;
                    rest = &rest[pos + 2..];
                }
                None => break,
            }
        }
    }

    spans
}

/// Returns the innermost item (smallest line span) among `item_spans` whose
/// range contains `line`, or `file`'s path if none contains it.
fn nearest_item_path(item_spans: &[ItemSpan], line: usize, file: &Path) -> String {
    item_spans
        .iter()
        .filter(|span| span.start_line <= line && line <= span.end_line)
        .min_by_key(|span| span.end_line - span.start_line)
        .map(|span| span.item_path.clone())
        .unwrap_or_else(|| file.display().to_string())
}

/// Builds a `Finding` for a raw-text match. There's no `proc_macro2::Span`
/// available here (these findings come from a plain line scan, not `syn`),
/// so the column is hardcoded to `1` — a known simplification, since these
/// are line-based, not token-based, findings.
fn build_finding(
    rule: &'static str,
    line: usize,
    file: &Path,
    item_spans: &[ItemSpan],
    severity: Severity,
    evidence: Option<serde_json::Value>,
) -> Finding {
    let rule = crate::finding::RuleId::from(rule);
    let evidence_class = crate::finding::evidence_class_for_rule(&rule);
    Finding::new(
        format!("{rule}:{}:{line}:1", file.display()),
        rule,
        severity,
        Location {
            file: file.to_path_buf(),
            line: crate::finding::OneBasedLine::new(line)
                .expect("text-scan line numbers are 1-based"),
            item_path: nearest_item_path(item_spans, line, file),
        },
        evidence_class,
        Origin::Code,
        evidence,
    )
}

/// Lowercases `text` and splits it on non-alphanumeric boundaries (naturally
/// splits `snake_case` on `_`, since `_` isn't alphanumeric). Kept local —
/// `crate::rules::slop` has its own copy for `doc-restates-signature`, not shared,
/// since it's a three-line helper and the two modules otherwise have no
/// reason to depend on each other.
fn tokenize(text: &str) -> Vec<String> {
    text.to_lowercase()
        .split(|c: char| !c.is_alphanumeric())
        .filter(|token| !token.is_empty())
        .map(str::to_string)
        .collect()
}

/// Runs the three raw-text `G3` matchers over every comment in `source` and
/// returns their combined findings.
pub(crate) fn scan_comments(source: &str, item_spans: &[ItemSpan], file: &Path) -> Vec<Finding> {
    let comments = extract_comments(source);
    let source_lines: Vec<&str> = source.lines().collect();

    let mut findings = Vec::new();
    findings.extend(conversational_artifact_findings(
        &comments, item_spans, file,
    ));
    findings.extend(step_comment_inflation_findings(
        &comments,
        &source_lines,
        item_spans,
        file,
    ));
    findings.extend(restating_comment_findings(
        &comments,
        &source_lines,
        item_spans,
        file,
    ));
    findings
}

/// Near-certain AI-assistant framing leaking into a comment (see todo.md
/// §3.G `conversational-artifact`). Fires regardless of where in the comment
/// the phrase appears.
pub(crate) const CONVERSATIONAL_TIER1: &[&str] = &[
    "as an ai",
    "as an ai language model",
    "as a language model",
    "i'm an ai",
    "i cannot browse the internet",
];

/// Plausible but weaker prose habits (see todo.md §3.G
/// `conversational-artifact`). Only counted if the phrase starts within the
/// first 8 whitespace-separated words of the comment — mitigates legitimate
/// mid-sentence technical usage (e.g. "here is" showing up deep in an
/// otherwise unremarkable explanation).
pub(crate) const CONVERSATIONAL_TIER2: &[&str] = &[
    "here is",
    "here's",
    "note that this is a simplified",
    "in a real implementation",
    "in a production implementation",
    "for the purposes of this example",
];

/// The whitespace-separated word index at which `pos` (a byte offset into
/// `text`) falls — i.e. how many whole words precede it.
fn word_index_at(text: &str, pos: usize) -> usize {
    text[..pos].split_whitespace().count()
}

/// Whether a quote character (`"` or `` ` ``) sits within a couple of
/// characters of the phrase boundary on the side `chars` walks toward,
/// skipping over intervening non-alphanumeric punctuation (e.g. the `(` in
/// `("as an AI")`) — used by [`phrase_at_word_boundary`] to recognize a
/// trigger phrase that is itself the *subject* of a quoting comment (like
/// this rule's own `exclusions` text in `rule_registry.rs`, which quotes
/// `"as an AI"` to explain the rule rather than uttering it as a
/// disclaimer) rather than a live disclaimer. Bails out as soon as it hits
/// an alphanumeric character, since that means no quote mark is adjacent.
fn quote_char_nearby(mut chars: impl Iterator<Item = char>) -> bool {
    for _ in 0..3 {
        match chars.next() {
            Some(c) if c == '"' || c == '`' => return true,
            Some(c) if c.is_alphanumeric() => return false,
            Some(_) => continue,
            None => return false,
        }
    }
    false
}

/// The byte offset of the first occurrence of `phrase` in `haystack` that is
/// bounded by non-alphanumeric characters (or the string's own start/end) on
/// both sides — a plain substring search would also match `"here is"`/
/// `"here's"` inside the common words `"there is"`/`"there's"`/`"where is"`
/// (see `conversational-artifact`, todo.md §3.G G3) — and that is not
/// quoted meta-discussion of the phrase itself (see [`quote_char_nearby`]):
/// a comment that quotes `"as an AI"` to explain why the rule exists is not
/// itself an AI disclaimer, so a match immediately enclosed by matching
/// quote marks on both sides is skipped in favor of the next candidate.
fn phrase_at_word_boundary(haystack: &str, phrase: &str) -> Option<usize> {
    let mut start = 0;
    while let Some(offset) = haystack[start..].find(phrase) {
        let match_start = start + offset;
        let match_end = match_start + phrase.len();
        let before_ok = !haystack[..match_start]
            .chars()
            .next_back()
            .is_some_and(|c| c.is_alphanumeric());
        let after_ok = !haystack[match_end..]
            .chars()
            .next()
            .is_some_and(|c| c.is_alphanumeric());
        let quoted = quote_char_nearby(haystack[..match_start].chars().rev())
            && quote_char_nearby(haystack[match_end..].chars());
        if before_ok && after_ok && !quoted {
            return Some(match_start);
        }
        start = match_start + 1;
        if start >= haystack.len() {
            break;
        }
    }
    None
}

/// `conversational-artifact` (see todo.md §3.G): AI-assistant phrase leakage
/// into a plain comment. Only non-doc [`CommentSpan`]s are checked —
/// legitimate stub-limitation prose like "in a real implementation you would
/// also handle X" is common and appropriate in a `///` doc comment
/// explaining a stub, and excluding doc comments entirely sidesteps that
/// false-positive class. A phrase quoted in the comment (see
/// [`quote_char_nearby`]) to meta-discuss the rule itself — rather than
/// utter it as a disclaimer — is also excluded, which is why this rule does
/// not self-trigger on its own `exclusions` text in `rule_registry.rs`. For
/// a multi-line run of consecutive `//` comments, each line is scanned
/// independently — they are deliberately not joined into one logical block
/// (v1 scope-narrowing).
fn conversational_artifact_findings(
    comments: &[CommentSpan],
    item_spans: &[ItemSpan],
    file: &Path,
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for comment in comments {
        if comment.is_doc {
            continue;
        }
        let lower = comment.text.to_lowercase();

        if CONVERSATIONAL_TIER1
            .iter()
            .any(|phrase| phrase_at_word_boundary(&lower, phrase).is_some())
        {
            findings.push(build_finding(
                crate::rules::slop::CONVERSATIONAL_ARTIFACT_RULE,
                comment.start_line,
                file,
                item_spans,
                Severity::Warn,
                None,
            ));
            continue;
        }

        let hit = CONVERSATIONAL_TIER2.iter().any(|phrase| {
            phrase_at_word_boundary(&lower, phrase)
                .is_some_and(|pos| word_index_at(&lower, pos) < 8)
        });
        if hit {
            findings.push(build_finding(
                crate::rules::slop::CONVERSATIONAL_ARTIFACT_RULE,
                comment.start_line,
                file,
                item_spans,
                Severity::Info,
                None,
            ));
        }
    }
    findings
}

/// Whether `text`, trimmed, starts with the literal `Step\s*\d+` shape,
/// case-insensitive (`"Step 1:"`, `"Step1"`, `"STEP 2 -"`) — and if so, the
/// step number. Deliberately narrow: bare `1)`/`1.` numbering is not
/// recognized (too generic — would false-positive on legitimate ordered
/// documentation).
fn step_number(text: &str) -> Option<u32> {
    let trimmed = text.trim_start();
    // `get(..4)` instead of `[..4]`: byte 4 may fall inside a multi-byte
    // character (e.g. a comment starting `v1 — …`), which would panic.
    let prefix = trimmed.get(..4)?;
    if !prefix.eq_ignore_ascii_case("step") {
        return None;
    }
    let rest = trimmed[4..].trim_start();
    let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
    if digits.is_empty() {
        return None;
    }
    digits.parse().ok()
}

/// One `// Step N: ...`-shaped comment, as classified by [`step_number`].
struct StepComment {
    number: u32,
    start_line: usize,
    item_path: String,
}

/// Count of non-blank source lines strictly between `from_line` and
/// `to_line` (both 1-indexed, exclusive on both ends).
fn non_blank_lines_between(source_lines: &[&str], from_line: usize, to_line: usize) -> usize {
    if to_line <= from_line + 1 {
        return 0;
    }
    source_lines[from_line..to_line - 1]
        .iter()
        .filter(|line| !line.trim().is_empty())
        .count()
}

/// `step-comment-inflation` (see todo.md §3.G): a `// Step N:` comment chain
/// of three or more, grouped by enclosing item. Only non-doc
/// [`CommentSpan`]s are checked. A run continues as long as the step number
/// increases by exactly 1, the enclosing item stays the same, and at most 2
/// non-blank lines separate consecutive steps; a chain of 1-2 is normal and
/// not flagged.
fn step_comment_inflation_findings(
    comments: &[CommentSpan],
    source_lines: &[&str],
    item_spans: &[ItemSpan],
    file: &Path,
) -> Vec<Finding> {
    let steps: Vec<StepComment> = comments
        .iter()
        .filter(|comment| !comment.is_doc)
        .filter_map(|comment| {
            step_number(&comment.text).map(|number| StepComment {
                number,
                start_line: comment.start_line,
                item_path: nearest_item_path(item_spans, comment.start_line, file),
            })
        })
        .collect();

    let mut findings = Vec::new();
    let mut chain: Vec<&StepComment> = Vec::new();

    for step in &steps {
        let continues_chain = match chain.last() {
            Some(last) => {
                last.item_path == step.item_path
                    && step.number == last.number + 1
                    && non_blank_lines_between(source_lines, last.start_line, step.start_line) <= 2
            }
            None => true,
        };
        if !continues_chain {
            flush_step_chain(&mut chain, &mut findings, file, item_spans);
        }
        chain.push(step);
    }
    flush_step_chain(&mut chain, &mut findings, file, item_spans);

    findings
}

/// Emits one finding for `chain` if it has 3 or more steps, then clears it.
fn flush_step_chain(
    chain: &mut Vec<&StepComment>,
    findings: &mut Vec<Finding>,
    file: &Path,
    item_spans: &[ItemSpan],
) {
    if chain.len() >= 3 {
        let lines: Vec<usize> = chain.iter().map(|step| step.start_line).collect();
        findings.push(build_finding(
            crate::rules::slop::STEP_COMMENT_INFLATION_RULE,
            chain[0].start_line,
            file,
            item_spans,
            Severity::Info,
            Some(serde_json::json!({ "chain_length": chain.len(), "lines": lines })),
        ));
    }
    chain.clear();
}

/// Stopwords dropped before comparing a comment against the code line it
/// precedes (see todo.md §3.G `restating-comment`).
const RESTATING_STOPWORDS: &[&str] = &[
    "the", "a", "an", "to", "of", "and", "this", "is", "let", "mut", "fn", "if", "else", "return",
];

/// Tokenizes `text` and drops [`RESTATING_STOPWORDS`].
fn content_tokens(text: &str) -> std::collections::HashSet<String> {
    tokenize(text)
        .into_iter()
        .filter(|token| !RESTATING_STOPWORDS.contains(&token.as_str()))
        .collect()
}

/// The first non-blank line after 1-indexed `after_line`, if any.
fn next_non_blank_line<'a>(source_lines: &[&'a str], after_line: usize) -> Option<&'a str> {
    source_lines
        .iter()
        .skip(after_line)
        .find(|line| !line.trim().is_empty())
        .copied()
}

/// Item-declaration prefixes that, when the next code line starts with one,
/// exclude that comment from `restating-comment` — keeps the check scoped to
/// statement-level restating inside function bodies, not doc-comment-shaped
/// prose sitting above an item declaration.
const RESTATING_ITEM_KEYWORDS: &[&str] = &[
    "fn ", "pub fn", "struct ", "enum ", "impl ", "trait ", "mod ", "#[",
];

/// `restating-comment` (see todo.md §3.G): a single-line comment that only
/// paraphrases the next line of code. Multi-line block comments are excluded
/// from v1 (scope limitation) — only single-line (`start_line == end_line`),
/// non-doc [`CommentSpan`]s are checked. Requires both a comment-token floor
/// (≥4, post-stopword) and a code-line-token floor (≥3, post-stopword)
/// before scoring at all — the mitigation for short, legitimate comments
/// like `// increment i` above `i += 1;`, which never reach the floor.
fn restating_comment_findings(
    comments: &[CommentSpan],
    source_lines: &[&str],
    item_spans: &[ItemSpan],
    file: &Path,
) -> Vec<Finding> {
    let mut findings = Vec::new();
    for comment in comments {
        if comment.is_doc || comment.start_line != comment.end_line {
            continue;
        }
        let Some(code_line) = next_non_blank_line(source_lines, comment.end_line) else {
            continue;
        };
        let trimmed_code = code_line.trim();
        if trimmed_code.starts_with("//")
            || trimmed_code.starts_with("/*")
            || RESTATING_ITEM_KEYWORDS
                .iter()
                .any(|keyword| trimmed_code.starts_with(keyword))
        {
            continue;
        }

        let comment_tokens = content_tokens(&comment.text);
        let code_tokens = content_tokens(trimmed_code);
        if comment_tokens.len() < 4 || code_tokens.len() < 3 {
            continue;
        }

        let intersection = comment_tokens.intersection(&code_tokens).count();
        let union = comment_tokens.union(&code_tokens).count();
        if union == 0 {
            continue;
        }
        let similarity = intersection as f32 / union as f32;
        if similarity >= 0.7 {
            findings.push(build_finding(
                crate::rules::slop::RESTATING_COMMENT_RULE,
                comment.start_line,
                file,
                item_spans,
                Severity::Info,
                None,
            ));
        }
    }
    findings
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_multibyte_char_at_byte_four_does_not_panic_step_number() {
        // Regression: `trimmed[..4]` panicked when byte 4 fell inside a
        // multi-byte character, aborting the whole analysis run.
        assert_eq!(step_number("v1 — new format"), None);
        assert_eq!(step_number("äöü"), None);
        assert_eq!(step_number("Step 3:"), Some(3));
    }

    #[test]
    fn string_literal_containing_comment_markers_is_not_a_comment() {
        let spans = extract_comments("let url = \"http://example.com\";\n");
        assert!(spans.is_empty());
    }

    #[test]
    fn line_comment_after_a_string_literal_is_still_found() {
        let spans = extract_comments("let url = \"http://example.com\"; // real comment\n");
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].text, "real comment");
        assert!(!spans[0].is_doc);
    }

    #[test]
    fn triple_slash_is_doc_quadruple_slash_is_not() {
        let spans = extract_comments("/// doc\n//// not doc\n");
        assert_eq!(spans.len(), 2);
        assert!(spans[0].is_doc);
        assert!(!spans[1].is_doc);
    }

    #[test]
    fn block_comment_spans_multiple_lines() {
        let spans = extract_comments("/* line one\nline two */\ncode();\n");
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].start_line, 1);
        assert_eq!(spans[0].end_line, 2);
        assert!(spans[0].text.contains("line one"));
        assert!(spans[0].text.contains("line two"));
    }

    fn findings_for(source: &str, name: &str) -> Vec<Finding> {
        let dir = crate::test_util::TempDir::new(name);
        let file = dir.join("lib.rs");
        std::fs::write(&file, source).unwrap();
        crate::rules::slop::analyze_file(&file, false).unwrap()
    }

    fn rule_findings<'a>(findings: &'a [Finding], rule: &str) -> Vec<&'a Finding> {
        findings.iter().filter(|f| f.rule == rule).collect()
    }

    /// Documented v1 limitation #1 (see module doc): [`extract_comments`]
    /// does not handle nested `/* /* */ */` block comments the way Rust's
    /// own lexer does — it closes at the *first* `*/` it finds, not the one
    /// matching the true nesting depth. Real Rust nests this comment one
    /// level deep (open, open, close-inner, close-outer), so the whole
    /// thing — including the "in a real implementation" sentence — is one
    /// comment invisible to `rustc`. This scanner instead closes after
    /// `/* inner note */`, leaving the rest of the (still, to `rustc`,
    /// commented-out) text to fall through as unrecognized, un-scanned
    /// content: no `CommentSpan` at all is produced for it, so a trigger
    /// phrase sitting there is never even considered — not "not matched",
    /// but silently never looked at.
    #[test]
    fn nested_block_comment_swallows_trailing_text_in_extract_comments() {
        let spans = extract_comments(
            "/* outer doc\n/* inner note */\nin a real implementation, this text sits inside the outer comment but the scanner already closed it\nstill more hidden text */\n",
        );
        assert_eq!(spans.len(), 1);
        assert!(!spans[0].text.contains("in a real implementation"));
    }

    /// Same limitation as above, followed through the full pipeline: the
    /// file parses fine (Rust really does nest block comments, so `syn`
    /// sees one big comment followed by `fn f() {}`), but
    /// `conversational-artifact` never fires on the Tier-2 trigger phrase
    /// "in a real implementation" because [`extract_comments`] never
    /// produced a `CommentSpan` covering it.
    #[test]
    fn nested_block_comment_hides_trigger_from_conversational_artifact() {
        let findings = findings_for(
            "/* outer doc\n/* inner note */\nin a real implementation, this text sits inside the outer comment but the scanner already closed it\nstill more hidden text */\nfn f() {}\n",
            "slop-text-nested-block-comment",
        );
        assert!(
            rule_findings(&findings, crate::rules::slop::CONVERSATIONAL_ARTIFACT_RULE).is_empty()
        );
    }

    /// Documented v1 limitation #2 (see module doc): consecutive `//` lines
    /// are never joined into one logical comment block — each line becomes
    /// its own [`CommentSpan`], scanned independently. Here a Tier-1
    /// `conversational-artifact` phrase ("i'm an ai") is split across two
    /// consecutive `//` lines: `// I'm an` / `// AI assistant explaining
    /// this limitation in detail here.`. Read together, the phrase is
    /// obviously present; scanned line-by-line, neither line's text alone
    /// contains it, so the rule produces zero findings.
    #[test]
    fn consecutive_line_comments_are_never_joined_into_one_block() {
        let findings = findings_for(
            "fn f() {\n    // I'm an\n    // AI assistant explaining this limitation in detail here.\n    let _ = 1;\n}\n",
            "slop-text-consecutive-line-comments",
        );
        assert!(
            rule_findings(&findings, crate::rules::slop::CONVERSATIONAL_ARTIFACT_RULE).is_empty()
        );
    }

    /// A comment that *quotes* a trigger phrase to meta-discuss the rule
    /// itself — the exact shape of `rule_registry.rs`'s own
    /// `conversational-artifact` `exclusions` doc comment, which quotes
    /// `"as an AI"` while explaining why a string literal elsewhere doesn't
    /// self-trigger — must not fire. Without the quote check this comment
    /// used to produce a false-positive finding against judge's own
    /// codebase.
    #[test]
    fn quoted_trigger_phrase_used_for_meta_discussion_does_not_fire() {
        let findings = findings_for(
            "// The trigger phrase (\"as an AI\") lives inside a Rust string literal\n// here, not a real comment, so this can't self-trigger the rule.\nfn f() {}\n",
            "slop-text-quoted-trigger-phrase",
        );
        assert!(
            rule_findings(&findings, crate::rules::slop::CONVERSATIONAL_ARTIFACT_RULE).is_empty()
        );
    }

    /// Regression guard for the fix above: an unquoted, genuine disclaimer
    /// must still fire — the quote exclusion must not weaken real
    /// detection.
    #[test]
    fn unquoted_genuine_disclaimer_still_fires() {
        let findings = findings_for(
            "fn f() {\n    // As an AI, I can't verify this.\n    let _ = 1;\n}\n",
            "slop-text-unquoted-disclaimer",
        );
        assert_eq!(
            rule_findings(&findings, crate::rules::slop::CONVERSATIONAL_ARTIFACT_RULE).len(),
            1
        );
    }
}