ryo-mutations 0.2.0

[experimental] Code transformation primitives for Rust source code
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Clippy diagnostic types and parsing

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Applicability level of a Clippy suggestion
///
/// Determines whether a fix can be automatically applied.
/// See: <https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/enum.Applicability.html>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum Applicability {
    /// The suggestion is definitely correct and can be applied automatically.
    MachineApplicable,
    /// The suggestion may be correct but needs human verification.
    MaybeIncorrect,
    /// The suggestion contains placeholders that need manual editing.
    HasPlaceholders,
    /// The applicability is unknown.
    #[default]
    Unspecified,
}

impl Applicability {
    /// Returns true if this suggestion can be safely auto-applied
    pub fn is_auto_applicable(&self) -> bool {
        matches!(self, Applicability::MachineApplicable)
    }
}

/// Category of Clippy lint
///
/// See: <https://doc.rust-lang.org/stable/clippy/lints.html>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LintCategory {
    /// Lints that detect outright wrong or useless code (deny by default)
    Correctness,
    /// Lints that detect suspicious code patterns
    Suspicious,
    /// Lints suggesting simpler code
    Complexity,
    /// Lints suggesting performance improvements
    Perf,
    /// Lints about idiomatic Rust style
    Style,
    /// Opinionated lints that may have false positives
    Pedantic,
    /// Lints that may lint against reasonable code
    Restriction,
    /// Lints for cargo manifest issues
    Cargo,
    /// Nursery lints (experimental)
    Nursery,
}

impl LintCategory {
    /// Get the clippy lint group name
    pub fn as_str(&self) -> &'static str {
        match self {
            LintCategory::Correctness => "correctness",
            LintCategory::Suspicious => "suspicious",
            LintCategory::Complexity => "complexity",
            LintCategory::Perf => "perf",
            LintCategory::Style => "style",
            LintCategory::Pedantic => "pedantic",
            LintCategory::Restriction => "restriction",
            LintCategory::Cargo => "cargo",
            LintCategory::Nursery => "nursery",
        }
    }

    /// Look up the clippy category for a given lint name.
    ///
    /// Accepts both the canonical prefixed form (`"clippy::unwrap_used"`) and
    /// the short form without the prefix (`"unwrap_used"`).  The category
    /// returned is the one assigned by clippy's official lint list at
    /// <https://rust-lang.github.io/rust-clippy/master/index.html>.
    ///
    /// # Arguments
    ///
    /// * `name` - A lint name, either `"clippy::foo"` or `"foo"`.
    ///
    /// # Returns
    ///
    /// `Some(LintCategory)` when the lint is in the lookup table, `None` for
    /// unknown or unrecognised lint names.
    pub fn from_lint_name(name: &str) -> Option<Self> {
        // Accept both "clippy::foo" and "foo" forms.
        // strip_prefix returns Option<&str>; unwrap_or falls back to the
        // original slice without panicking.
        let short = name.strip_prefix("clippy::").unwrap_or(name);
        match short {
            // --- Correctness (deny by default) ---
            "absurd_extreme_comparisons"
            | "almost_swapped"
            | "approx_constant"
            | "async_yields_async"
            | "bad_bit_mask"
            | "cast_slice_different_sizes"
            | "char_indices_as_byte_indices"
            | "derive_hash_xor_eq"
            | "derive_ord_xor_partial_ord"
            | "erasing_op"
            | "if_let_mutex"
            | "impossible_comparisons"
            | "invalid_regex"
            | "mistyped_literal_suffixes"
            | "nonsensical_open_options"
            | "uninit_assumed_init"
            | "unit_cmp"
            | "unit_return_expecting_ord"
            | "while_immutable_condition" => Some(LintCategory::Correctness),

            // --- Suspicious ---
            "almost_complete_range"
            | "arc_with_non_send_sync"
            | "await_holding_lock"
            | "await_holding_refcell_ref"
            | "blanket_clippy_restriction_lints"
            | "cast_abs_to_unsigned"
            | "cast_enum_constructor"
            | "cast_enum_truncation"
            | "cast_nan_to_int"
            | "cast_slice_from_raw_parts"
            | "confusing_method_to_numeric_cast"
            | "debug_assert_with_mut_call" => Some(LintCategory::Suspicious),

            // --- Complexity ---
            "bind_instead_of_map"
            | "bool_comparison"
            | "borrow_deref_ref"
            | "borrowed_box"
            | "bytes_count_to_len"
            | "char_lit_as_u8"
            | "clone_on_copy"
            | "deref_addrof"
            | "manual_unwrap_or"
            | "needless_bool"
            | "needless_borrow"
            | "option_map_unwrap_or"
            | "redundant_closure"
            | "redundant_slicing"
            | "too_many_arguments"
            | "unnecessary_cast"
            | "unused_self"
            | "useless_format" => Some(LintCategory::Complexity),

            // --- Perf ---
            "box_collection"
            | "boxed_local"
            | "cmp_owned"
            | "collapsible_str_replace"
            | "iter_cloned_collect"
            | "manual_filter_map"
            | "manual_find_map"
            | "manual_map"
            | "map_clone"
            | "or_fun_call"
            | "redundant_allocation"
            | "unnecessary_lazy_evaluations"
            | "useless_conversion"
            | "vec_init_then_push" => Some(LintCategory::Perf),

            // --- Style ---
            "assertions_on_constants"
            | "assign_op_pattern"
            | "blocks_in_conditions"
            | "bool_assert_comparison"
            | "box_default"
            | "builtin_type_shadow"
            | "byte_char_slices"
            | "bytes_nth"
            | "chars_last_cmp"
            | "chars_next_cmp"
            | "cmp_null"
            | "collapsible_if"
            | "collapsible_match"
            | "comparison_to_empty"
            | "const_static_lifetime"
            | "declare_interior_mutable_const"
            | "doc_markdown"
            | "if_not_else"
            | "len_without_is_empty"
            | "len_zero"
            | "manual_string_new"
            | "match_bool"
            | "match_wildcard_for_single_variants"
            | "needless_return"
            | "new_without_default"
            | "ptr_arg"
            | "redundant_pattern_matching"
            | "semicolon_if_nothing_returned"
            | "should_implement_trait"
            | "single_match"
            | "unnecessary_struct_initialization"
            | "upper_case_acronyms"
            | "wrong_self_convention" => Some(LintCategory::Style),

            // --- Pedantic ---
            "assigning_clones"
            | "bool_to_int_with_if"
            | "borrow_as_ptr"
            | "case_sensitive_file_extension_comparisons"
            | "cast_lossless"
            | "cast_possible_truncation"
            | "cast_possible_wrap"
            | "cast_precision_loss"
            | "cast_ptr_alignment"
            | "cast_sign_loss"
            | "checked_conversions"
            | "cloned_instead_of_copied"
            | "collapsible_else_if"
            | "comparison_chain"
            | "copy_iterator"
            | "default_constructed_unit_structs"
            | "default_numeric_fallback"
            | "derive_partial_eq_without_eq"
            | "enum_glob_use"
            | "if_same_then_else"
            | "implicit_clone"
            | "map_unwrap_or"
            | "match_wild_err_arm"
            | "missing_errors_doc"
            | "missing_panics_doc"
            | "module_name_repetitions"
            | "must_use_candidate"
            | "needless_pass_by_value"
            | "option_if_let_else"
            | "similar_names"
            | "todo"
            | "too_many_lines"
            | "type_repetition_in_bounds"
            | "unimplemented"
            | "unnecessary_wraps"
            | "unused_async"
            | "use_self"
            | "verbose_bit_mask"
            | "wildcard_enum_match_arm" => Some(LintCategory::Pedantic),

            // --- Restriction ---
            "absolute_paths"
            | "alloc_instead_of_core"
            | "allow_attributes"
            | "allow_attributes_without_reason"
            | "arithmetic_side_effects"
            | "as_conversions"
            | "as_underscore"
            | "clone_on_ref_ptr"
            | "cognitive_complexity"
            | "create_dir"
            | "dbg_macro"
            | "decimal_literal_representation"
            | "default_union_representation"
            | "expect_used"
            | "implicit_return"
            | "missing_docs_in_private_items"
            | "panic"
            | "print_stderr"
            | "print_stdout"
            | "str_to_string"
            | "string_add"
            | "string_to_string"
            | "todo_in_production"
            | "unwrap_used"
            | "wildcard_imports" => Some(LintCategory::Restriction),

            // --- Cargo ---
            "cargo_common_metadata"
            | "multiple_crate_versions"
            | "negative_feature_names"
            | "redundant_feature_names"
            | "wildcard_dependencies" => Some(LintCategory::Cargo),

            // --- Nursery (experimental) ---
            "as_ptr_cast_mut"
            | "branches_sharing_code"
            | "clear_with_drain"
            | "collection_is_never_read"
            | "coerce_container_to_any"
            | "empty_line_after_doc_comments"
            | "empty_line_after_outer_attr"
            | "equatable_if_let"
            | "fallible_impl_from"
            | "future_not_send"
            | "imprecise_flops"
            | "iter_on_empty_collections"
            | "iter_on_single_items"
            | "iter_with_drain"
            | "large_stack_frames"
            | "missing_const_for_fn"
            | "mutex_integer"
            | "needless_collect"
            | "non_send_fields_in_send_ty"
            | "path_buf_push_overwrite"
            | "redundant_pub_crate"
            | "significant_drop_in_scrutinee"
            | "significant_drop_tightening"
            | "string_lit_as_bytes"
            | "suboptimal_flops"
            | "suspicious_operation_groupings"
            | "trait_duplication_in_bounds"
            | "useless_let_if_seq" => Some(LintCategory::Nursery),

            _ => None,
        }
    }
}

/// Span within a source file
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Span {
    /// File path
    pub file_name: PathBuf,
    /// Start byte offset
    pub byte_start: usize,
    /// End byte offset
    pub byte_end: usize,
    /// Start line (1-indexed)
    pub line_start: usize,
    /// End line (1-indexed)
    pub line_end: usize,
    /// Start column (1-indexed)
    pub column_start: usize,
    /// End column (1-indexed)
    pub column_end: usize,
}

impl Span {
    /// Create a span from byte offsets
    pub fn from_bytes(file_name: impl Into<PathBuf>, start: usize, end: usize) -> Self {
        Self {
            file_name: file_name.into(),
            byte_start: start,
            byte_end: end,
            line_start: 0,
            line_end: 0,
            column_start: 0,
            column_end: 0,
        }
    }

    /// Byte range for slicing
    pub fn byte_range(&self) -> std::ops::Range<usize> {
        self.byte_start..self.byte_end
    }
}

/// A suggestion from Clippy for fixing a lint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Suggestion {
    /// The span to replace
    pub span: Span,
    /// The replacement text
    pub replacement: String,
    /// Applicability level
    pub applicability: Applicability,
    /// Human-readable message
    pub message: String,
}

impl Suggestion {
    /// Create a new suggestion
    pub fn new(span: Span, replacement: impl Into<String>) -> Self {
        Self {
            span,
            replacement: replacement.into(),
            applicability: Applicability::Unspecified,
            message: String::new(),
        }
    }

    /// Set applicability level
    pub fn with_applicability(mut self, applicability: Applicability) -> Self {
        self.applicability = applicability;
        self
    }

    /// Set message
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = message.into();
        self
    }
}

/// A diagnostic message from Clippy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClippyDiagnostic {
    /// The lint name (e.g., "clippy::bool_comparison")
    pub lint_name: String,
    /// Severity level
    pub level: DiagnosticLevel,
    /// Primary message
    pub message: String,
    /// Primary span (where the issue was detected)
    pub span: Option<Span>,
    /// Suggested fixes
    pub suggestions: Vec<Suggestion>,
    /// Additional notes
    pub notes: Vec<String>,
}

/// Diagnostic severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DiagnosticLevel {
    Error,
    Warning,
    Note,
    Help,
}

impl ClippyDiagnostic {
    /// Create a new diagnostic
    pub fn new(lint_name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            lint_name: lint_name.into(),
            level: DiagnosticLevel::Warning,
            message: message.into(),
            span: None,
            suggestions: Vec::new(),
            notes: Vec::new(),
        }
    }

    /// Get the short lint name (without "clippy::" prefix)
    pub fn short_lint_name(&self) -> &str {
        self.lint_name
            .strip_prefix("clippy::")
            .unwrap_or(&self.lint_name)
    }

    /// Check if any suggestion is machine-applicable
    pub fn has_auto_fix(&self) -> bool {
        self.suggestions
            .iter()
            .any(|s| s.applicability.is_auto_applicable())
    }

    /// Get the first machine-applicable suggestion
    pub fn auto_fix(&self) -> Option<&Suggestion> {
        self.suggestions
            .iter()
            .find(|s| s.applicability.is_auto_applicable())
    }

    /// Convert to a Mutation if possible
    ///
    /// This attempts to create an appropriate Mutation based on the lint type.
    /// Returns None if the lint doesn't have a corresponding Mutation implementation.
    pub fn to_mutation(&self) -> Option<Box<dyn crate::Mutation>> {
        use super::lints;
        use crate::idiom::*;

        match self.lint_name.as_str() {
            lints::BOOL_COMPARISON => Some(Box::new(BoolSimplifyMutation::new())),
            lints::COLLAPSIBLE_IF => Some(Box::new(CollapsibleIfMutation::new())),
            lints::COMPARISON_TO_EMPTY => Some(Box::new(ComparisonToMethodMutation::new())),
            lints::ASSIGN_OP_PATTERN => Some(Box::new(AssignOpMutation::new())),
            lints::CLONE_ON_COPY => Some(Box::new(CloneOnCopyMutation::new())),
            lints::REDUNDANT_CLOSURE => Some(Box::new(RedundantClosureMutation::new())),
            // Add more mappings as mutations are implemented
            _ => None,
        }
    }
}

/// Parse Clippy's JSON output format
///
/// Clippy outputs diagnostics in the cargo JSON message format when run with
/// `--message-format=json`.
///
/// # Example
///
/// ```rust,ignore
/// use ryo_mutations::clippy::parse_clippy_output;
///
/// let output = r#"{"reason":"compiler-message","message":{"code":{"code":"clippy::bool_comparison"},...}}"#;
/// let diagnostics = parse_clippy_output(output)?;
/// ```
pub fn parse_clippy_output(json_lines: &str) -> Result<Vec<ClippyDiagnostic>, serde_json::Error> {
    let mut diagnostics = Vec::new();

    for line in json_lines.lines() {
        if line.trim().is_empty() {
            continue;
        }

        // Parse the cargo message envelope
        if let Ok(CargoMessage::CompilerMessage { message }) =
            serde_json::from_str::<CargoMessage>(line)
        {
            if let Some(diag) = convert_compiler_message(message) {
                diagnostics.push(diag);
            }
        }
    }

    Ok(diagnostics)
}

/// Cargo's JSON message envelope
#[derive(Debug, Deserialize)]
#[serde(tag = "reason")]
enum CargoMessage {
    #[serde(rename = "compiler-message")]
    CompilerMessage { message: CompilerMessage },
    #[serde(other)]
    Other,
}

/// Compiler message from cargo
#[derive(Debug, Deserialize)]
struct CompilerMessage {
    code: Option<DiagnosticCode>,
    level: String,
    message: String,
    spans: Vec<CompilerSpan>,
    children: Vec<CompilerMessage>,
}

#[derive(Debug, Deserialize)]
struct DiagnosticCode {
    code: String,
}

#[derive(Debug, Deserialize)]
struct CompilerSpan {
    file_name: String,
    byte_start: usize,
    byte_end: usize,
    line_start: usize,
    line_end: usize,
    column_start: usize,
    column_end: usize,
    is_primary: bool,
    suggested_replacement: Option<String>,
    suggestion_applicability: Option<String>,
}

fn convert_compiler_message(msg: CompilerMessage) -> Option<ClippyDiagnostic> {
    // Only process clippy lints
    let code = msg.code.as_ref()?;
    if !code.code.starts_with("clippy::") {
        return None;
    }

    let level = match msg.level.as_str() {
        "error" => DiagnosticLevel::Error,
        "warning" => DiagnosticLevel::Warning,
        "note" => DiagnosticLevel::Note,
        "help" => DiagnosticLevel::Help,
        _ => DiagnosticLevel::Warning,
    };

    let primary_span = msg.spans.iter().find(|s| s.is_primary).map(|s| Span {
        file_name: PathBuf::from(&s.file_name),
        byte_start: s.byte_start,
        byte_end: s.byte_end,
        line_start: s.line_start,
        line_end: s.line_end,
        column_start: s.column_start,
        column_end: s.column_end,
    });

    // Extract suggestions from spans and children
    let mut suggestions = Vec::new();
    for span in &msg.spans {
        if let Some(ref replacement) = span.suggested_replacement {
            let applicability = span
                .suggestion_applicability
                .as_ref()
                .map(|s| match s.as_str() {
                    "MachineApplicable" => Applicability::MachineApplicable,
                    "MaybeIncorrect" => Applicability::MaybeIncorrect,
                    "HasPlaceholders" => Applicability::HasPlaceholders,
                    _ => Applicability::Unspecified,
                })
                .unwrap_or(Applicability::Unspecified);

            suggestions.push(Suggestion {
                span: Span {
                    file_name: PathBuf::from(&span.file_name),
                    byte_start: span.byte_start,
                    byte_end: span.byte_end,
                    line_start: span.line_start,
                    line_end: span.line_end,
                    column_start: span.column_start,
                    column_end: span.column_end,
                },
                replacement: replacement.clone(),
                applicability,
                message: String::new(),
            });
        }
    }

    // Extract notes from children
    let notes: Vec<String> = msg
        .children
        .iter()
        .filter(|c| c.level == "note" || c.level == "help")
        .map(|c| c.message.clone())
        .collect();

    Some(ClippyDiagnostic {
        lint_name: code.code.clone(),
        level,
        message: msg.message,
        span: primary_span,
        suggestions,
        notes,
    })
}

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

    #[test]
    fn test_applicability_auto_applicable() {
        assert!(Applicability::MachineApplicable.is_auto_applicable());
        assert!(!Applicability::MaybeIncorrect.is_auto_applicable());
        assert!(!Applicability::HasPlaceholders.is_auto_applicable());
        assert!(!Applicability::Unspecified.is_auto_applicable());
    }

    #[test]
    fn test_diagnostic_short_lint_name() {
        let diag = ClippyDiagnostic::new("clippy::bool_comparison", "test");
        assert_eq!(diag.short_lint_name(), "bool_comparison");

        let diag2 = ClippyDiagnostic::new("other_lint", "test");
        assert_eq!(diag2.short_lint_name(), "other_lint");
    }

    #[test]
    fn test_parse_clippy_output_empty() {
        let result = parse_clippy_output("");
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    // --- from_lint_name tests ---

    #[test]
    fn test_from_lint_name_correctness() {
        assert_eq!(
            LintCategory::from_lint_name("absurd_extreme_comparisons"),
            Some(LintCategory::Correctness)
        );
        assert_eq!(
            LintCategory::from_lint_name("erasing_op"),
            Some(LintCategory::Correctness)
        );
    }

    #[test]
    fn test_from_lint_name_suspicious() {
        assert_eq!(
            LintCategory::from_lint_name("await_holding_lock"),
            Some(LintCategory::Suspicious)
        );
        assert_eq!(
            LintCategory::from_lint_name("cast_nan_to_int"),
            Some(LintCategory::Suspicious)
        );
    }

    #[test]
    fn test_from_lint_name_complexity() {
        // Acceptance criterion: bool_comparison must map to Complexity (not Style).
        // The official clippy list classifies bool_comparison as Complexity;
        // mod.rs comments are incorrect on this point.
        assert_eq!(
            LintCategory::from_lint_name("bool_comparison"),
            Some(LintCategory::Complexity)
        );
        assert_eq!(
            LintCategory::from_lint_name("redundant_closure"),
            Some(LintCategory::Complexity)
        );
    }

    #[test]
    fn test_from_lint_name_perf() {
        assert_eq!(
            LintCategory::from_lint_name("box_collection"),
            Some(LintCategory::Perf)
        );
        assert_eq!(
            LintCategory::from_lint_name("useless_conversion"),
            Some(LintCategory::Perf)
        );
    }

    #[test]
    fn test_from_lint_name_style() {
        assert_eq!(
            LintCategory::from_lint_name("collapsible_if"),
            Some(LintCategory::Style)
        );
        assert_eq!(
            LintCategory::from_lint_name("needless_return"),
            Some(LintCategory::Style)
        );
    }

    #[test]
    fn test_from_lint_name_pedantic() {
        assert_eq!(
            LintCategory::from_lint_name("cast_lossless"),
            Some(LintCategory::Pedantic)
        );
        assert_eq!(
            LintCategory::from_lint_name("missing_errors_doc"),
            Some(LintCategory::Pedantic)
        );
    }

    #[test]
    fn test_from_lint_name_restriction() {
        // Acceptance criterion: unwrap_used must map to Restriction.
        assert_eq!(
            LintCategory::from_lint_name("unwrap_used"),
            Some(LintCategory::Restriction)
        );
        assert_eq!(
            LintCategory::from_lint_name("expect_used"),
            Some(LintCategory::Restriction)
        );
    }

    #[test]
    fn test_from_lint_name_cargo() {
        assert_eq!(
            LintCategory::from_lint_name("cargo_common_metadata"),
            Some(LintCategory::Cargo)
        );
        assert_eq!(
            LintCategory::from_lint_name("multiple_crate_versions"),
            Some(LintCategory::Cargo)
        );
    }

    #[test]
    fn test_from_lint_name_nursery() {
        assert_eq!(
            LintCategory::from_lint_name("branches_sharing_code"),
            Some(LintCategory::Nursery)
        );
        assert_eq!(
            LintCategory::from_lint_name("needless_collect"),
            Some(LintCategory::Nursery)
        );
    }

    #[test]
    fn test_from_lint_name_unknown() {
        assert_eq!(LintCategory::from_lint_name("unknown_lint"), None);
        assert_eq!(LintCategory::from_lint_name(""), None);
        assert_eq!(LintCategory::from_lint_name("rustc::unused_imports"), None);
    }

    #[test]
    fn test_from_lint_name_with_prefix() {
        assert_eq!(
            LintCategory::from_lint_name("clippy::unwrap_used"),
            Some(LintCategory::Restriction)
        );
        assert_eq!(
            LintCategory::from_lint_name("clippy::bool_comparison"),
            Some(LintCategory::Complexity)
        );
    }

    #[test]
    fn test_from_lint_name_without_prefix() {
        assert_eq!(
            LintCategory::from_lint_name("unwrap_used"),
            Some(LintCategory::Restriction)
        );
        assert_eq!(
            LintCategory::from_lint_name("bool_comparison"),
            Some(LintCategory::Complexity)
        );
    }
}