bronzite-client 0.2.1

🔮 Client library for querying the Bronzite compile-time reflection daemon from proc-macros
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
//! High-level reflection API for Bronzite.
//!
//! This module provides an ergonomic, type-safe API for compile-time reflection.
//! Types hold references to the client and can navigate relationships fluently.
//!
//! # Example
//!
//! ```ignore
//! use bronzite_client::Crate;
//!
//! let krate = Crate::reflect("my_crate")?;
//!
//! // Query items with patterns
//! let items = krate.items("bevy::prelude::*")?;
//!
//! // Get a specific struct and explore it
//! let user = krate.get_struct("User")?;
//! for field in user.fields()? {
//!     println!("{}: {} (size: {})",
//!         field.name,
//!         field.ty,
//!         field.size.unwrap_or(0)
//!     );
//! }
//!
//! // Check trait implementations
//! if user.implements("Debug")? {
//!     println!("User implements Debug");
//! }
//! ```

use crate::{BronziteClient, Error, Result};
use bronzite_types::{
    AssocConstInfo, AssocTypeInfo, FieldInfo as RawFieldInfo, FunctionSignature, GenericParam,
    LayoutInfo, MethodDetails as RawMethodDetails, TraitDetails as RawTraitDetails,
    TraitImplDetails as RawTraitImpl, TypeDetails, TypeSummary, Visibility,
};
use std::sync::Arc;

// ============================================================================
// Core Reflection Entry Point
// ============================================================================

/// A reflected crate - the main entry point for type reflection.
pub struct Crate {
    name: String,
    client: Arc<BronziteClient>,
}

impl Crate {
    /// Reflect on a crate by name.
    ///
    /// This will connect to the daemon (starting it if needed) and return
    /// a handle for querying types in the specified crate.
    pub fn reflect(crate_name: impl Into<String>) -> Result<Self> {
        crate::ensure_daemon_running(None)?;
        let client = crate::connect()?;
        Ok(Self {
            name: crate_name.into(),
            client: Arc::new(client),
        })
    }

    /// Get the crate name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get all items matching a pattern.
    ///
    /// Supports:
    /// - Exact: `"foo::Bar"`
    /// - Wildcard: `"foo::Bar*"`
    /// - Single-level glob: `"foo::*"` (matches `foo::Bar` but not `foo::bar::Baz`)
    /// - Recursive glob: `"foo::**"` (matches all descendants)
    pub fn items(&self, pattern: &str) -> Result<Vec<Item>> {
        let types = self.client_mut()?.find_types(&self.name, pattern)?;

        types
            .into_iter()
            .map(|summary| Item::from_summary(summary, &self.name, Arc::clone(&self.client)))
            .collect()
    }

    /// Get all structs matching a pattern.
    pub fn structs(&self, pattern: &str) -> Result<Vec<StructDef>> {
        let items = self.items(pattern)?;
        Ok(items
            .into_iter()
            .filter_map(|item| match item {
                Item::Struct(s) => Some(s),
                _ => None,
            })
            .collect())
    }

    /// Get all enums matching a pattern.
    pub fn enums(&self, pattern: &str) -> Result<Vec<EnumDef>> {
        let items = self.items(pattern)?;
        Ok(items
            .into_iter()
            .filter_map(|item| match item {
                Item::Enum(e) => Some(e),
                _ => None,
            })
            .collect())
    }

    /// Get all traits matching a pattern.
    pub fn traits(&self, pattern: &str) -> Result<Vec<TraitDef>> {
        let all_traits = self.client_mut()?.get_traits(&self.name)?;

        let matching: Vec<_> = all_traits
            .into_iter()
            .filter(|t| bronzite_types::path_matches_pattern(&t.path, pattern))
            .collect();

        matching
            .into_iter()
            .map(|info| TraitDef::from_info(info, &self.name, Arc::clone(&self.client)))
            .collect()
    }

    /// Get a specific struct by path.
    pub fn get_struct(&self, path: &str) -> Result<StructDef> {
        let details = self.client_mut()?.get_type(&self.name, path)?;
        StructDef::from_details(details, &self.name, Arc::clone(&self.client))
    }

    /// Get a specific enum by path.
    pub fn get_enum(&self, path: &str) -> Result<EnumDef> {
        let details = self.client_mut()?.get_type(&self.name, path)?;
        EnumDef::from_details(details, &self.name, Arc::clone(&self.client))
    }

    /// Get a specific trait by path.
    pub fn get_trait(&self, path: &str) -> Result<TraitDef> {
        let details = self.client_mut()?.get_trait(&self.name, path)?;
        TraitDef::from_trait_details(details, &self.name, Arc::clone(&self.client))
    }

    /// Get a specific type alias by path.
    pub fn get_type_alias(&self, path: &str) -> Result<TypeAliasDef> {
        let (original, resolved, chain) = self.client_mut()?.resolve_alias(&self.name, path)?;
        Ok(TypeAliasDef {
            path: original,
            resolved_path: resolved,
            resolution_chain: chain,
            crate_name: self.name.clone(),
            client: Arc::clone(&self.client),
        })
    }

    /// Helper to get mutable client access (Arc doesn't need Mutex for single-threaded use).
    fn client_mut(&self) -> Result<&mut BronziteClient> {
        // SAFETY: This is safe in proc-macro context where we're single-threaded.
        // Arc is used for cheap cloning, not thread-safety here.
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

// ============================================================================
// Item Enum - Unified Type Representation
// ============================================================================

/// A unified representation of any Rust item (struct, enum, trait, etc).
///
/// This enum provides a type-safe way to work with different kinds of items
/// discovered through pattern matching or queries. Each variant contains
/// a specific type definition with navigation methods.
///
/// # Example
///
/// ```ignore
/// use bronzite_client::{Crate, Item};
///
/// let krate = Crate::reflect("my_crate")?;
/// for item in krate.items("*")? {
///     match item {
///         Item::Struct(s) => println!("Struct: {}", s.name),
///         Item::Enum(e) => println!("Enum: {}", e.name),
///         Item::Trait(t) => println!("Trait: {}", t.name),
///         Item::TypeAlias(a) => println!("Alias: {}", a.path),
///         Item::Union(u) => println!("Union: {}", u.name),
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub enum Item {
    /// A struct definition
    Struct(StructDef),
    /// An enum definition
    Enum(EnumDef),
    /// A trait definition
    Trait(TraitDef),
    /// A type alias
    TypeAlias(TypeAliasDef),
    /// A union definition
    Union(UnionDef),
}

impl Item {
    /// Get the name of this item.
    pub fn name(&self) -> &str {
        match self {
            Item::Struct(s) => &s.name,
            Item::Enum(e) => &e.name,
            Item::Trait(t) => &t.name,
            Item::TypeAlias(a) => &a.path,
            Item::Union(u) => &u.name,
        }
    }

    /// Get the full path of this item.
    pub fn path(&self) -> &str {
        match self {
            Item::Struct(s) => &s.path,
            Item::Enum(e) => &e.path,
            Item::Trait(t) => &t.path,
            Item::TypeAlias(a) => &a.path,
            Item::Union(u) => &u.path,
        }
    }

    fn from_summary(
        summary: TypeSummary,
        crate_name: &str,
        client: Arc<BronziteClient>,
    ) -> Result<Self> {
        match summary.kind {
            bronzite_types::TypeKind::Struct => Ok(Item::Struct(StructDef {
                name: summary.name,
                path: summary.path,
                generics: summary.generics,
                crate_name: crate_name.to_string(),
                client,
                cached_details: None,
            })),
            bronzite_types::TypeKind::Enum => Ok(Item::Enum(EnumDef {
                name: summary.name,
                path: summary.path,
                generics: summary.generics,
                crate_name: crate_name.to_string(),
                client,
                cached_details: None,
            })),
            bronzite_types::TypeKind::Union => Ok(Item::Union(UnionDef {
                name: summary.name,
                path: summary.path,
                generics: summary.generics,
                crate_name: crate_name.to_string(),
                client,
            })),
            bronzite_types::TypeKind::Trait => {
                // For traits, we need to fetch full details
                let client_mut = unsafe {
                    let ptr = Arc::as_ptr(&client) as *mut BronziteClient;
                    &mut *ptr
                };
                let details = client_mut.get_trait(crate_name, &summary.path)?;
                Ok(Item::Trait(TraitDef::from_trait_details(
                    details, crate_name, client,
                )?))
            }
            _ => Err(Error::UnexpectedResponse),
        }
    }
}

// ============================================================================
// Struct Definition
// ============================================================================

/// A reflected struct definition with navigation methods.
///
/// Provides access to struct metadata and navigation to related types like
/// fields, trait implementations, and methods.
///
/// # Example
///
/// ```ignore
/// use bronzite_client::Crate;
///
/// let krate = Crate::reflect("my_crate")?;
/// let user = krate.get_struct("User")?;
///
/// // Get fields
/// for field in user.fields()? {
///     println!("Field: {} of type {}",
///         field.name.unwrap_or_default(),
///         field.ty
///     );
/// }
///
/// // Check trait implementation
/// if user.implements("Debug")? {
///     println!("User implements Debug");
/// }
///
/// // Get methods
/// for method in user.methods()? {
///     println!("Method: {}", method.name);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct StructDef {
    /// The struct's name (without path)
    pub name: String,
    /// The struct's full path
    pub path: String,
    /// Generic parameters
    pub generics: Vec<GenericParam>,
    crate_name: String,
    client: Arc<BronziteClient>,
    cached_details: Option<Box<TypeDetails>>,
}

impl StructDef {
    fn from_details(
        details: TypeDetails,
        crate_name: &str,
        client: Arc<BronziteClient>,
    ) -> Result<Self> {
        Ok(Self {
            name: details.name.clone(),
            path: details.path.clone(),
            generics: details.generics.clone(),
            crate_name: crate_name.to_string(),
            client,
            cached_details: Some(Box::new(details)),
        })
    }

    /// Get all fields of this struct.
    ///
    /// Returns a vector of [`Field`] objects, each representing a field in the struct.
    /// Fields include metadata like name, type, visibility, size, and offset.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// for field in user.fields()? {
    ///     println!("Field: {} of type {}",
    ///         field.name.as_deref().unwrap_or("<unnamed>"),
    ///         field.ty
    ///     );
    ///     if let Some(size) = field.size {
    ///         println!("  Size: {} bytes", size);
    ///     }
    /// }
    /// ```
    pub fn fields(&self) -> Result<Vec<Field>> {
        let fields = self
            .client_mut()?
            .get_fields(&self.crate_name, &self.path)?;
        Ok(fields
            .into_iter()
            .map(|f| Field::from_raw(f, &self.crate_name, Arc::clone(&self.client)))
            .collect())
    }

    /// Get all trait implementations for this struct.
    ///
    /// Returns a vector of [`TraitImpl`] objects containing information about each
    /// trait implementation, including methods, associated types, and source code.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// for impl_block in user.trait_impls()? {
    ///     println!("Implements: {}", impl_block.trait_path);
    ///     for method in impl_block.methods() {
    ///         println!("  - {}", method.name);
    ///     }
    /// }
    /// ```
    pub fn trait_impls(&self) -> Result<Vec<TraitImpl>> {
        let impls = self
            .client_mut()?
            .get_trait_impls(&self.crate_name, &self.path)?;
        Ok(impls
            .into_iter()
            .map(|i| TraitImpl::from_raw(i, &self.crate_name, Arc::clone(&self.client)))
            .collect())
    }

    /// Check if this struct implements a specific trait.
    ///
    /// This is a convenient way to test for trait implementation without
    /// fetching all trait impls.
    ///
    /// # Arguments
    ///
    /// * `trait_path` - The trait path to check (e.g., "Debug", "std::fmt::Display")
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// if user.implements("Debug")? {
    ///     println!("User can be debug-printed");
    /// }
    /// if user.implements("std::clone::Clone")? {
    ///     println!("User can be cloned");
    /// }
    /// ```
    pub fn implements(&self, trait_path: &str) -> Result<bool> {
        let (implements, _) =
            self.client_mut()?
                .check_impl(&self.crate_name, &self.path, trait_path)?;
        Ok(implements)
    }

    /// Get inherent methods (from `impl StructName { ... }` blocks).
    ///
    /// Returns methods defined in inherent impl blocks, not trait implementations.
    /// Each [`Method`] includes the signature, body source, and navigation to
    /// parameter/return types.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// for method in user.methods()? {
    ///     println!("Method: {}", method.signature);
    ///     if let Some(body) = &method.body_source {
    ///         println!("  Implementation: {}", body);
    ///     }
    ///     if let Some(ret_type) = method.return_type_def()? {
    ///         println!("  Returns: {}", ret_type.name());
    ///     }
    /// }
    /// ```
    pub fn methods(&self) -> Result<Vec<Method>> {
        let impls = self
            .client_mut()?
            .get_inherent_impls(&self.crate_name, &self.path)?;
        Ok(impls
            .into_iter()
            .flat_map(|impl_block| {
                impl_block
                    .methods
                    .into_iter()
                    .map(|m| Method::from_raw(m, &self.crate_name, Arc::clone(&self.client)))
            })
            .collect())
    }

    /// Get memory layout information for this struct.
    ///
    /// Returns [`LayoutInfo`] containing size, alignment, field offsets,
    /// and auto-trait implementations (Send, Sync, Copy).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// let layout = user.layout()?;
    /// println!("Size: {} bytes", layout.size);
    /// println!("Alignment: {} bytes", layout.align);
    /// println!("Is Copy: {}", layout.is_copy);
    /// ```
    pub fn layout(&self) -> Result<LayoutInfo> {
        self.client_mut()?.get_layout(&self.crate_name, &self.path)
    }

    /// Get the source code of this struct definition.
    pub fn source(&self) -> Option<&str> {
        self.details().and_then(|d| d.source.as_deref())
    }

    /// Get detailed type information.
    pub fn details(&self) -> Option<&TypeDetails> {
        self.cached_details.as_deref()
    }

    /// Get visibility of this struct.
    pub fn visibility(&self) -> Option<&Visibility> {
        self.details().map(|d| &d.visibility)
    }

    /// Get doc comments.
    pub fn docs(&self) -> Option<&str> {
        self.details().and_then(|d| d.docs.as_deref())
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

// ============================================================================
// Enum Definition
// ============================================================================

/// A reflected enum definition.
#[derive(Debug, Clone)]
pub struct EnumDef {
    pub name: String,
    pub path: String,
    pub generics: Vec<GenericParam>,
    crate_name: String,
    client: Arc<BronziteClient>,
    cached_details: Option<Box<TypeDetails>>,
}

impl EnumDef {
    fn from_details(
        details: TypeDetails,
        crate_name: &str,
        client: Arc<BronziteClient>,
    ) -> Result<Self> {
        Ok(Self {
            name: details.name.clone(),
            path: details.path.clone(),
            generics: details.generics.clone(),
            crate_name: crate_name.to_string(),
            client,
            cached_details: Some(Box::new(details)),
        })
    }

    /// Get the enum's variants.
    pub fn variants(&self) -> Option<&[bronzite_types::EnumVariantInfo]> {
        self.details().and_then(|d| d.variants.as_deref())
    }

    /// Get trait implementations for this enum.
    pub fn trait_impls(&self) -> Result<Vec<TraitImpl>> {
        let impls = self
            .client_mut()?
            .get_trait_impls(&self.crate_name, &self.path)?;
        Ok(impls
            .into_iter()
            .map(|i| TraitImpl::from_raw(i, &self.crate_name, Arc::clone(&self.client)))
            .collect())
    }

    /// Check if this enum implements a specific trait.
    pub fn implements(&self, trait_path: &str) -> Result<bool> {
        let (implements, _) =
            self.client_mut()?
                .check_impl(&self.crate_name, &self.path, trait_path)?;
        Ok(implements)
    }

    /// Get inherent methods.
    pub fn methods(&self) -> Result<Vec<Method>> {
        let impls = self
            .client_mut()?
            .get_inherent_impls(&self.crate_name, &self.path)?;
        Ok(impls
            .into_iter()
            .flat_map(|impl_block| {
                impl_block
                    .methods
                    .into_iter()
                    .map(|m| Method::from_raw(m, &self.crate_name, Arc::clone(&self.client)))
            })
            .collect())
    }

    /// Get the source code of this enum definition.
    pub fn source(&self) -> Option<&str> {
        self.details().and_then(|d| d.source.as_deref())
    }

    pub fn details(&self) -> Option<&TypeDetails> {
        self.cached_details.as_deref()
    }

    pub fn visibility(&self) -> Option<&Visibility> {
        self.details().map(|d| &d.visibility)
    }

    pub fn docs(&self) -> Option<&str> {
        self.details().and_then(|d| d.docs.as_deref())
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

// ============================================================================
// Union Definition
// ============================================================================

/// A reflected union definition.
#[derive(Debug, Clone)]
pub struct UnionDef {
    pub name: String,
    pub path: String,
    pub generics: Vec<GenericParam>,
    crate_name: String,
    client: Arc<BronziteClient>,
}

impl UnionDef {
    /// Get the union's fields.
    pub fn fields(&self) -> Result<Vec<Field>> {
        let fields = self
            .client_mut()?
            .get_fields(&self.crate_name, &self.path)?;
        Ok(fields
            .into_iter()
            .map(|f| Field::from_raw(f, &self.crate_name, Arc::clone(&self.client)))
            .collect())
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

// ============================================================================
// Trait Definition
// ============================================================================

/// A reflected trait definition.
#[derive(Debug, Clone)]
pub struct TraitDef {
    pub name: String,
    pub path: String,
    pub generics: Vec<GenericParam>,
    pub is_auto: bool,
    pub is_unsafe: bool,
    pub supertraits: Vec<String>,
    pub source: Option<String>,
    pub docs: Option<String>,
    crate_name: String,
    client: Arc<BronziteClient>,
    cached_details: Option<Box<RawTraitDetails>>,
}

impl TraitDef {
    fn from_info(
        info: bronzite_types::TraitInfo,
        crate_name: &str,
        client: Arc<BronziteClient>,
    ) -> Result<Self> {
        // Fetch full details
        let client_mut = unsafe {
            let ptr = Arc::as_ptr(&client) as *mut BronziteClient;
            &mut *ptr
        };
        let details = client_mut.get_trait(crate_name, &info.path)?;
        Self::from_trait_details(details, crate_name, client)
    }

    fn from_trait_details(
        details: RawTraitDetails,
        crate_name: &str,
        client: Arc<BronziteClient>,
    ) -> Result<Self> {
        Ok(Self {
            name: details.name.clone(),
            path: details.path.clone(),
            generics: details.generics.clone(),
            is_auto: details.is_auto,
            is_unsafe: details.is_unsafe,
            supertraits: details.supertraits.clone(),
            source: details.source.clone(),
            docs: details.docs.clone(),
            crate_name: crate_name.to_string(),
            client,
            cached_details: Some(Box::new(details)),
        })
    }

    /// Get all methods defined in this trait.
    pub fn methods(&self) -> Vec<TraitMethod> {
        self.cached_details
            .as_ref()
            .map(|d| {
                d.methods
                    .iter()
                    .map(|m| TraitMethod {
                        name: m.name.clone(),
                        signature: m.signature.clone(),
                        parsed_signature: m.parsed_signature.clone(),
                        has_default: m.has_default,
                        default_body: m.default_body.clone(),
                        is_unsafe: m.is_unsafe,
                        docs: m.docs.clone(),
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get associated types.
    pub fn associated_types(&self) -> Vec<&AssocTypeInfo> {
        self.cached_details
            .as_ref()
            .map(|d| d.assoc_types.iter().collect())
            .unwrap_or_default()
    }

    /// Get associated constants.
    pub fn associated_consts(&self) -> Vec<&AssocConstInfo> {
        self.cached_details
            .as_ref()
            .map(|d| d.assoc_consts.iter().collect())
            .unwrap_or_default()
    }

    /// Get all types that implement this trait.
    pub fn implementors(&self) -> Result<Vec<Item>> {
        let types = self
            .client_mut()?
            .get_implementors(&self.crate_name, &self.path)?;
        types
            .into_iter()
            .map(|summary| Item::from_summary(summary, &self.crate_name, Arc::clone(&self.client)))
            .collect()
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

/// A method defined in a trait.
#[derive(Debug, Clone)]
pub struct TraitMethod {
    pub name: String,
    pub signature: String,
    pub parsed_signature: FunctionSignature,
    pub has_default: bool,
    pub default_body: Option<String>,
    pub is_unsafe: bool,
    pub docs: Option<String>,
}

// ============================================================================
// Type Alias Definition
// ============================================================================

/// A reflected type alias.
#[derive(Debug, Clone)]
pub struct TypeAliasDef {
    pub path: String,
    pub resolved_path: String,
    pub resolution_chain: Vec<String>,
    crate_name: String,
    client: Arc<BronziteClient>,
}

impl TypeAliasDef {
    /// Resolve this alias to its concrete type.
    pub fn resolve(&self) -> Result<Item> {
        // Get the final resolved type
        let details = self
            .client_mut()?
            .get_type(&self.crate_name, &self.resolved_path)?;

        let summary = TypeSummary {
            name: details.name.clone(),
            path: details.path.clone(),
            kind: details.kind.clone(),
            generics: details.generics.clone(),
        };

        Item::from_summary(summary, &self.crate_name, Arc::clone(&self.client))
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

// ============================================================================
// Field
// ============================================================================

/// A field of a struct, enum variant, or union.
///
/// Provides field metadata and the ability to navigate to the field's type definition.
///
/// # Example
///
/// ```ignore
/// let user = krate.get_struct("User")?;
/// for field in user.fields()? {
///     println!("Field: {}", field.name.as_deref().unwrap_or("<unnamed>"));
///     println!("  Type: {}", field.ty);
///     println!("  Size: {:?}", field.size);
///
///     // Navigate to the field's type definition
///     if let Some(field_type) = field.type_def()? {
///         println!("  Defined in: {}", field_type.path());
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Field {
    /// Field name (None for tuple struct fields)
    pub name: Option<String>,
    /// Field index in the struct
    pub index: usize,
    /// Type as a string
    pub ty: String,
    /// Resolved type (following aliases)
    pub resolved_ty: Option<String>,
    /// Field visibility
    pub visibility: Visibility,
    /// Doc comments
    pub docs: Option<String>,
    /// Offset in bytes (if layout is known)
    pub offset: Option<usize>,
    /// Size in bytes (if layout is known)
    pub size: Option<usize>,
    crate_name: String,
    client: Arc<BronziteClient>,
}

impl Field {
    fn from_raw(raw: RawFieldInfo, crate_name: &str, client: Arc<BronziteClient>) -> Self {
        Self {
            name: raw.name,
            index: raw.index,
            ty: raw.ty,
            resolved_ty: raw.resolved_ty,
            visibility: raw.visibility,
            docs: raw.docs,
            offset: raw.offset,
            size: raw.size,
            crate_name: crate_name.to_string(),
            client,
        }
    }

    /// Navigate to the type definition for this field's type.
    ///
    /// Returns an [`Item`] representing the field's type definition, if it
    /// can be resolved. Returns `None` for primitive types or external types
    /// not in the queried crate.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// for field in user.fields()? {
    ///     if let Some(field_type) = field.type_def()? {
    ///         match field_type {
    ///             Item::Struct(s) => println!("{} is a struct", field.name.unwrap()),
    ///             Item::Enum(e) => println!("{} is an enum", field.name.unwrap()),
    ///             _ => {}
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Returns
    ///
    /// - `Ok(Some(Item))` - The type definition was found
    /// - `Ok(None)` - The type is primitive or external
    /// - `Err(_)` - An error occurred querying the daemon
    pub fn type_def(&self) -> Result<Option<Item>> {
        let type_path = self.resolved_ty.as_ref().unwrap_or(&self.ty);

        // Try to get type details
        match self.client_mut()?.get_type(&self.crate_name, type_path) {
            Ok(details) => {
                let summary = TypeSummary {
                    name: details.name.clone(),
                    path: details.path.clone(),
                    kind: details.kind.clone(),
                    generics: details.generics.clone(),
                };
                Ok(Some(Item::from_summary(
                    summary,
                    &self.crate_name,
                    Arc::clone(&self.client),
                )?))
            }
            Err(_) => Ok(None), // Type might be external or primitive
        }
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

// ============================================================================
// Trait Implementation
// ============================================================================

/// A trait implementation block.
#[derive(Debug, Clone)]
pub struct TraitImpl {
    pub trait_path: String,
    pub generics: Vec<GenericParam>,
    pub is_unsafe: bool,
    pub source: Option<String>,
    raw: RawTraitImpl,
    crate_name: String,
    client: Arc<BronziteClient>,
}

impl TraitImpl {
    fn from_raw(raw: RawTraitImpl, crate_name: &str, client: Arc<BronziteClient>) -> Self {
        Self {
            trait_path: raw.trait_path.clone(),
            generics: raw.generics.clone(),
            is_unsafe: raw.is_unsafe,
            source: raw.source.clone(),
            raw,
            crate_name: crate_name.to_string(),
            client,
        }
    }

    /// Navigate to the trait definition being implemented.
    ///
    /// Returns the [`TraitDef`] for the trait that this impl block implements.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// for impl_block in user.trait_impls()? {
    ///     let trait_def = impl_block.trait_def()?;
    ///     println!("Implements trait: {}", trait_def.name);
    ///     println!("Trait has {} methods", trait_def.methods().len());
    /// }
    /// ```
    pub fn trait_def(&self) -> Result<TraitDef> {
        let details = self
            .client_mut()?
            .get_trait(&self.crate_name, &self.trait_path)?;
        TraitDef::from_trait_details(details, &self.crate_name, Arc::clone(&self.client))
    }

    /// Get methods defined in this impl block.
    pub fn methods(&self) -> Vec<Method> {
        self.raw
            .methods
            .iter()
            .map(|m| Method::from_raw(m.clone(), &self.crate_name, Arc::clone(&self.client)))
            .collect()
    }

    /// Get associated types in this impl.
    pub fn associated_types(&self) -> &[AssocTypeInfo] {
        &self.raw.assoc_types
    }

    /// Get associated constants in this impl.
    pub fn associated_consts(&self) -> &[AssocConstInfo] {
        &self.raw.assoc_consts
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}

// ============================================================================
// Method
// ============================================================================

/// A method (from an impl block).
///
/// Provides method metadata including signature, source code, and the ability
/// to navigate to parameter and return types.
///
/// # Example
///
/// ```ignore
/// let user = krate.get_struct("User")?;
/// for method in user.methods()? {
///     println!("Method: {}", method.name);
///     println!("  Signature: {}", method.signature);
///
///     // Get return type
///     if let Some(return_type) = method.return_type_def()? {
///         println!("  Returns: {}", return_type.name());
///     }
///
///     // Get method body source
///     if let Some(body) = &method.body_source {
///         println!("  Body: {}", body);
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Method {
    /// Method name
    pub name: String,
    /// Full signature as a string
    pub signature: String,
    /// Parsed signature components
    pub parsed_signature: FunctionSignature,
    /// Method body source code (if available)
    pub body_source: Option<String>,
    /// Whether this is an unsafe method
    pub is_unsafe: bool,
    /// Whether this is a const method
    pub is_const: bool,
    /// Whether this is an async method
    pub is_async: bool,
    /// Doc comments
    pub docs: Option<String>,
    crate_name: String,
    client: Arc<BronziteClient>,
}

impl Method {
    fn from_raw(raw: RawMethodDetails, crate_name: &str, client: Arc<BronziteClient>) -> Self {
        Self {
            name: raw.name,
            signature: raw.signature,
            parsed_signature: raw.parsed_signature,
            body_source: raw.body_source,
            is_unsafe: raw.is_unsafe,
            is_const: raw.is_const,
            is_async: raw.is_async,
            docs: raw.docs,
            crate_name: crate_name.to_string(),
            client,
        }
    }

    /// Navigate to the return type definition.
    ///
    /// Returns an [`Item`] representing the method's return type definition,
    /// if it can be resolved. Returns `None` if the method returns `()`, or
    /// if the type is primitive or external.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// for method in user.methods()? {
    ///     if let Some(return_type) = method.return_type_def()? {
    ///         println!("{} returns {}", method.name, return_type.name());
    ///     }
    /// }
    /// ```
    ///
    /// # Returns
    ///
    /// - `Ok(Some(Item))` - The return type definition was found
    /// - `Ok(None)` - No return type, or primitive/external type
    /// - `Err(_)` - An error occurred querying the daemon
    pub fn return_type_def(&self) -> Result<Option<Item>> {
        if let Some(return_ty) = &self.parsed_signature.return_ty {
            match self.client_mut()?.get_type(&self.crate_name, return_ty) {
                Ok(details) => {
                    let summary = TypeSummary {
                        name: details.name.clone(),
                        path: details.path.clone(),
                        kind: details.kind.clone(),
                        generics: details.generics.clone(),
                    };
                    Ok(Some(Item::from_summary(
                        summary,
                        &self.crate_name,
                        Arc::clone(&self.client),
                    )?))
                }
                Err(_) => Ok(None),
            }
        } else {
            Ok(None)
        }
    }

    /// Navigate to parameter type definitions.
    ///
    /// Returns a vector of optional [`Item`]s, one for each parameter.
    /// Each entry is `Some(Item)` if the type can be resolved, or `None`
    /// for primitive/external types.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let user = krate.get_struct("User")?;
    /// for method in user.methods()? {
    ///     println!("Method: {}", method.name);
    ///     for (i, param_type) in method.param_types()?.into_iter().enumerate() {
    ///         if let Some(ptype) = param_type {
    ///             println!("  Param {}: {}", i, ptype.name());
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Returns
    ///
    /// A vector where each element corresponds to a parameter:
    /// - `Some(Item)` - The parameter type was found
    /// - `None` - The type is primitive or external
    pub fn param_types(&self) -> Result<Vec<Option<Item>>> {
        self.parsed_signature
            .params
            .iter()
            .map(
                |param| match self.client_mut()?.get_type(&self.crate_name, &param.ty) {
                    Ok(details) => {
                        let summary = TypeSummary {
                            name: details.name.clone(),
                            path: details.path.clone(),
                            kind: details.kind.clone(),
                            generics: details.generics.clone(),
                        };
                        Ok(Some(Item::from_summary(
                            summary,
                            &self.crate_name,
                            Arc::clone(&self.client),
                        )?))
                    }
                    Err(_) => Ok(None),
                },
            )
            .collect()
    }

    fn client_mut(&self) -> Result<&mut BronziteClient> {
        unsafe {
            let ptr = Arc::as_ptr(&self.client) as *mut BronziteClient;
            Ok(&mut *ptr)
        }
    }
}