ryo-analysis 0.1.0

Code graph and discovery engine for the RYO project
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
//! DetailStore - Cached symbol details for O(1) access.
//!
//! Extracts and caches detailed information from PureAST for fast lookup.
//! Updated at Tick boundaries when symbols are modified.
//!
//! # Design
//!
//! - **Tick内読み取り**: O(1) via SecondaryMap
//! - **Tick境界更新**: rebuild_affected() for changed symbols only
//! - **Single Source**: PureFile remains the source of truth
//!
//! # Example
//!
//! ```ignore
//! let ctx = AnalysisContext::from_path_files(files, "my_crate");
//!
//! // O(1) access during Tick
//! if let Some(detail) = ctx.detail_store.function(symbol_id) {
//!     println!("is_async: {}", detail.is_async);
//! }
//!
//! // At Tick boundary
//! ctx.detail_store.rebuild_affected(&changed_ids, &ctx.registry, &ctx.files);
//! ```

use crate::ast::ASTRegistry;
use crate::context::ImHashMap;
use crate::symbol::{SymbolId, SymbolRegistry};
use crate::SymbolKind;
use ryo_source::pure::{
    PureEnum, PureFields, PureFile, PureFn, PureGenerics, PureImpl, PureItem, PureParam,
    PureStruct, PureTrait, PureType, PureVis,
};
use ryo_symbol::{SymbolPathResolver, WorkspaceFilePath};
use serde::{Deserialize, Serialize};
use slotmap::SecondaryMap;
use std::collections::HashMap;
use std::sync::Arc;

// ============================================================================
// Common Types
// ============================================================================

/// Generic parameters info (simplified).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GenericInfo {
    /// Type parameters: ["T", "U"]
    pub type_params: Vec<String>,
    /// Lifetimes: ["'a", "'b"]
    pub lifetimes: Vec<String>,
    /// Const parameters: [("N", "usize")]
    pub const_params: Vec<(String, String)>,
}

impl GenericInfo {
    /// Check if there are no generics.
    pub fn is_empty(&self) -> bool {
        self.type_params.is_empty() && self.lifetimes.is_empty() && self.const_params.is_empty()
    }
}

/// Parameter info for functions/methods.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParamInfo {
    /// Parameter name.
    pub name: String,
    /// Type as string.
    pub ty: String,
    /// Is this a self parameter?
    pub is_self: bool,
    /// Is mutable (for &mut self)?
    pub is_mut: bool,
}

/// Field info for structs/enums.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldInfo {
    /// Field name.
    pub name: String,
    /// Type as string.
    pub ty: String,
    /// Is publicly visible?
    pub is_public: bool,
}

// ============================================================================
// Detail Types
// ============================================================================

/// Function/method details.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionDetail {
    // --- Modifiers ---
    /// Is async fn?
    pub is_async: bool,
    /// Is const fn?
    pub is_const: bool,
    /// Is unsafe fn?
    pub is_unsafe: bool,

    // --- Signature ---
    /// Parameters.
    pub params: Vec<ParamInfo>,
    /// Return type (None = unit).
    pub return_type: Option<String>,
    /// Generic parameters.
    pub generics: GenericInfo,

    // --- Method-specific ---
    /// Is this a method (in impl/trait)?
    pub is_method: bool,
    /// Self type for methods (e.g., "Foo" in `impl Foo`).
    pub self_ty: Option<String>,
    /// Trait being implemented (e.g., "Clone" in `impl Clone for Foo`).
    pub trait_impl: Option<String>,
    /// Has self parameter (&self, &mut self, self).
    pub has_self: bool,

    // --- Attributes ---
    /// Attribute paths (e.g., ["deprecated", "allow", "inline"]).
    #[serde(default)]
    pub attrs: Vec<String>,
}

/// Struct kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StructKind {
    /// Named fields: `struct Foo { x: i32 }`
    Named,
    /// Tuple struct: `struct Foo(i32, i32)`
    Tuple,
    /// Unit struct: `struct Foo;`
    Unit,
}

/// Struct details.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StructDetail {
    /// Fields.
    pub fields: Vec<FieldInfo>,
    /// Struct kind.
    pub kind: StructKind,
    /// Generic parameters.
    pub generics: GenericInfo,
    /// Attribute paths (e.g., ["derive", "serde"]).
    #[serde(default)]
    pub attrs: Vec<String>,
}

/// Enum variant info.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VariantInfo {
    /// Variant name.
    pub name: String,
    /// Fields (empty for unit variants).
    pub fields: Vec<FieldInfo>,
    /// Discriminant value if specified.
    pub discriminant: Option<String>,
}

/// Enum details.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnumDetail {
    /// Variants.
    pub variants: Vec<VariantInfo>,
    /// Generic parameters.
    pub generics: GenericInfo,
    /// Attribute paths (e.g., ["derive", "repr"]).
    #[serde(default)]
    pub attrs: Vec<String>,
}

/// Trait details.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraitDetail {
    /// Is unsafe trait?
    pub is_unsafe: bool,
    /// Is auto trait?
    pub is_auto: bool,
    /// Supertraits.
    pub supertraits: Vec<String>,
    /// Method names.
    pub methods: Vec<String>,
    /// Associated type names.
    pub types: Vec<String>,
    /// Generic parameters.
    pub generics: GenericInfo,
    /// Attribute paths (e.g., ["async_trait"]).
    #[serde(default)]
    pub attrs: Vec<String>,
}

/// Impl block details.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImplDetail {
    /// Is unsafe impl?
    pub is_unsafe: bool,
    /// Self type being implemented.
    pub self_ty: String,
    /// Trait being implemented (None for inherent impl).
    pub trait_: Option<String>,
    /// Method names.
    pub methods: Vec<String>,
    /// Generic parameters.
    pub generics: GenericInfo,
    /// Attribute paths (e.g., ["automatically_derived"]).
    #[serde(default)]
    pub attrs: Vec<String>,
}

// ============================================================================
// DetailStore
// ============================================================================

/// Cached symbol details for O(1) access.
///
/// # Thread Safety
///
/// DetailStore is designed for single-threaded access within a Tick.
/// Updates happen at Tick boundaries under Executor control.
///
/// NOTE: Deserialize is NOT derived because DetailStore uses SecondaryMap<SymbolId, ...>
/// and SymbolId is process-specific (SlotMap key). Serialization is supported for
/// debugging/inspection purposes only.
#[derive(Clone, Serialize)]
pub struct DetailStore {
    functions: SecondaryMap<SymbolId, FunctionDetail>,
    structs: SecondaryMap<SymbolId, StructDetail>,
    enums: SecondaryMap<SymbolId, EnumDetail>,
    traits: SecondaryMap<SymbolId, TraitDetail>,
    impls: SecondaryMap<SymbolId, ImplDetail>,
}

impl DetailStore {
    /// Create a new empty store.
    pub fn new() -> Self {
        Self {
            functions: SecondaryMap::new(),
            structs: SecondaryMap::new(),
            enums: SecondaryMap::new(),
            traits: SecondaryMap::new(),
            impls: SecondaryMap::new(),
        }
    }

    // ========================================================================
    // O(1) Accessors
    // ========================================================================

    /// Get function detail.
    #[inline]
    pub fn function(&self, id: SymbolId) -> Option<&FunctionDetail> {
        self.functions.get(id)
    }

    /// Get struct detail.
    #[inline]
    pub fn struct_(&self, id: SymbolId) -> Option<&StructDetail> {
        self.structs.get(id)
    }

    /// Get enum detail.
    #[inline]
    pub fn enum_(&self, id: SymbolId) -> Option<&EnumDetail> {
        self.enums.get(id)
    }

    /// Get trait detail.
    #[inline]
    pub fn trait_(&self, id: SymbolId) -> Option<&TraitDetail> {
        self.traits.get(id)
    }

    /// Get impl detail.
    #[inline]
    pub fn impl_(&self, id: SymbolId) -> Option<&ImplDetail> {
        self.impls.get(id)
    }

    // ========================================================================
    // Build & Update
    // ========================================================================

    /// Build DetailStore from WorkspaceFilePath-keyed files.
    ///
    /// **Deprecated**: Use `rebuild_for_symbols` for incremental updates from ASTRegistry.
    /// This method is only needed for initial construction before ASTRegistry exists.
    #[deprecated(
        since = "0.1.0",
        note = "Use rebuild_for_symbols() for incremental updates. This is only for initial construction."
    )]
    pub fn build_all_workspace(
        registry: &SymbolRegistry,
        files: &HashMap<WorkspaceFilePath, PureFile>,
        crate_name: &str,
    ) -> Self {
        let mut store = Self::new();
        let resolver = SymbolPathResolver::new(crate_name);

        // Build module-to-file mapping for efficient lookup
        // module_path → (&WorkspaceFilePath, &PureFile)
        let module_file_map: HashMap<String, (&WorkspaceFilePath, &PureFile)> = files
            .iter()
            .map(|(path, file)| {
                let mod_path = resolver.module_path_str(path);
                (mod_path, (path, file))
            })
            .collect();

        for (id, path) in registry.iter() {
            if let Some(kind) = registry.kind(id) {
                let symbol_name = path.name();
                let parent_path = path.parent().map(|p| p.to_string()).unwrap_or_default();

                // For methods in impl blocks, the parent is "<impl Type>" which doesn't match
                // module paths. We need to go one level up to find the actual module.
                let module_path = if parent_path.contains("<impl") {
                    path.parent()
                        .and_then(|p| p.parent())
                        .map(|p| p.to_string())
                        .unwrap_or_default()
                } else {
                    parent_path
                };

                // Find the file containing this symbol
                if let Some((_path, file)) = module_file_map.get(&module_path) {
                    store.extract_detail_direct(id, kind, symbol_name, file);
                }
            }
        }

        store
    }

    /// Build from Arc-wrapped files (for use with AnalysisContext.files).
    ///
    /// This variant accepts `ImHashMap<WorkspaceFilePath, Arc<PureFile>>` which
    /// is the storage format used by AnalysisContext after fork-on-write.
    ///
    /// **Deprecated**: Use `rebuild_for_symbols` for incremental updates from ASTRegistry.
    /// This method is only needed for initial construction before ASTRegistry exists.
    #[deprecated(
        since = "0.1.0",
        note = "Use rebuild_for_symbols() for incremental updates. This is only for initial construction."
    )]
    pub fn build_from_arc_files(
        registry: &SymbolRegistry,
        files: &ImHashMap<WorkspaceFilePath, Arc<PureFile>>,
        crate_name: &str,
    ) -> Self {
        let mut store = Self::new();
        let resolver = SymbolPathResolver::new(crate_name);

        // Build module-to-file mapping for efficient lookup
        // module_path → &PureFile
        let module_file_map: HashMap<String, &PureFile> = files
            .iter()
            .map(|(path, file)| {
                let mod_path = resolver.module_path_str(path);
                (mod_path, file.as_ref())
            })
            .collect();

        for (id, path) in registry.iter() {
            if let Some(kind) = registry.kind(id) {
                let symbol_name = path.name();
                let parent_path = path.parent().map(|p| p.to_string()).unwrap_or_default();

                // For methods in impl blocks, the parent is "<impl Type>" which doesn't match
                // module paths. We need to go one level up to find the actual module.
                let module_path = if parent_path.contains("<impl") {
                    path.parent()
                        .and_then(|p| p.parent())
                        .map(|p| p.to_string())
                        .unwrap_or_default()
                } else {
                    parent_path
                };

                // Find the file containing this symbol
                if let Some(file) = module_file_map.get(&module_path) {
                    store.extract_detail_direct(id, kind, symbol_name, file);
                }
            }
        }

        store
    }

    /// Rebuild details for affected symbols (Tick boundary update).
    ///
    /// Uses WorkspaceFilePath-keyed files for the new architecture.
    pub fn rebuild_affected_workspace(
        &mut self,
        affected: &[SymbolId],
        registry: &SymbolRegistry,
        files: &ImHashMap<WorkspaceFilePath, Arc<PureFile>>,
        crate_name: &str,
    ) {
        let resolver = SymbolPathResolver::new(crate_name);

        // Build module-to-file mapping for efficient lookup
        let module_file_map: HashMap<String, &PureFile> = files
            .iter()
            .map(|(path, file)| {
                let mod_path = resolver.module_path_str(path);
                (mod_path, file.as_ref())
            })
            .collect();

        for &id in affected {
            // Remove old details
            self.remove(id);

            // Re-extract if symbol still exists
            if let Some(kind) = registry.kind(id) {
                if let Some(path) = registry.resolve(id) {
                    let symbol_name = path.name();
                    let parent_path = path.parent().map(|p| p.to_string()).unwrap_or_default();

                    // For methods in impl blocks, go up to the module level
                    let module_path = if parent_path.contains("<impl") {
                        path.parent()
                            .and_then(|p| p.parent())
                            .map(|p| p.to_string())
                            .unwrap_or_default()
                    } else {
                        parent_path
                    };

                    // Find the file and extract details
                    if let Some(file) = module_file_map.get(&module_path) {
                        self.extract_detail_direct(id, kind, symbol_name, file);
                    }
                }
            }
        }
    }

    /// Remove all details for a symbol.
    pub fn remove(&mut self, id: SymbolId) {
        self.functions.remove(id);
        self.structs.remove(id);
        self.enums.remove(id);
        self.traits.remove(id);
        self.impls.remove(id);
    }

    /// Rebuild details for affected symbols using ASTRegistry.
    ///
    /// This is the Symbol-based incremental update path that:
    /// 1. Removes existing details for affected symbols
    /// 2. Extracts new details directly from ASTRegistry (no file I/O)
    ///
    /// Note: Method details require impl block context, so they are
    /// rebuilt from the parent impl block if available.
    pub fn rebuild_for_symbols(&mut self, affected_ids: &[SymbolId], ast_registry: &ASTRegistry) {
        for &id in affected_ids {
            // Remove existing detail
            self.remove(id);

            // Extract new detail from ASTRegistry
            if let Some(item) = ast_registry.get(id) {
                self.extract_from_item(id, item);
            }
        }
    }

    /// Extract and store detail from a PureItem.
    fn extract_from_item(&mut self, id: SymbolId, item: &PureItem) {
        match item {
            PureItem::Fn(f) => {
                // Top-level function (no self_ty or trait_impl)
                let detail = build_function_detail(f, None, None);
                self.functions.insert(id, detail);
            }
            PureItem::Struct(s) => {
                let detail = build_struct_detail(s);
                self.structs.insert(id, detail);
            }
            PureItem::Enum(e) => {
                let detail = build_enum_detail(e);
                self.enums.insert(id, detail);
            }
            PureItem::Trait(t) => {
                let detail = build_trait_detail(t);
                self.traits.insert(id, detail);
            }
            PureItem::Impl(i) => {
                let detail = build_impl_detail(i);
                self.impls.insert(id, detail);
            }
            // Other item types don't have details
            _ => {}
        }
    }

    /// Extract and store detail directly from a file (without span lookup).
    fn extract_detail_direct(
        &mut self,
        id: SymbolId,
        kind: SymbolKind,
        symbol_name: &str,
        file: &PureFile,
    ) {
        match kind {
            SymbolKind::Function => {
                // トップレベル関数のみを検索
                if let Some(detail) = extract_toplevel_function_detail(file, symbol_name) {
                    self.functions.insert(id, detail);
                }
            }
            SymbolKind::Method => {
                // impl/trait ブロック内のメソッドのみを検索
                if let Some(detail) = extract_method_detail(file, symbol_name) {
                    self.functions.insert(id, detail);
                }
            }
            SymbolKind::Struct => {
                if let Some(detail) = extract_struct_detail(file, symbol_name) {
                    self.structs.insert(id, detail);
                }
            }
            SymbolKind::Enum => {
                if let Some(detail) = extract_enum_detail(file, symbol_name) {
                    self.enums.insert(id, detail);
                }
            }
            SymbolKind::Trait => {
                if let Some(detail) = extract_trait_detail(file, symbol_name) {
                    self.traits.insert(id, detail);
                }
            }
            SymbolKind::Impl => {
                if let Some(detail) = extract_impl_detail(file, symbol_name) {
                    self.impls.insert(id, detail);
                }
            }
            _ => {}
        }
    }

    // ========================================================================
    // Statistics
    // ========================================================================

    /// Get total number of cached details.
    pub fn len(&self) -> usize {
        self.functions.len()
            + self.structs.len()
            + self.enums.len()
            + self.traits.len()
            + self.impls.len()
    }

    /// Check if store is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

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

// ============================================================================
// Extraction Functions
// ============================================================================

/// Convert PureGenerics to GenericInfo.
fn convert_generics(generics: &PureGenerics) -> GenericInfo {
    let mut info = GenericInfo::default();

    for param in &generics.params {
        match param {
            ryo_source::pure::PureGenericParam::Type { name, .. } => {
                info.type_params.push(name.clone());
            }
            ryo_source::pure::PureGenericParam::Lifetime { name, .. } => {
                info.lifetimes.push(name.clone());
            }
            ryo_source::pure::PureGenericParam::Const { name, ty } => {
                info.const_params.push((name.clone(), ty.clone()));
            }
        }
    }

    info
}

/// Convert PureType to string representation.
fn type_to_string(ty: &PureType) -> String {
    match ty {
        PureType::Path(p) => p.clone(),
        PureType::Ref {
            lifetime,
            is_mut,
            ty,
        } => {
            let lt = lifetime
                .as_ref()
                .map(|l| format!("{} ", l))
                .unwrap_or_default();
            let m = if *is_mut { "mut " } else { "" };
            format!("&{}{}{}", lt, m, type_to_string(ty))
        }
        PureType::Tuple(types) => {
            let inner: Vec<_> = types.iter().map(type_to_string).collect();
            format!("({})", inner.join(", "))
        }
        PureType::Array { ty, len } => format!("[{}; {}]", type_to_string(ty), len),
        PureType::Slice(ty) => format!("[{}]", type_to_string(ty)),
        PureType::Fn { params, ret } => {
            let ps: Vec<_> = params.iter().map(type_to_string).collect();
            let r = ret
                .as_ref()
                .map(|t| format!(" -> {}", type_to_string(t)))
                .unwrap_or_default();
            format!("fn({}){}", ps.join(", "), r)
        }
        PureType::ImplTrait(bounds) => format!("impl {}", bounds.join(" + ")),
        PureType::TraitObject(bounds) => format!("dyn {}", bounds.join(" + ")),
        PureType::Infer => "_".to_string(),
        PureType::Never => "!".to_string(),
        PureType::Other(s) => s.clone(),
    }
}

/// Convert PureVis to is_public bool.
fn is_public(vis: &PureVis) -> bool {
    matches!(vis, PureVis::Public | PureVis::Crate)
}

/// Extract FunctionDetail for top-level functions only (not methods).
fn extract_toplevel_function_detail(file: &PureFile, symbol_name: &str) -> Option<FunctionDetail> {
    for item in &file.items {
        if let PureItem::Fn(f) = item {
            if f.name == symbol_name {
                return Some(build_function_detail(f, None, None));
            }
        }
    }
    None
}

/// Extract FunctionDetail for methods in impl/trait blocks only.
fn extract_method_detail(file: &PureFile, symbol_name: &str) -> Option<FunctionDetail> {
    for item in &file.items {
        // Check in impl blocks
        if let PureItem::Impl(impl_block) = item {
            for impl_item in &impl_block.items {
                if let ryo_source::pure::PureImplItem::Fn(f) = impl_item {
                    if f.name == symbol_name {
                        return Some(build_function_detail(
                            f,
                            Some(&impl_block.self_ty),
                            impl_block.trait_.as_deref(),
                        ));
                    }
                }
            }
        }
        // Check in trait blocks
        if let PureItem::Trait(trait_block) = item {
            for trait_item in &trait_block.items {
                if let ryo_source::pure::PureTraitItem::Fn(f) = trait_item {
                    if f.name == symbol_name {
                        return Some(build_function_detail(f, None, Some(&trait_block.name)));
                    }
                }
            }
        }
    }
    None
}

#[cfg(test)]
/// Extract FunctionDetail from PureFile by symbol name.
fn extract_function_detail(
    file: &PureFile,
    symbol_name: &str,
    self_ty: Option<&str>,
    trait_impl: Option<&str>,
) -> Option<FunctionDetail> {
    // Find function by name
    for item in &file.items {
        if let PureItem::Fn(f) = item {
            if f.name == symbol_name {
                return Some(build_function_detail(f, self_ty, trait_impl));
            }
        }
        // Check in impl blocks
        if let PureItem::Impl(impl_block) = item {
            for impl_item in &impl_block.items {
                if let ryo_source::pure::PureImplItem::Fn(f) = impl_item {
                    if f.name == symbol_name {
                        return Some(build_function_detail(
                            f,
                            Some(&impl_block.self_ty),
                            impl_block.trait_.as_deref(),
                        ));
                    }
                }
            }
        }
        // Check in trait blocks
        if let PureItem::Trait(trait_block) = item {
            for trait_item in &trait_block.items {
                if let ryo_source::pure::PureTraitItem::Fn(f) = trait_item {
                    if f.name == symbol_name {
                        return Some(build_function_detail(f, None, Some(&trait_block.name)));
                    }
                }
            }
        }
    }
    None
}

/// Build FunctionDetail from PureFn.
fn build_function_detail(
    f: &PureFn,
    self_ty: Option<&str>,
    trait_impl: Option<&str>,
) -> FunctionDetail {
    let mut params = Vec::new();
    let mut has_self = false;

    for param in &f.params {
        match param {
            PureParam::SelfValue { is_ref, is_mut } => {
                has_self = true;
                let ty = if *is_ref {
                    if *is_mut {
                        "&mut Self"
                    } else {
                        "&Self"
                    }
                } else {
                    "Self"
                };
                params.push(ParamInfo {
                    name: "self".to_string(),
                    ty: ty.to_string(),
                    is_self: true,
                    is_mut: *is_mut,
                });
            }
            PureParam::Typed { name, ty } => {
                params.push(ParamInfo {
                    name: name.clone(),
                    ty: type_to_string(ty),
                    is_self: false,
                    is_mut: false,
                });
            }
        }
    }

    FunctionDetail {
        is_async: f.is_async,
        is_const: f.is_const,
        is_unsafe: f.is_unsafe,
        params,
        return_type: f.ret.as_ref().map(type_to_string),
        generics: convert_generics(&f.generics),
        is_method: self_ty.is_some(),
        self_ty: self_ty.map(String::from),
        trait_impl: trait_impl.map(String::from),
        has_self,
        attrs: extract_attr_paths(&f.attrs),
    }
}

/// Extract StructDetail from PureFile by symbol name.
fn extract_struct_detail(file: &PureFile, symbol_name: &str) -> Option<StructDetail> {
    for item in &file.items {
        if let PureItem::Struct(s) = item {
            if s.name == symbol_name {
                return Some(build_struct_detail(s));
            }
        }
    }
    None
}

/// Build StructDetail from PureStruct.
fn build_struct_detail(s: &PureStruct) -> StructDetail {
    let (fields, kind) = match &s.fields {
        PureFields::Named(fs) => {
            let fields = fs
                .iter()
                .map(|f| FieldInfo {
                    name: f.name.clone(),
                    ty: type_to_string(&f.ty),
                    is_public: is_public(&f.vis),
                })
                .collect();
            (fields, StructKind::Named)
        }
        PureFields::Tuple(types) => {
            let fields = types
                .iter()
                .enumerate()
                .map(|(i, ty)| FieldInfo {
                    name: i.to_string(),
                    ty: type_to_string(ty),
                    is_public: true, // tuple fields follow struct visibility
                })
                .collect();
            (fields, StructKind::Tuple)
        }
        PureFields::Unit => (Vec::new(), StructKind::Unit),
    };

    StructDetail {
        fields,
        kind,
        generics: convert_generics(&s.generics),
        attrs: extract_attr_paths(&s.attrs),
    }
}

/// Extract EnumDetail from PureFile by symbol name.
fn extract_enum_detail(file: &PureFile, symbol_name: &str) -> Option<EnumDetail> {
    for item in &file.items {
        if let PureItem::Enum(e) = item {
            if e.name == symbol_name {
                return Some(build_enum_detail(e));
            }
        }
    }
    None
}

/// Build EnumDetail from PureEnum.
fn build_enum_detail(e: &PureEnum) -> EnumDetail {
    let variants = e
        .variants
        .iter()
        .map(|v| {
            let fields = match &v.fields {
                PureFields::Named(fs) => fs
                    .iter()
                    .map(|f| FieldInfo {
                        name: f.name.clone(),
                        ty: type_to_string(&f.ty),
                        is_public: is_public(&f.vis),
                    })
                    .collect(),
                PureFields::Tuple(types) => types
                    .iter()
                    .enumerate()
                    .map(|(i, ty)| FieldInfo {
                        name: i.to_string(),
                        ty: type_to_string(ty),
                        is_public: true,
                    })
                    .collect(),
                PureFields::Unit => Vec::new(),
            };

            VariantInfo {
                name: v.name.clone(),
                fields,
                discriminant: v.discriminant.clone(),
            }
        })
        .collect();

    EnumDetail {
        variants,
        generics: convert_generics(&e.generics),
        attrs: extract_attr_paths(&e.attrs),
    }
}

/// Extract TraitDetail from PureFile by symbol name.
fn extract_trait_detail(file: &PureFile, symbol_name: &str) -> Option<TraitDetail> {
    for item in &file.items {
        if let PureItem::Trait(t) = item {
            if t.name == symbol_name {
                return Some(build_trait_detail(t));
            }
        }
    }
    None
}

/// Build TraitDetail from PureTrait.
fn build_trait_detail(t: &PureTrait) -> TraitDetail {
    let mut methods = Vec::new();
    let mut types = Vec::new();

    for item in &t.items {
        match item {
            ryo_source::pure::PureTraitItem::Fn(f) => methods.push(f.name.clone()),
            ryo_source::pure::PureTraitItem::Type { name, .. } => types.push(name.clone()),
            _ => {}
        }
    }

    TraitDetail {
        is_unsafe: t.is_unsafe,
        is_auto: t.is_auto,
        supertraits: t.supertraits.clone(),
        methods,
        types,
        generics: convert_generics(&t.generics),
        attrs: extract_attr_paths(&t.attrs),
    }
}

/// Extract ImplDetail from PureFile by symbol name.
///
/// Symbol name for impl blocks is like `<impl Trait for Type>` or `<impl Type>`.
fn extract_impl_detail(file: &PureFile, symbol_name: &str) -> Option<ImplDetail> {
    for item in &file.items {
        if let PureItem::Impl(i) = item {
            // Build the expected impl name and compare
            let impl_name = if let Some(ref trait_name) = i.trait_ {
                format!("<impl {} for {}>", trait_name, i.self_ty)
            } else {
                format!("<impl {}>", i.self_ty)
            };
            if impl_name == symbol_name {
                return Some(build_impl_detail(i));
            }
        }
    }
    None
}

/// Build ImplDetail from PureImpl.
fn build_impl_detail(i: &PureImpl) -> ImplDetail {
    let methods = i
        .items
        .iter()
        .filter_map(|item| {
            if let ryo_source::pure::PureImplItem::Fn(f) = item {
                Some(f.name.clone())
            } else {
                None
            }
        })
        .collect();

    ImplDetail {
        is_unsafe: i.is_unsafe,
        self_ty: i.self_ty.clone(),
        trait_: i.trait_.clone(),
        methods,
        generics: convert_generics(&i.generics),
        attrs: extract_attr_paths(&i.attrs),
    }
}

/// Extract attribute representations from PureAttribute list.
///
/// Returns both the path and full representation with arguments:
/// - `#[deprecated]` → ["deprecated"]
/// - `#[allow(dead_code)]` → ["allow", "allow(dead_code)"]
/// - `#[derive(Debug, Clone)]` → ["derive", "derive(Debug, Clone)"]
fn extract_attr_paths(attrs: &[ryo_source::pure::PureAttribute]) -> Vec<String> {
    use ryo_source::pure::PureAttrMeta;

    let mut result = Vec::new();
    for attr in attrs {
        // Always include the path
        result.push(attr.path.clone());

        // If there are arguments, also include the full form
        match &attr.meta {
            PureAttrMeta::List(args) if !args.is_empty() => {
                result.push(format!("{}({})", attr.path, args));
            }
            PureAttrMeta::NameValue(value) if !value.is_empty() => {
                result.push(format!("{} = {}", attr.path, value));
            }
            _ => {}
        }
    }
    result
}

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

    #[test]
    fn test_generic_info_is_empty() {
        let info = GenericInfo::default();
        assert!(info.is_empty());

        let info = GenericInfo {
            type_params: vec!["T".to_string()],
            ..Default::default()
        };
        assert!(!info.is_empty());
    }

    #[test]
    fn test_type_to_string() {
        assert_eq!(
            type_to_string(&PureType::Path("String".to_string())),
            "String"
        );
        assert_eq!(type_to_string(&PureType::Infer), "_");
        assert_eq!(type_to_string(&PureType::Never), "!");
    }

    #[test]
    fn test_detail_store_new() {
        let store = DetailStore::new();
        assert!(store.is_empty());
        assert_eq!(store.len(), 0);
    }

    #[test]
    fn test_extract_method_with_mut_self() {
        use ryo_source::pure::PureFile;

        let source = r#"
            struct Foo;
            impl Foo {
                pub fn get_mut(&mut self) -> &mut i32 {
                    &mut self.0
                }
            }
        "#;

        let file = PureFile::from_source(source).unwrap();
        let detail = extract_function_detail(&file, "get_mut", None, None);

        assert!(detail.is_some(), "get_mut should be found");
        let detail = detail.unwrap();
        assert!(detail.has_self, "get_mut should have self");
        assert!(!detail.params.is_empty(), "get_mut should have params");

        let first_param = &detail.params[0];
        assert!(first_param.is_self, "first param should be self");
        assert!(first_param.is_mut, "first param should be mut");
        assert_eq!(first_param.ty, "&mut Self", "self type should be &mut Self");
    }

    #[test]
    fn test_extract_toplevel_vs_method_same_name() {
        use ryo_source::pure::PureFile;

        // This simulates the case where both a free function and a method
        // have the same name "execute"
        let source = r#"
            struct Executor;

            impl Executor {
                pub fn execute(&self, cmd: &str) -> bool {
                    true
                }
            }

            pub fn execute(cmd: &str, config: &str) -> bool {
                false
            }
        "#;

        let file = PureFile::from_source(source).unwrap();

        // extract_toplevel_function_detail should only find the free function
        let toplevel_detail = extract_toplevel_function_detail(&file, "execute");
        assert!(
            toplevel_detail.is_some(),
            "toplevel execute should be found"
        );
        let toplevel_detail = toplevel_detail.unwrap();
        assert!(
            !toplevel_detail.has_self,
            "toplevel execute should NOT have self"
        );
        assert!(
            !toplevel_detail.params.iter().any(|p| p.is_self),
            "toplevel execute params should not contain self"
        );

        // extract_method_detail should only find the method
        let method_detail = extract_method_detail(&file, "execute");
        assert!(method_detail.is_some(), "method execute should be found");
        let method_detail = method_detail.unwrap();
        assert!(method_detail.has_self, "method execute SHOULD have self");
        assert!(
            method_detail.params.iter().any(|p| p.is_self),
            "method execute params should contain self"
        );
        assert_eq!(
            method_detail.params[0].ty, "&Self",
            "method self should be &Self"
        );
    }

    #[test]
    fn test_extract_method_with_ref_self() {
        use ryo_source::pure::PureFile;

        let source = r#"
            struct Reader;
            impl Reader {
                pub fn read(&self, buf: &mut [u8]) -> usize {
                    0
                }
            }
        "#;

        let file = PureFile::from_source(source).unwrap();
        let detail = extract_method_detail(&file, "read");

        assert!(detail.is_some(), "read should be found");
        let detail = detail.unwrap();
        assert!(detail.has_self, "read should have self");
        assert!(!detail.params.is_empty(), "read should have params");

        let first_param = &detail.params[0];
        assert!(first_param.is_self, "first param should be self");
        assert!(!first_param.is_mut, "first param should NOT be mut");
        assert_eq!(first_param.ty, "&Self", "self type should be &Self");
    }

    #[test]
    fn test_extract_method_with_owned_self() {
        use ryo_source::pure::PureFile;

        let source = r#"
            struct Consumer;
            impl Consumer {
                pub fn consume(self) -> i32 {
                    42
                }
            }
        "#;

        let file = PureFile::from_source(source).unwrap();
        let detail = extract_method_detail(&file, "consume");

        assert!(detail.is_some(), "consume should be found");
        let detail = detail.unwrap();
        assert!(detail.has_self, "consume should have self");

        let first_param = &detail.params[0];
        assert!(first_param.is_self, "first param should be self");
        assert!(!first_param.is_mut, "first param should NOT be mut");
        assert_eq!(first_param.ty, "Self", "self type should be Self (owned)");
    }

    #[test]
    fn test_extract_attrs_from_function() {
        use ryo_source::pure::PureFile;

        let source = r#"
            #[deprecated(note = "use new_function instead")]
            #[inline]
            pub fn old_function() {}
        "#;

        let file = PureFile::from_source(source).unwrap();
        let detail = extract_toplevel_function_detail(&file, "old_function");

        assert!(detail.is_some(), "old_function should be found");
        let detail = detail.unwrap();
        assert!(
            detail.attrs.contains(&"deprecated".to_string()),
            "should have deprecated attr"
        );
        assert!(
            detail.attrs.contains(&"inline".to_string()),
            "should have inline attr"
        );
    }

    #[test]
    fn test_extract_attrs_from_struct() {
        use ryo_source::pure::PureFile;

        let source = r#"
            #[derive(Debug, Clone)]
            #[repr(C)]
            pub struct Config {
                pub name: String,
            }
        "#;

        let file = PureFile::from_source(source).unwrap();
        let detail = extract_struct_detail(&file, "Config");

        assert!(detail.is_some(), "Config should be found");
        let detail = detail.unwrap();
        assert!(
            detail.attrs.contains(&"derive".to_string()),
            "should have derive attr"
        );
        assert!(
            detail.attrs.contains(&"repr".to_string()),
            "should have repr attr"
        );
    }
}