ryo-suggest 0.1.0

[experimental] Pattern-based suggestion engine for RYO
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! UnwrapToExpect - Detect unwrap() calls and suggest expect() with descriptive message
//!
//! # Rule Code
//! RS101 (Ryo Safety)
//!
//! # Detection Goal
//!
//! `Option<T>::unwrap()` / `Result<T, E>::unwrap()` のうち、panic の可能性がある箇所を検知し、
//! `expect("descriptive message")` への置換または適切なエラーハンドリングを提案する。
//!
//! # Type Resolution Constraint (重要な設計制約)
//!
//! PureExpr AST は式レベルの型情報を保持しない。
//! `foo().unwrap()` の `foo()` が `Option<T>` を返すのか `Result<T,E>` を返すのか、
//! あるいは全く別の型の `.unwrap()` メソッドなのかを、AST 単体では判別できない。
//!
//! TypeFlowGraphV2 はシンボルレベル(関数の引数型・戻り値型・フィールド型)の追跡であり、
//! 式レベルの型推論(「この部分式の型は Option<T>」)は提供しない。
//! receiver の型を完全に解決するには、receiver のメソッドチェーンを遡って
//! 各段階の型を推論する必要があり、これは事実上ミニ型推論エンジンの構築に相当する。
//!
//! # Current Approach: Method Name Heuristic
//!
//! 完全な型解決の代わりに、receiver のメソッド名から型を推定する:
//!
//! - **既知の Option 返却メソッド** (`get`, `find`, `first`, `last`, `next` 等)
//!   → 高い確度で検知
//! - **既知の Result 返却メソッド** (`parse`, `lock`, `read`, `write` 等)
//!   → 高い確度で検知
//! - **既知の非 Option/Result 返却メソッド** (`entry`, `iter`, `clone` 等)
//!   → 検知をスキップ(FP の主要因)
//! - **不明なメソッド / 変数 / フィールド**
//!   → 中程度の確度で検知し、メッセージで制約を説明
//!
//! # False Positive Policy
//!
//! この方式は FP を完全には排除できない。検知メッセージには以下を含める:
//! - receiver の型が Option/Result でない場合は FP である旨
//! - その場合は Ignore 設定を推奨する旨

use ryo_analysis::context::AnalysisContext;
use ryo_analysis::{SymbolId, SymbolKind};
use ryo_source::pure::{PureBlock, PureExpr, PureImplItem, PureItem, PureStmt, PureType};

use super::SafetySuggest;
use crate::{
    LintSeverity, MutationSpec, OpportunityId, SafetyLevel, Suggest, SuggestCategory,
    SuggestLocation, SuggestOpportunity, SuggestResult, SymbolScope,
};

/// receiver メソッド名から推定した型ヒント。
///
/// PureExpr に型情報がないため、メソッド名ベースのヒューリスティックで
/// `.unwrap()` の receiver が Option/Result かどうかを推定する。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReceiverTypeHint {
    /// `get`, `find`, `first` 等 — 標準ライブラリで Option<T> を返すメソッド
    LikelyOption,
    /// `parse`, `lock`, `read` 等 — 標準ライブラリで Result<T,E> を返すメソッド
    LikelyResult,
    /// `entry`, `iter`, `clone` 等 — Option/Result を返さないことが既知のメソッド
    KnownNonOptionResult,
    /// メソッド名から型が推定できない、または変数/フィールドの直接 unwrap
    Unknown,
}

/// UnwrapToExpect detection rule
///
/// Detects unwrap() calls on likely Option/Result types and suggests
/// expect() with descriptive message.
///
/// # Detection Confidence Levels
///
/// - **High (0.9)**: receiver が既知の Option/Result 返却メソッド
/// - **Medium (0.7)**: 変数/フィールドの直接 unwrap(型不明だが Option/Result の可能性が高い)
/// - **Skipped**: receiver が既知の非 Option/Result メソッド
pub struct UnwrapToExpect {
    /// Minimum confidence threshold for reporting
    min_confidence: f32,
}

impl UnwrapToExpect {
    pub fn new() -> Self {
        Self {
            min_confidence: 0.5,
        }
    }

    /// Set minimum confidence threshold
    pub fn with_min_confidence(mut self, threshold: f32) -> Self {
        self.min_confidence = threshold.clamp(0.0, 1.0);
        self
    }

    /// Check if a return type is Option or Result (compatible with ? operator)
    fn returns_option_or_result(ret: &Option<PureType>) -> bool {
        match ret {
            Some(PureType::Path(path)) => {
                path.starts_with("Option<")
                    || path.starts_with("Result<")
                    || path == "Option"
                    || path == "Result"
            }
            _ => false,
        }
    }

    /// receiver のメソッド名から Option/Result の可能性を推定する。
    ///
    /// # Design Note
    ///
    /// PureExpr は型情報を持たないため、メソッド名のみで判定する。
    /// std の代表的なメソッド名を基準としており、同名のカスタムメソッドが
    /// 異なる型を返すケースでは誤判定が生じ得る。
    fn infer_receiver_type_hint(receiver: &PureExpr) -> ReceiverTypeHint {
        match receiver {
            PureExpr::MethodCall { method, .. } => Self::classify_method_name(method),
            PureExpr::Call { func, .. } => {
                // 関数呼び出し: Some(...), Ok(...), Err(...) 等
                if let PureExpr::Path(name) = func.as_ref() {
                    match name.as_str() {
                        "Some" | "Ok" | "Err" => ReceiverTypeHint::LikelyOption,
                        _ => ReceiverTypeHint::Unknown,
                    }
                } else {
                    ReceiverTypeHint::Unknown
                }
            }
            // 変数やフィールドの直接 unwrap — 型情報なし
            PureExpr::Path(_) | PureExpr::Field { .. } => ReceiverTypeHint::Unknown,
            _ => ReceiverTypeHint::Unknown,
        }
    }

    /// メソッド名を Option/Result/その他に分類する。
    ///
    /// 分類基準: Rust 標準ライブラリおよび主要クレートのメソッドシグネチャ。
    /// 網羅的ではないため、未知のメソッドは Unknown を返す。
    fn classify_method_name(method: &str) -> ReceiverTypeHint {
        // --- 既知の Option<T> 返却メソッド ---
        // コレクション系: HashMap::get, Vec::get, BTreeMap::get, etc.
        // イテレータ系: Iterator::next, Iterator::find, etc.
        // スライス系: [T]::first, [T]::last, etc.
        // str系: str::strip_prefix, str::find, etc.
        // 数値系: u32::checked_add, etc.
        // Path系: Path::parent, Path::file_name, etc.
        // Option自身のメソッド: Option::as_ref, Option::take, etc.
        const OPTION_METHODS: &[&str] = &[
            // コレクションアクセス
            "get",
            "get_mut",
            // スライス・イテレータ
            "first",
            "first_mut",
            "last",
            "last_mut",
            "find",
            "find_map",
            "position",
            "rposition",
            "next",
            "next_back",
            "peek",
            // コレクション操作
            "pop",
            "pop_front",
            "pop_back",
            "front",
            "front_mut",
            "back",
            "back_mut",
            "remove", // HashMap::remove returns Option<V>
            // str
            "strip_prefix",
            "strip_suffix",
            // 数値 checked 演算
            "checked_add",
            "checked_sub",
            "checked_mul",
            "checked_div",
            "checked_rem",
            "checked_neg",
            "checked_shl",
            "checked_shr",
            // Path
            "parent",
            "file_name",
            "file_stem",
            "extension",
            "to_str",
            // Option 自身のメソッド (chain 中で unwrap するケース)
            "as_ref",
            "as_mut",
            "as_deref",
            "as_deref_mut",
            "take",
            "replace",
            "map",
            "and_then",
            "or",
            "or_else",
            "filter",
            "zip",
            // Result → Option 変換
            "ok",
            "err",
            // その他
            "min",
            "max", // Iterator::min/max return Option
        ];

        // --- 既知の Result<T, E> 返却メソッド ---
        // IO系: Read::read, Write::write, etc.
        // 同期系: Mutex::lock, etc.
        // パース系: str::parse, etc.
        // 変換系: TryInto::try_into, etc.
        const RESULT_METHODS: &[&str] = &[
            // パース・変換
            "parse",
            "try_into",
            "try_from",
            // IO
            "read",
            "read_to_string",
            "read_to_end",
            "read_line",
            "read_exact",
            "write",
            "write_all",
            "write_fmt",
            "flush",
            // 同期プリミティブ
            "lock",
            "try_lock",
            "try_read", // RwLock (read は IO の read と重複するため上で定義済み)
            // チャネル
            "send",
            "try_send",
            "recv",
            "try_recv",
            "recv_timeout",
            // ネットワーク・ファイル
            "connect",
            "bind",
            "accept",
            "open",
            "create",
            // スレッド
            "join",
        ];

        // --- 既知の非 Option/Result 返却メソッド ---
        // これらのメソッドに .unwrap() が付いている場合は FP の可能性が極めて高い。
        // HashMap::entry → Entry (not Option)
        // Iterator::iter → Iterator (not Option)
        // Clone::clone → T (not Option)
        const NON_OPTION_RESULT_METHODS: &[&str] = &[
            // コレクション操作 (Option/Result を返さない)
            "entry",
            "or_insert",
            "or_insert_with",
            "or_default",
            // イテレータ生成 (Iterator を返す)
            "iter",
            "iter_mut",
            "into_iter",
            "keys",
            "values",
            "values_mut",
            "enumerate",
            "chain",
            // NOTE: map, filter, zip, take は Iterator にも存在するが、
            // Iterator 版は .unwrap() を持たないため OPTION_METHODS で正しく分類される。
            // ここには Iterator 固有(Option に同名メソッドがない)ものだけ列挙する。
            "filter_map",
            "flat_map",
            "flatten",
            "skip",
            "skip_while",
            "take_while",
            "collect",
            "fold",
            "for_each",
            // 複製・変換
            "clone",
            "clone_from",
            "to_string",
            "to_owned",
            "into",
            "from",
            "as_str",
            "as_bytes",
            "as_slice",
            "as_mut_slice",
            // プロパティ (値を返す)
            "len",
            "is_empty",
            "capacity",
            "contains",
            "contains_key",
            // ソート・反転
            "sort",
            "sort_by",
            "sort_by_key",
            "reverse",
            "dedup",
            // 表示
            "display",
            "fmt",
        ];

        if OPTION_METHODS.contains(&method) {
            return ReceiverTypeHint::LikelyOption;
        }
        if RESULT_METHODS.contains(&method) {
            return ReceiverTypeHint::LikelyResult;
        }
        if NON_OPTION_RESULT_METHODS.contains(&method) {
            return ReceiverTypeHint::KnownNonOptionResult;
        }

        ReceiverTypeHint::Unknown
    }

    /// Find all unwrap() calls in a block
    fn find_unwrap_calls(&self, block: &PureBlock) -> Vec<UnwrapCallInfo> {
        let mut calls = Vec::new();
        for stmt in &block.stmts {
            self.find_unwrap_in_stmt(stmt, &mut calls);
        }
        calls
    }

    fn find_unwrap_in_stmt(&self, stmt: &PureStmt, calls: &mut Vec<UnwrapCallInfo>) {
        match stmt {
            PureStmt::Local { init: Some(e), .. } => self.find_unwrap_in_expr(e, calls),
            PureStmt::Semi(e) | PureStmt::Expr(e) => self.find_unwrap_in_expr(e, calls),
            _ => {}
        }
    }

    fn find_unwrap_in_expr(&self, expr: &PureExpr, calls: &mut Vec<UnwrapCallInfo>) {
        // Check if this is an unwrap() call
        if let PureExpr::MethodCall {
            receiver,
            method,
            args,
            ..
        } = expr
        {
            if method == "unwrap" && args.is_empty() {
                let type_hint = Self::infer_receiver_type_hint(receiver);

                // 既知の非 Option/Result メソッド → FP 回避のためスキップ
                if type_hint == ReceiverTypeHint::KnownNonOptionResult {
                    // receiver が Option/Result を返さないメソッドの場合、
                    // .unwrap() は別の型のメソッドである可能性が高い。
                    // 例: HashMap::entry().unwrap() は Entry 型に .unwrap() は存在しないため、
                    //     DashMap 等の特殊な API か、中間の型変換が介在している。
                    //     いずれにせよ、標準的な Option/Result::unwrap() とは異なるため除外する。
                } else {
                    let context = self.extract_context(receiver);
                    let message = self.generate_message(&context, type_hint);
                    calls.push(UnwrapCallInfo {
                        context,
                        type_hint,
                        suggested_message: message,
                        confidence: self.calculate_confidence(receiver, type_hint),
                    });
                }
            }
        }

        // Recursively search sub-expressions
        match expr {
            PureExpr::Binary { left, right, .. } => {
                self.find_unwrap_in_expr(left, calls);
                self.find_unwrap_in_expr(right, calls);
            }
            PureExpr::Unary { expr: inner, .. } => {
                self.find_unwrap_in_expr(inner, calls);
            }
            PureExpr::Call { func, args } => {
                self.find_unwrap_in_expr(func, calls);
                for arg in args {
                    self.find_unwrap_in_expr(arg, calls);
                }
            }
            PureExpr::MethodCall { receiver, args, .. } => {
                self.find_unwrap_in_expr(receiver, calls);
                for arg in args {
                    self.find_unwrap_in_expr(arg, calls);
                }
            }
            PureExpr::Field { expr: inner, .. } => {
                self.find_unwrap_in_expr(inner, calls);
            }
            PureExpr::Index { expr: inner, index } => {
                self.find_unwrap_in_expr(inner, calls);
                self.find_unwrap_in_expr(index, calls);
            }
            PureExpr::Block { block, .. } => {
                for stmt in &block.stmts {
                    self.find_unwrap_in_stmt(stmt, calls);
                }
            }
            PureExpr::If {
                cond,
                then_branch,
                else_branch,
            } => {
                self.find_unwrap_in_expr(cond, calls);
                for stmt in &then_branch.stmts {
                    self.find_unwrap_in_stmt(stmt, calls);
                }
                if let Some(else_expr) = else_branch {
                    self.find_unwrap_in_expr(else_expr, calls);
                }
            }
            PureExpr::Match { expr: e, arms } => {
                self.find_unwrap_in_expr(e, calls);
                for arm in arms {
                    self.find_unwrap_in_expr(&arm.body, calls);
                }
            }
            PureExpr::Loop { body: block, .. } | PureExpr::While { body: block, .. } => {
                for stmt in &block.stmts {
                    self.find_unwrap_in_stmt(stmt, calls);
                }
            }
            PureExpr::For {
                expr: iter_expr,
                body,
                ..
            } => {
                self.find_unwrap_in_expr(iter_expr, calls);
                for stmt in &body.stmts {
                    self.find_unwrap_in_stmt(stmt, calls);
                }
            }
            PureExpr::Closure { body, .. } => {
                self.find_unwrap_in_expr(body, calls);
            }
            PureExpr::Tuple(exprs) | PureExpr::Array(exprs) => {
                for e in exprs {
                    self.find_unwrap_in_expr(e, calls);
                }
            }
            PureExpr::Struct { fields, .. } => {
                for (_, e) in fields {
                    self.find_unwrap_in_expr(e, calls);
                }
            }
            PureExpr::Ref { expr: inner, .. } => {
                self.find_unwrap_in_expr(inner, calls);
            }
            PureExpr::Return(Some(inner)) => {
                self.find_unwrap_in_expr(inner, calls);
            }
            PureExpr::Try(inner) => {
                self.find_unwrap_in_expr(inner, calls);
            }
            PureExpr::Await(inner) => {
                self.find_unwrap_in_expr(inner, calls);
            }
            _ => {}
        }
    }

    /// Extract context from the receiver expression
    fn extract_context(&self, receiver: &PureExpr) -> UnwrapContext {
        match receiver {
            PureExpr::Path(name) => UnwrapContext::Variable(name.clone()),
            PureExpr::Field { expr, field } => {
                let base = self.extract_base_name(expr);
                UnwrapContext::Field {
                    base,
                    field: field.clone(),
                }
            }
            PureExpr::MethodCall { method, .. } => UnwrapContext::MethodCall(method.clone()),
            PureExpr::Call { func, .. } => {
                let func_name = self.extract_func_name(func);
                UnwrapContext::FunctionCall(func_name)
            }
            _ => UnwrapContext::Unknown,
        }
    }

    fn extract_base_name(&self, expr: &PureExpr) -> String {
        match expr {
            PureExpr::Path(name) => name.clone(),
            PureExpr::Field { expr, field } => {
                format!("{}.{}", self.extract_base_name(expr), field)
            }
            _ => "value".to_string(),
        }
    }

    fn extract_func_name(&self, expr: &PureExpr) -> String {
        match expr {
            PureExpr::Path(name) => name.clone(),
            _ => "function".to_string(),
        }
    }

    /// Generate expect message based on context and type hint
    fn generate_message(&self, context: &UnwrapContext, type_hint: ReceiverTypeHint) -> String {
        let base_msg = match context {
            UnwrapContext::Variable(name) => format!("{} should be Some/Ok", name),
            UnwrapContext::Field { base, field } => {
                format!("{}.{} should be initialized", base, field)
            }
            UnwrapContext::MethodCall(method) => match type_hint {
                ReceiverTypeHint::LikelyOption => {
                    format!("{}() should return Some", method)
                }
                ReceiverTypeHint::LikelyResult => {
                    format!("{}() should succeed", method)
                }
                _ => format!("{}() should return Some/Ok", method),
            },
            UnwrapContext::FunctionCall(func) => format!("{}() should return Some/Ok", func),
            UnwrapContext::Unknown => "value should be Some/Ok".to_string(),
        };
        base_msg
    }

    /// Calculate confidence based on expression complexity and type hint.
    ///
    /// 型ヒントが明確なほど高い confidence を返す。
    /// Unknown の場合は型の確信がないため低めに設定する。
    fn calculate_confidence(&self, receiver: &PureExpr, type_hint: ReceiverTypeHint) -> f32 {
        let base = match receiver {
            PureExpr::Path(_) => 0.8,
            PureExpr::Field { .. } => 0.75,
            PureExpr::MethodCall { .. } => 0.7,
            PureExpr::Call { .. } => 0.7,
            _ => 0.5,
        };

        match type_hint {
            // 既知の Option/Result 返却メソッド → 高い確度
            ReceiverTypeHint::LikelyOption | ReceiverTypeHint::LikelyResult => {
                (base + 0.1_f32).min(1.0)
            }
            // 変数/フィールド等、型が不明 → ベースのまま
            ReceiverTypeHint::Unknown => base,
            // KnownNonOptionResult はここに到達しない(事前にスキップ済み)
            ReceiverTypeHint::KnownNonOptionResult => 0.0,
        }
    }

    /// 検知メッセージの末尾に付与する制約説明。
    ///
    /// ユーザーに対して:
    /// 1. この検知がメソッド名ヒューリスティックに基づくこと
    /// 2. receiver が Option/Result でない場合は誤検知であること
    /// 3. その場合は Ignore 設定を推奨すること
    ///    を丁寧に伝える。
    fn format_suggestion(call: &UnwrapCallInfo) -> String {
        let action = match call.type_hint {
            ReceiverTypeHint::LikelyOption => {
                format!(
                    "Replace `.unwrap()` with `.expect(\"{}\")`, or handle None with match/if-let",
                    call.suggested_message,
                )
            }
            ReceiverTypeHint::LikelyResult => {
                format!(
                    "Replace `.unwrap()` with `.expect(\"{}\")`, or propagate error with `?`",
                    call.suggested_message,
                )
            }
            _ => {
                format!(
                    "Replace `.unwrap()` with `.expect(\"{}\")`",
                    call.suggested_message,
                )
            }
        };

        let caveat = match call.type_hint {
            ReceiverTypeHint::LikelyOption | ReceiverTypeHint::LikelyResult => String::new(),
            ReceiverTypeHint::Unknown => {
                "\n\n[Type constraint] RS101 は AST 上の式レベル型情報を持たないため、\
                 receiver が Option/Result であることを確認できていません。\
                 もし receiver が Option/Result 以外の型(例: カスタム型の .unwrap() メソッド)\
                 であれば、この検知は誤検知です。その場合はこの検知を Ignore に設定してください。"
                    .to_string()
            }
            // KnownNonOptionResult はここに到達しない
            ReceiverTypeHint::KnownNonOptionResult => String::new(),
        };

        format!("{action}{caveat}")
    }
}

impl Default for UnwrapToExpect {
    fn default() -> Self {
        Self::new()
    }
}

impl SafetySuggest for UnwrapToExpect {
    fn code(&self) -> &'static str {
        "RS101"
    }

    fn default_severity(&self) -> LintSeverity {
        LintSeverity::Warning
    }
}

impl Suggest for UnwrapToExpect {
    fn name(&self) -> &'static str {
        "unwrap-to-expect"
    }

    fn description(&self) -> &str {
        "Converts unwrap() to expect() with descriptive error message for better debugging"
    }

    fn category(&self) -> SuggestCategory {
        SuggestCategory::Safety
    }

    fn safety_level(&self) -> SafetyLevel {
        SafetyLevel::Confirm // Needs review for message appropriateness
    }

    fn priority_weight(&self) -> f32 {
        1.0
    }

    fn target_scopes(&self) -> Vec<SymbolScope> {
        vec![SymbolScope::Lib, SymbolScope::Bin]
    }

    fn detect(&self, ctx: &AnalysisContext, symbols: &[SymbolId]) -> Vec<SuggestOpportunity> {
        let mut opportunities = Vec::new();
        let mut next_id = 0u32;

        // Only standalone functions here — methods are handled in the impl block
        // pass below (with qualified `Type::method` names) to avoid duplication.
        //
        // When `symbols` is non-empty it may contain Method/Field/Impl IDs.
        // Since `ast_registry` stores methods as `PureItem::Fn` (converted from
        // `PureImplItem::Fn`), passing a Method ID here would match Pass 1's
        // `PureItem::Fn` check AND Pass 2's impl-block iteration → duplicate.
        // Filter to `SymbolKind::Function` to prevent this.
        let fn_symbols: Vec<SymbolId> = if symbols.is_empty() {
            ctx.registry.iter_by_kind(SymbolKind::Function).collect()
        } else {
            symbols
                .iter()
                .copied()
                .filter(|id| ctx.registry.kind(*id) == Some(SymbolKind::Function))
                .collect()
        };

        // Check standalone functions
        for symbol_id in &fn_symbols {
            if let Some(PureItem::Fn(f)) = ctx.ast_registry.get(*symbol_id) {
                // Skip if function returns Option/Result (can use ? instead)
                if Self::returns_option_or_result(&f.ret) {
                    continue;
                }

                let unwrap_calls = self.find_unwrap_calls(&f.body);
                for call in unwrap_calls {
                    if call.confidence < self.min_confidence {
                        continue;
                    }

                    let Some(location) = SuggestLocation::from_context(ctx, *symbol_id) else {
                        continue;
                    };

                    let message = format!("unwrap() without descriptive message in `{}`", f.name);
                    let suggestion = Self::format_suggestion(&call);

                    let opp = self.create_safety_opportunity(
                        OpportunityId::new(next_id),
                        vec![*symbol_id],
                        location,
                        message,
                        suggestion,
                        call.confidence,
                    );

                    opportunities.push(opp);
                    next_id += 1;
                }
            }
        }

        // Check impl blocks for methods
        let impl_symbols: Vec<SymbolId> = ctx.registry.iter_by_kind(SymbolKind::Impl).collect();

        for impl_id in impl_symbols {
            if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(impl_id) {
                for impl_item in &imp.items {
                    if let PureImplItem::Fn(f) = impl_item {
                        // Skip if method returns Option/Result
                        if Self::returns_option_or_result(&f.ret) {
                            continue;
                        }

                        let unwrap_calls = self.find_unwrap_calls(&f.body);
                        for call in unwrap_calls {
                            if call.confidence < self.min_confidence {
                                continue;
                            }

                            let Some(location) = SuggestLocation::from_context(ctx, impl_id) else {
                                continue;
                            };

                            let message = format!(
                                "unwrap() without descriptive message in `{}::{}`",
                                imp.self_ty, f.name
                            );
                            let suggestion = Self::format_suggestion(&call);

                            let opp = self.create_safety_opportunity(
                                OpportunityId::new(next_id),
                                vec![impl_id],
                                location,
                                message,
                                suggestion,
                                call.confidence,
                            );

                            opportunities.push(opp);
                            next_id += 1;
                        }
                    }
                }
            }
        }

        opportunities
    }

    fn to_mutation_specs(
        &self,
        _ctx: &AnalysisContext,
        _opportunity: &SuggestOpportunity,
    ) -> SuggestResult<Vec<MutationSpec>> {
        // Phase 1: Manual fix required
        // Future: Add UnwrapToExpect MutationSpec for automatic transformation
        Ok(Vec::new())
    }
}

/// Context information about an unwrap() call
#[derive(Debug, Clone)]
enum UnwrapContext {
    /// Simple variable: `x.unwrap()`
    Variable(String),
    /// Field access: `self.data.unwrap()`
    Field { base: String, field: String },
    /// Method call: `get_value().unwrap()`
    MethodCall(String),
    /// Function call: `load_config().unwrap()`
    FunctionCall(String),
    /// Unknown context
    Unknown,
}

/// Information about a detected unwrap() call
struct UnwrapCallInfo {
    #[allow(dead_code)]
    context: UnwrapContext,
    type_hint: ReceiverTypeHint,
    suggested_message: String,
    confidence: f32,
}

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

    #[test]
    fn test_rule_metadata() {
        let rule = UnwrapToExpect::new();
        assert_eq!(rule.code(), "RS101");
        assert_eq!(rule.name(), "unwrap-to-expect");
        assert_eq!(rule.category(), SuggestCategory::Safety);
        assert_eq!(rule.safety_level(), SafetyLevel::Confirm);
    }

    #[test]
    fn test_confidence_threshold() {
        let rule = UnwrapToExpect::new().with_min_confidence(0.8);
        assert!((rule.min_confidence - 0.8).abs() < f32::EPSILON);

        // Clamp to valid range
        let rule = UnwrapToExpect::new().with_min_confidence(1.5);
        assert!((rule.min_confidence - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_returns_option_or_result() {
        assert!(UnwrapToExpect::returns_option_or_result(&Some(
            PureType::Path("Option<i32>".to_string())
        )));
        assert!(UnwrapToExpect::returns_option_or_result(&Some(
            PureType::Path("Result<String, Error>".to_string())
        )));
        assert!(!UnwrapToExpect::returns_option_or_result(&Some(
            PureType::Path("i32".to_string())
        )));
        assert!(!UnwrapToExpect::returns_option_or_result(&None));
    }

    // --- ReceiverTypeHint tests ---

    #[test]
    fn test_classify_known_option_methods() {
        let option_methods = [
            "get",
            "find",
            "first",
            "last",
            "next",
            "pop",
            "peek",
            "checked_add",
            "parent",
            "file_name",
            "as_ref",
            "take",
            "ok",
            "err",
        ];
        for method in option_methods {
            assert_eq!(
                UnwrapToExpect::classify_method_name(method),
                ReceiverTypeHint::LikelyOption,
                "expected LikelyOption for method: {method}"
            );
        }
    }

    #[test]
    fn test_classify_known_result_methods() {
        let result_methods = [
            "parse",
            "lock",
            "try_lock",
            "read_to_string",
            "write_all",
            "send",
            "recv",
            "connect",
            "open",
            "join",
        ];
        for method in result_methods {
            assert_eq!(
                UnwrapToExpect::classify_method_name(method),
                ReceiverTypeHint::LikelyResult,
                "expected LikelyResult for method: {method}"
            );
        }
    }

    #[test]
    fn test_classify_known_non_option_result_methods() {
        let safe_methods = [
            "entry",
            "iter",
            "into_iter",
            "clone",
            "to_string",
            "to_owned",
            "len",
            "is_empty",
            "contains",
            "sort",
            "collect",
        ];
        for method in safe_methods {
            assert_eq!(
                UnwrapToExpect::classify_method_name(method),
                ReceiverTypeHint::KnownNonOptionResult,
                "expected KnownNonOptionResult for method: {method}"
            );
        }
    }

    #[test]
    fn test_classify_unknown_methods() {
        let unknown_methods = ["custom_method", "do_something", "process"];
        for method in unknown_methods {
            assert_eq!(
                UnwrapToExpect::classify_method_name(method),
                ReceiverTypeHint::Unknown,
                "expected Unknown for method: {method}"
            );
        }
    }

    #[test]
    fn test_infer_variable_receiver_is_unknown() {
        let expr = PureExpr::Path("config".to_string());
        assert_eq!(
            UnwrapToExpect::infer_receiver_type_hint(&expr),
            ReceiverTypeHint::Unknown,
        );
    }

    #[test]
    fn test_infer_field_receiver_is_unknown() {
        let expr = PureExpr::Field {
            expr: Box::new(PureExpr::Path("self".to_string())),
            field: "data".to_string(),
        };
        assert_eq!(
            UnwrapToExpect::infer_receiver_type_hint(&expr),
            ReceiverTypeHint::Unknown,
        );
    }

    #[test]
    fn test_infer_method_call_get_is_option() {
        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("map".to_string())),
            method: "get".to_string(),
            turbofish: None,
            args: vec![PureExpr::Path("key".to_string())],
        };
        assert_eq!(
            UnwrapToExpect::infer_receiver_type_hint(&expr),
            ReceiverTypeHint::LikelyOption,
        );
    }

    #[test]
    fn test_infer_method_call_entry_is_non_option() {
        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("map".to_string())),
            method: "entry".to_string(),
            turbofish: None,
            args: vec![PureExpr::Path("key".to_string())],
        };
        assert_eq!(
            UnwrapToExpect::infer_receiver_type_hint(&expr),
            ReceiverTypeHint::KnownNonOptionResult,
        );
    }

    #[test]
    fn test_infer_method_call_lock_is_result() {
        let expr = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("mutex".to_string())),
            method: "lock".to_string(),
            turbofish: None,
            args: vec![],
        };
        assert_eq!(
            UnwrapToExpect::infer_receiver_type_hint(&expr),
            ReceiverTypeHint::LikelyResult,
        );
    }

    #[test]
    fn test_confidence_higher_for_known_types() {
        let rule = UnwrapToExpect::new();

        // Known Option method → higher confidence
        let option_receiver = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("map".to_string())),
            method: "get".to_string(),
            turbofish: None,
            args: vec![],
        };
        let option_conf =
            rule.calculate_confidence(&option_receiver, ReceiverTypeHint::LikelyOption);

        // Unknown method → base confidence
        let unknown_receiver = PureExpr::MethodCall {
            receiver: Box::new(PureExpr::Path("x".to_string())),
            method: "custom".to_string(),
            turbofish: None,
            args: vec![],
        };
        let unknown_conf = rule.calculate_confidence(&unknown_receiver, ReceiverTypeHint::Unknown);

        assert!(
            option_conf > unknown_conf,
            "known Option confidence ({option_conf}) should be > unknown ({unknown_conf})"
        );
    }

    #[test]
    fn test_generate_message_with_type_hint() {
        let rule = UnwrapToExpect::new();

        let msg_opt = rule.generate_message(
            &UnwrapContext::MethodCall("get".to_string()),
            ReceiverTypeHint::LikelyOption,
        );
        assert!(msg_opt.contains("return Some"), "Option hint: {msg_opt}");

        let msg_res = rule.generate_message(
            &UnwrapContext::MethodCall("lock".to_string()),
            ReceiverTypeHint::LikelyResult,
        );
        assert!(msg_res.contains("succeed"), "Result hint: {msg_res}");
    }

    #[test]
    fn test_format_suggestion_includes_caveat_for_unknown() {
        let call = UnwrapCallInfo {
            context: UnwrapContext::Variable("x".to_string()),
            type_hint: ReceiverTypeHint::Unknown,
            suggested_message: "x should be Some/Ok".to_string(),
            confidence: 0.8,
        };
        let suggestion = UnwrapToExpect::format_suggestion(&call);
        assert!(
            suggestion.contains("Ignore"),
            "Unknown type should mention Ignore: {suggestion}"
        );
        assert!(
            suggestion.contains("RS101"),
            "Should reference rule code: {suggestion}"
        );
    }

    #[test]
    fn test_format_suggestion_no_caveat_for_known_option() {
        let call = UnwrapCallInfo {
            context: UnwrapContext::MethodCall("get".to_string()),
            type_hint: ReceiverTypeHint::LikelyOption,
            suggested_message: "get() should return Some".to_string(),
            confidence: 0.9,
        };
        let suggestion = UnwrapToExpect::format_suggestion(&call);
        assert!(
            !suggestion.contains("Ignore"),
            "Known Option should NOT mention Ignore: {suggestion}"
        );
        assert!(
            suggestion.contains("match/if-let"),
            "Option suggestion should mention alternatives: {suggestion}"
        );
    }

    #[test]
    fn test_format_suggestion_no_caveat_for_known_result() {
        let call = UnwrapCallInfo {
            context: UnwrapContext::MethodCall("lock".to_string()),
            type_hint: ReceiverTypeHint::LikelyResult,
            suggested_message: "lock() should succeed".to_string(),
            confidence: 0.9,
        };
        let suggestion = UnwrapToExpect::format_suggestion(&call);
        assert!(
            !suggestion.contains("Ignore"),
            "Known Result should NOT mention Ignore: {suggestion}"
        );
        assert!(
            suggestion.contains("propagate error"),
            "Result suggestion should mention ? operator: {suggestion}"
        );
    }
}