uncomment 3.10.0

A CLI tool to remove comments from code using tree-sitter for accurate parsing
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
use crate::ast::visitor::CommentInfo;
use std::borrow::Cow;

#[derive(Debug, Clone)]
pub enum PreservationRule {
    Pattern(Cow<'static, str>),
    PatternCaseInsensitive(Cow<'static, str>),
    Documentation,
    FileHeader,
    Shebang,
}

impl PreservationRule {
    pub fn matches(&self, comment: &CommentInfo, content: &str) -> bool {
        match self {
            PreservationRule::Pattern(pattern) => content.contains(pattern.as_ref()),
            PreservationRule::PatternCaseInsensitive(pattern) => {
                Self::contains_case_insensitive(content, pattern.as_ref())
            }
            PreservationRule::Documentation => self.is_documentation_comment(comment, content),
            PreservationRule::FileHeader => self.is_file_header_comment(comment, content),
            PreservationRule::Shebang => self.is_shebang(comment, content),
        }
    }

    pub fn pattern_matches(&self, pattern: &str) -> bool {
        match self {
            PreservationRule::Pattern(rule_pattern) => rule_pattern.as_ref() == pattern,
            PreservationRule::PatternCaseInsensitive(rule_pattern) => rule_pattern.as_ref() == pattern,
            _ => false,
        }
    }

    /// Every case-insensitive pattern is an ASCII word tag, so this folds over bytes rather than
    /// lowercasing: this runs for each such rule against every comment in the tree, and allocating a
    /// `String` per offset made it the hottest path in a large run. A needle of ASCII bytes cannot
    /// match at a UTF-8 continuation byte, so raw byte windows need no char-boundary check.
    fn contains_case_insensitive(haystack: &str, needle: &str) -> bool {
        if needle.is_empty() {
            return true;
        }
        haystack
            .as_bytes()
            .windows(needle.len())
            .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
    }

    fn is_shebang(&self, comment: &CommentInfo, content: &str) -> bool {
        if comment.node_type.contains("shebang") {
            return true;
        }

        let trimmed = content.trim_start();
        trimmed.starts_with("#!")
    }

    fn is_documentation_comment(&self, comment: &CommentInfo, content: &str) -> bool {
        comment.is_documentation || is_documentation_syntax(&comment.node_type, content)
    }

    fn is_file_header_comment(&self, comment: &CommentInfo, content: &str) -> bool {
        comment.start_row < 10 && Self::looks_like_header(content)
    }

    fn looks_like_header(content: &str) -> bool {
        const HEADER_INDICATORS: &[&str] = &[
            "copyright",
            "license",
            "author",
            "version",
            "file:",
            "description:",
            "created:",
            "modified:",
            "encoding:",
            "auto-generated",
            "autogenerated",
            "generated by",
            "do not edit",
            "don't edit",
            "do not modify",
            "don't modify",
            "@file",
            "@author",
            "@version",
            "@copyright",
            "@license",
            "===",
            "---",
            "***",
        ];

        let lower_content = content.to_lowercase();
        HEADER_INDICATORS
            .iter()
            .any(|&indicator| lower_content.contains(indicator))
    }

    pub fn pattern(pattern: &'static str) -> Self {
        PreservationRule::Pattern(Cow::Borrowed(pattern))
    }

    pub fn pattern_owned(pattern: String) -> Self {
        PreservationRule::Pattern(Cow::Owned(pattern))
    }

    pub fn pattern_ci(pattern: &'static str) -> Self {
        PreservationRule::PatternCaseInsensitive(Cow::Borrowed(pattern))
    }

    pub fn pattern_ci_owned(pattern: String) -> Self {
        PreservationRule::PatternCaseInsensitive(Cow::Owned(pattern))
    }

    pub fn documentation() -> Self {
        PreservationRule::Documentation
    }

    pub fn file_header() -> Self {
        PreservationRule::FileHeader
    }

    pub fn shebang() -> Self {
        PreservationRule::Shebang
    }
}

impl PreservationRule {
    pub fn default_rules() -> Vec<Self> {
        vec![
            Self::pattern_ci("TODO"),
            Self::pattern_ci("FIXME"),
            Self::pattern_ci("HACK"),
            Self::pattern_ci("XXX"),
            Self::pattern("NOTE"),
            Self::pattern("WARNING"),
            Self::pattern_ci("COPYRIGHT"),
            Self::pattern_ci("LICENSE"),
            Self::documentation(),
            Self::file_header(),
            Self::pattern("eslint-disable"),
            Self::pattern("prettier-ignore"),
            Self::pattern("//nolint"),
            Self::pattern("# noqa"),
            Self::pattern("type: ignore"),
            Self::pattern("fmt: off"),
            Self::pattern("fmt: on"),
            Self::pattern("@ts-ignore"),
            Self::pattern("@ts-expect-error"),
            Self::pattern("/// <reference"),
            Self::pattern_ci("NOSONAR"),
            Self::shebang(),
        ]
    }

    pub fn comprehensive_rules() -> Vec<Self> {
        let mut rules = Self::default_rules();
        rules.extend(vec![
            Self::pattern_ci("BUG"),
            Self::pattern_ci("REVIEW"),
            Self::pattern_ci("OPTIMIZE"),
            Self::pattern_ci("PERFORMANCE"),
            Self::pattern_ci("SECURITY"),
            Self::pattern_ci("DEPRECATED"),
            Self::pattern("eslint-disable"),
            Self::pattern("eslint-enable"),
            Self::pattern("eslint-disable-next-line"),
            Self::pattern("eslint-disable-line"),
            Self::pattern("eslint-env"),
            Self::pattern("eslint:"),
            Self::pattern("biome-ignore"),
            Self::pattern("biome:"),
            Self::pattern("oxlint-ignore"),
            Self::pattern("oxlint-disable"),
            Self::pattern("deno-lint-ignore"),
            Self::pattern("deno-fmt-ignore"),
            Self::pattern("@ts-expect-error"),
            Self::pattern("@ts-ignore"),
            Self::pattern("@ts-nocheck"),
            Self::pattern("@ts-check"),
            Self::pattern("/// <reference"),
            Self::pattern("/// <amd-module"),
            Self::pattern("/// <amd-dependency"),
            Self::pattern("prettier-ignore"),
            Self::pattern("v8 ignore"),
            Self::pattern("c8 ignore"),
            Self::pattern("istanbul ignore"),
            Self::pattern("node:coverage"),
            Self::pattern("@preserve"),
            Self::pattern("webpack:"),
            Self::pattern("vite:"),
            Self::pattern("rollup:"),
            Self::pattern("esbuild:"),
            Self::pattern("type: ignore"),
            Self::pattern("type:ignore"),
            Self::pattern("mypy:"),
            Self::pattern("pyright:"),
            Self::pattern("pyright: ignore"),
            Self::pattern("ruff:"),
            Self::pattern("noqa"),
            Self::pattern("# noqa"),
            Self::pattern("pragma:"),
            Self::pattern("pylint: disable"),
            Self::pattern("pylint: enable"),
            Self::pattern("pylint:"),
            Self::pattern("flake8:"),
            Self::pattern("black:"),
            Self::pattern("fmt: off"),
            Self::pattern("fmt: on"),
            Self::pattern("fmt:off"),
            Self::pattern("fmt:on"),
            Self::pattern("bandit:"),
            Self::pattern("nosec"),
            Self::pattern("isort:"),
            Self::pattern("pyre-ignore"),
            Self::pattern("pyre-fixme"),
            Self::pattern("frozen_string_literal:"),
            Self::pattern("#["),
            Self::pattern("allow("),
            Self::pattern("deny("),
            Self::pattern("warn("),
            Self::pattern("forbid("),
            Self::pattern("expect("),
            Self::pattern("cfg("),
            Self::pattern("#!["),
            Self::pattern("clippy::"),
            Self::pattern("rustfmt::"),
            Self::pattern("#[rustfmt"),
            Self::pattern("#![rustfmt"),
            Self::pattern("//go:"),
            Self::pattern("nolint"),
            Self::pattern("//nolint"),
            Self::pattern("golangci-lint"),
            Self::pattern("lint:ignore"),
            Self::pattern("gosec:"),
            Self::pattern("gocyclo:"),
            Self::pattern("staticcheck:"),
            Self::pattern("exhaustive:"),
            Self::pattern("govet:"),
            Self::pattern("rubocop:"),
            Self::pattern("rubocop:disable"),
            Self::pattern("rubocop:enable"),
            Self::pattern("reek:"),
            Self::pattern("standard:disable"),
            Self::pattern("standard:enable"),
            Self::pattern("@Override"),
            Self::pattern("@SuppressWarnings"),
            Self::pattern("@Deprecated"),
            Self::pattern("@Generated"),
            Self::pattern("@SuppressFBWarnings"),
            Self::pattern("checkstyle:"),
            Self::pattern("//noinspection"),
            Self::pattern("// noinspection"),
            Self::pattern("spotbugs:"),
            Self::pattern("trivy:ignore"),
            Self::pattern("trivy ignore"),
            Self::pattern("tfsec:ignore"),
            Self::pattern("checkov:skip"),
            Self::pattern("terrascan:skip"),
            Self::pattern("terraform-docs:"),
            Self::pattern("tflint-ignore:"),
            Self::pattern("tflint:"),
            Self::pattern("#pragma"),
            Self::pattern("NOLINT"),
            Self::pattern("NOLINTNEXTLINE"),
            Self::pattern("clang-format off"),
            Self::pattern("clang-format on"),
            Self::pattern("cppcheck-suppress"),
            Self::pattern("coverity["),
            Self::pattern("shellcheck disable"),
            Self::pattern("shellcheck source"),
            Self::pattern("hadolint ignore"),
            Self::pattern("yamllint disable"),
            Self::pattern("yamllint enable"),
            Self::pattern("@param"),
            Self::pattern("@return"),
            Self::pattern("@throws"),
            Self::pattern("@author"),
            Self::pattern("@since"),
            Self::pattern("@version"),
            Self::pattern("@see"),
            Self::pattern("@example"),
            Self::pattern("@deprecated"),
            Self::pattern("@internal"),
            Self::pattern("@public"),
            Self::pattern("@private"),
            Self::pattern("@protected"),
            // Dependency automation bots
            Self::pattern("renovate:"),   // # renovate: datasource=... depName=...
            Self::pattern("datasource="), // renovate custom-manager annotations
            Self::pattern("depName="),
            Self::pattern("dependabot"),
            // Security / quality scanners
            Self::pattern("snyk:ignore"),
            Self::pattern("codeql["), // CodeQL inline alert suppression
            // Spell checkers
            Self::pattern("cspell:"),        // cSpell: disable / ignore / words
            Self::pattern("spell-checker:"), // Code Spell Checker alternate prefix
            Self::pattern("codespell:ignore"),
            // Markdown and prose linters. These arrive as ordinary HTML comments, so nothing but
            // this list distinguishes them from a removable aside.
            Self::pattern("markdownlint"), // -disable, -enable, -capture, -restore, -configure-file
            Self::pattern("vale off"),     // bare `vale` would also match "prevalent"
            Self::pattern("vale on"),
            Self::pattern("doctoc"), // the START/END markers delimit generated content
        ]);
        rules
    }
}

/// Whether a comment is documentation by its own syntax — a doc node kind, a doc delimiter such as
/// `///`, `/**` or `##`, or a docstring — leaving out any classification a grammar handler made
/// from position alone, such as Go's "a comment directly above a declaration".
pub fn is_documentation_syntax(node_type: &str, content: &str) -> bool {
    let doc_patterns = [
        "/**",
        "///",
        "//!",
        "##",
        "\"\"\"",
        "doc_comment",
        "documentation_comment",
        "inner_doc_comment",
        "outer_doc_comment",
    ];

    if doc_patterns.iter().any(|&pattern| node_type.contains(pattern)) {
        return true;
    }

    if node_type == "string" {
        let trimmed = content.trim();
        if trimmed.starts_with("\"\"\"") || trimmed.starts_with("'''") {
            return true;
        }
    }

    let trimmed = content.trim();
    doc_patterns.iter().any(|&pattern| trimmed.starts_with(pattern))
}

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

    fn create_test_comment(node_type: &str, row: usize) -> CommentInfo {
        CommentInfo {
            start_byte: 0,
            end_byte: 0,
            start_row: row,
            end_row: row,
            node_type: node_type.to_string(),
            should_preserve: false,
            is_documentation: false,
        }
    }

    #[test]
    fn test_pattern_rule() {
        let rule = PreservationRule::pattern("TODO");
        let comment = create_test_comment("line_comment", 5);
        assert!(rule.matches(&comment, "// TODO: Fix this"));
        assert!(!rule.matches(&comment, "// Regular comment"));
    }

    #[test]
    fn test_documentation_rule() {
        let rule = PreservationRule::documentation();

        let cases = vec![
            ("/// Rust doc comment", "doc_comment", true),
            ("/** Java doc comment */", "block_comment", true),
            ("//! Inner doc comment", "line_comment", true),
            ("## Python docstring", "comment", true),
            ("// Regular comment", "line_comment", false),
        ];

        for (content, node_type, expected) in cases {
            let comment = create_test_comment(node_type, 5);
            assert_eq!(
                rule.matches(&comment, content),
                expected,
                "Failed for: {content} ({node_type})",
            );
        }
    }

    #[test]
    fn test_file_header_rule() {
        let rule = PreservationRule::file_header();

        let header_comment = create_test_comment("line_comment", 0);
        assert!(rule.matches(&header_comment, "// Copyright 2023 Author\n// Licensed under MIT"));

        let early_comment = create_test_comment("line_comment", 1);
        assert!(!rule.matches(&early_comment, "// Just a comment"));

        let late_header = create_test_comment("line_comment", 50);
        assert!(!rule.matches(&late_header, "// Copyright 2023 Author"));

        let autogenerated = create_test_comment("comment", 0);
        assert!(rule.matches(
            &autogenerated,
            "/* Auto-generated by cbindgen. Don't modify this file manually. */"
        ));
    }

    #[test]
    fn test_default_rules() {
        let rules = PreservationRule::default_rules();
        assert!(!rules.is_empty());

        let todo_comment = create_test_comment("line_comment", 5);
        let matches = rules
            .iter()
            .any(|rule| rule.matches(&todo_comment, "// TODO: Fix this"));
        assert!(matches);
    }

    #[test]
    fn test_rule_presets() {
        let default = PreservationRule::default_rules();
        let comprehensive = PreservationRule::comprehensive_rules();

        assert!(default.len() <= comprehensive.len());

        let todo_comment = create_test_comment("line_comment", 5);
        for rules in [&default, &comprehensive] {
            let matches = rules.iter().any(|rule| rule.matches(&todo_comment, "// TODO: Test"));
            assert!(matches, "TODO should be preserved by all rule presets");
        }
    }

    #[test]
    fn test_linting_ignore_patterns() {
        let rules = PreservationRule::comprehensive_rules();

        let test_cases = vec![
            "// eslint-disable-next-line no-console",
            "// biome-ignore lint/suspicious/noExplicitAny",
            "// @ts-ignore",
            "/* v8 ignore next */",
            "# noqa: F401",
            "# pylint: disable=unused-import",
            "# rubocop:disable Metrics/LineLength",
            "#[allow(clippy::too_many_arguments)]",
            "//nolint:gocyclo",
            "// @SuppressWarnings(\"unchecked\")",
        ];

        let comment = create_test_comment("line_comment", 5);
        for content in test_cases {
            let matches = rules.iter().any(|rule| rule.matches(&comment, content));
            assert!(matches, "Linting ignore pattern should be preserved: {content}");
        }
    }

    #[test]
    fn test_coverage_ignore_patterns() {
        let rules = PreservationRule::comprehensive_rules();

        let coverage_patterns = vec![
            "/* v8 ignore next 3 */",
            "/* istanbul ignore next */",
            "/* c8 ignore start */",
            "// @preserve",
        ];

        let comment = create_test_comment("block_comment", 5);
        for content in coverage_patterns {
            let matches = rules.iter().any(|rule| rule.matches(&comment, content));
            assert!(matches, "Coverage ignore pattern should be preserved: {content}");
        }
    }

    #[test]
    fn test_formatter_ignore_patterns() {
        let rules = PreservationRule::comprehensive_rules();

        let formatter_patterns = vec!["// prettier-ignore", "# fmt: off", "# black: off"];

        let comment = create_test_comment("line_comment", 5);
        for content in formatter_patterns {
            let matches = rules.iter().any(|rule| rule.matches(&comment, content));
            assert!(matches, "Formatter ignore pattern should be preserved: {content}");
        }
    }

    #[test]
    fn test_shebang_rule() {
        let rule = PreservationRule::shebang();

        let shebang = create_test_comment("comment", 0);
        assert!(rule.matches(&shebang, "#!/usr/bin/env bash"));

        let not_first_line = create_test_comment("comment", 1);
        assert!(rule.matches(&not_first_line, "#!/usr/bin/env bash"));

        let explicit_shebang_node = create_test_comment("shebang", 0);
        assert!(rule.matches(&explicit_shebang_node, "ignored"));
    }

    #[test]
    fn test_xxx_pattern_preserved() {
        let comment = create_test_comment("line_comment", 5);
        let default_rules = PreservationRule::default_rules();
        let matches = default_rules
            .iter()
            .any(|rule| rule.matches(&comment, "// XXX: this is load-bearing"));
        assert!(matches, "XXX should be preserved by default rules");

        let comprehensive_rules = PreservationRule::comprehensive_rules();
        let matches_comprehensive = comprehensive_rules
            .iter()
            .any(|rule| rule.matches(&comment, "// XXX: this is load-bearing"));
        assert!(matches_comprehensive, "XXX should be preserved by comprehensive rules");
    }

    #[test]
    fn test_nosonar_pattern_preserved() {
        let comment = create_test_comment("line_comment", 5);
        let default_rules = PreservationRule::default_rules();
        let matches = default_rules
            .iter()
            .any(|rule| rule.matches(&comment, "// NOSONAR suppression"));
        assert!(
            matches,
            "NOSONAR should be preserved by default rules as promised in help text"
        );

        let comprehensive_rules = PreservationRule::comprehensive_rules();
        let matches_comprehensive = comprehensive_rules
            .iter()
            .any(|rule| rule.matches(&comment, "// NOSONAR suppression"));
        assert!(
            matches_comprehensive,
            "NOSONAR should be preserved by comprehensive rules"
        );
    }

    #[test]
    fn test_nosec_pattern_preserved() {
        let comment = create_test_comment("comment", 5);
        let comprehensive_rules = PreservationRule::comprehensive_rules();

        let matches_bare = comprehensive_rules.iter().any(|rule| rule.matches(&comment, "# nosec"));
        assert!(matches_bare, "# nosec should be preserved by comprehensive rules");

        let matches_with_test_id = comprehensive_rules
            .iter()
            .any(|rule| rule.matches(&comment, "# nosec B101"));
        assert!(
            matches_with_test_id,
            "# nosec B101 should be preserved by comprehensive rules"
        );
    }

    /// Markdown's directives are ordinary HTML comments, so a markdown run sees them as removable
    /// unless they are named here. Silently deleting one turns a knowingly-suppressed lint error
    /// back into a build failure in a file nobody edited.
    #[test]
    fn markdown_directive_comments_are_preserved() {
        let comment = create_test_comment("html_block", 1);
        let comprehensive_rules = PreservationRule::comprehensive_rules();

        let directives = [
            "<!-- markdownlint-disable -->",
            "<!-- markdownlint-disable MD013 -->",
            "<!-- markdownlint-enable -->",
            "<!-- markdownlint-capture -->",
            "<!-- markdownlint-restore -->",
            "<!-- markdownlint-disable-next-line MD033 -->",
            "<!-- markdownlint-configure-file { \"MD013\": false } -->",
            "<!-- prettier-ignore -->",
            "<!-- vale off -->",
            "<!-- vale on -->",
            "<!-- START doctoc generated TOC -->",
            "<!-- END doctoc -->",
        ];
        for directive in directives {
            assert!(
                comprehensive_rules.iter().any(|rule| rule.matches(&comment, directive)),
                "{directive} should be preserved by comprehensive rules"
            );
        }

        assert!(
            !comprehensive_rules
                .iter()
                .any(|rule| rule.matches(&comment, "<!-- an ordinary aside -->")),
            "a prose comment must still be removable"
        );
    }

    #[test]
    fn test_word_tag_case_insensitive_matching() {
        let comment = create_test_comment("line_comment", 5);
        let default_rules = PreservationRule::default_rules();

        let test_cases = vec![
            ("# todo: fix this", true, "lowercase todo should be preserved"),
            ("# Todo: fix this", true, "titlecase Todo should be preserved"),
            ("# TODO: fix this", true, "uppercase TODO should be preserved"),
            ("# hack something", true, "lowercase hack should be preserved"),
            ("# Hack something", true, "titlecase Hack should be preserved"),
            ("# HACK something", true, "uppercase HACK should be preserved"),
            (
                "// todo refactor",
                true,
                "lowercase todo in C-style comment should be preserved",
            ),
            (
                "// Todo refactor",
                true,
                "titlecase Todo in C-style comment should be preserved",
            ),
            ("// fixme: broken", true, "lowercase fixme should be preserved"),
            ("// FIXME: broken", true, "uppercase FIXME should be preserved"),
            (
                "# just a plain comment",
                false,
                "plain comment without tag should NOT be preserved",
            ),
        ];

        for (content, should_match, description) in test_cases {
            let matches = default_rules.iter().any(|rule| rule.matches(&comment, content));
            assert_eq!(matches, should_match, "{description}");
        }
    }

    #[test]
    fn test_case_insensitive_matching_on_non_ascii_comments() {
        let comment = create_test_comment("line_comment", 5);
        let default_rules = PreservationRule::default_rules();

        // The matcher compares raw byte windows, so a multi-byte comment must neither panic nor
        // report a tag that is not there. Both of these are real shapes in a mixed-language repo.
        let matches_accented = default_rules
            .iter()
            .any(|rule| rule.matches(&comment, "# étoile — plain prose, pas de balise"));
        assert!(
            !matches_accented,
            "accented prose without a tag should NOT be preserved"
        );

        let matches_cjk_with_tag = default_rules
            .iter()
            .any(|rule| rule.matches(&comment, "# 修正が必要 todo: fix the encoding"));
        assert!(
            matches_cjk_with_tag,
            "a lowercase tag after multi-byte text should still be preserved"
        );
    }

    #[test]
    fn test_pragma_patterns_remain_case_sensitive() {
        let comment = create_test_comment("comment", 5);
        let comprehensive_rules = PreservationRule::comprehensive_rules();

        let matches_lowercase_noqa = comprehensive_rules.iter().any(|rule| rule.matches(&comment, "# noqa"));
        assert!(
            matches_lowercase_noqa,
            "lowercase '# noqa' should be preserved (exact match)"
        );

        let matches_uppercase_noqa = comprehensive_rules.iter().any(|rule| rule.matches(&comment, "# NOQA"));
        assert!(
            !matches_uppercase_noqa,
            "uppercase '# NOQA' should NOT be preserved by the '# noqa' pattern (pragma is case-sensitive)"
        );

        let matches_bare_noqa = comprehensive_rules.iter().any(|rule| rule.matches(&comment, "noqa"));
        assert!(matches_bare_noqa, "bare 'noqa' should be preserved (exact match)");

        let matches_bare_uppercase = comprehensive_rules.iter().any(|rule| rule.matches(&comment, "NOQA"));
        assert!(
            !matches_bare_uppercase,
            "bare 'NOQA' should NOT be preserved by the 'noqa' pattern (pragma is case-sensitive)"
        );

        let matches_lowercase_nosec = comprehensive_rules.iter().any(|rule| rule.matches(&comment, "# nosec"));
        assert!(
            matches_lowercase_nosec,
            "lowercase 'nosec' should be preserved (exact match)"
        );

        let matches_uppercase_nosec = comprehensive_rules.iter().any(|rule| rule.matches(&comment, "# NOSEC"));
        assert!(
            !matches_uppercase_nosec,
            "uppercase 'NOSEC' should NOT be preserved by the 'nosec' pattern (pragma is case-sensitive)"
        );
    }
}