Skip to main content

memscope_rs/capture/types/
generic.rs

1//! Generic type tracking types.
2//!
3//! This module contains types for tracking generic type instantiations,
4//! monomorphization, and type parameters.
5use serde::{Deserialize, Serialize};
6
7/// Memory access pattern.
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9pub enum MemoryAccessPattern {
10    /// Sequential access pattern.
11    Sequential,
12    /// Random access pattern.
13    Random,
14    /// Strided access pattern.
15    Strided {
16        /// Stride size.
17        stride: usize,
18    },
19    /// Clustered access pattern.
20    Clustered,
21    /// Mixed access pattern.
22    Mixed,
23}
24
25/// Generic type information.
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27pub struct GenericTypeInfo {
28    /// Generic base type name.
29    pub base_type: String,
30    /// Generic type parameters.
31    pub type_parameters: Vec<TypeParameter>,
32    /// Monomorphization information.
33    pub monomorphization_info: MonomorphizationInfo,
34    /// Generic constraint information.
35    pub constraints: Vec<GenericConstraint>,
36}
37
38/// Generic type parameter.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct TypeParameter {
41    /// Parameter name.
42    pub name: String,
43    /// Concrete type.
44    pub concrete_type: String,
45    /// Type size.
46    pub size: usize,
47    /// Type alignment.
48    pub alignment: usize,
49    /// Whether this is a lifetime parameter.
50    pub is_lifetime: bool,
51}
52
53/// Monomorphization information.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55pub struct MonomorphizationInfo {
56    /// Number of monomorphization instances.
57    pub instance_count: usize,
58    /// Memory usage per instance.
59    pub per_instance_memory: usize,
60    /// Total memory usage.
61    pub total_memory_usage: usize,
62    /// Code bloat assessment.
63    pub code_bloat_assessment: CodeBloatLevel,
64}
65
66/// Code bloat level.
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub enum CodeBloatLevel {
69    /// Low code bloat.
70    Low,
71    /// Moderate code bloat.
72    Moderate,
73    /// High code bloat.
74    High,
75    /// Excessive code bloat.
76    Excessive,
77}
78
79/// Generic constraint.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81pub struct GenericConstraint {
82    /// Constraint type.
83    pub constraint_type: ConstraintType,
84    /// Constraint description.
85    pub description: String,
86    /// Impact on memory layout.
87    pub memory_impact: MemoryImpact,
88}
89
90/// Constraint type.
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92pub enum ConstraintType {
93    /// Trait constraint.
94    Trait(String),
95    /// Lifetime constraint.
96    Lifetime(String),
97    /// Associated type constraint.
98    Associated(String),
99    /// Where clause constraint.
100    Where(String),
101}
102
103/// Memory impact.
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub enum MemoryImpact {
106    /// No memory impact.
107    None,
108    /// Size increase.
109    SizeIncrease(usize),
110    /// Alignment change.
111    AlignmentChange(usize),
112    /// Layout change.
113    LayoutChange(String),
114}
115
116/// Enhanced generic instantiation tracking.
117#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
118pub struct GenericInstantiationInfo {
119    /// Base generic type name.
120    pub base_type: String,
121    /// Concrete type parameters.
122    pub concrete_parameters: Vec<ConcreteTypeParameter>,
123    /// Instantiation location.
124    pub instantiation_location: SourceLocation,
125    /// Instantiation frequency.
126    pub instantiation_count: usize,
127    /// Memory usage per instantiation.
128    pub memory_per_instance: usize,
129    /// Total memory usage across all instances.
130    pub total_memory_usage: usize,
131    /// Compilation time impact.
132    pub compilation_impact: CompilationImpact,
133    /// Runtime performance characteristics.
134    pub performance_characteristics: PerformanceCharacteristics,
135}
136
137/// Concrete type parameter with detailed information.
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139pub struct ConcreteTypeParameter {
140    /// Parameter name.
141    pub name: String,
142    /// Concrete type.
143    pub concrete_type: String,
144    /// Type complexity score.
145    pub complexity_score: u32,
146    /// Memory footprint.
147    pub memory_footprint: usize,
148    /// Alignment requirements.
149    pub alignment: usize,
150    /// Whether type implements common traits.
151    pub trait_implementations: Vec<String>,
152    /// Type category.
153    pub type_category: TypeCategory,
154}
155
156/// Type category classification.
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
158pub enum TypeCategory {
159    /// Primitive type.
160    Primitive,
161    /// Struct type.
162    Struct,
163    /// Enum type.
164    Enum,
165    /// Union type.
166    Union,
167    /// Tuple type.
168    Tuple,
169    /// Array type.
170    Array,
171    /// Slice type.
172    Slice,
173    /// Reference type.
174    Reference,
175    /// Pointer type.
176    Pointer,
177    /// Function type.
178    Function,
179    /// Closure type.
180    TraitObject,
181    /// Generic type.
182    Generic,
183    /// Associated type.
184    Associated,
185}
186
187/// Source location information.
188#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
189pub struct SourceLocation {
190    /// File path.
191    pub file: String,
192    /// Line number.
193    pub line: u32,
194    /// Column number.
195    pub column: u32,
196}
197
198/// Compilation impact assessment.
199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
200pub struct CompilationImpact {
201    /// Estimated compilation time increase (milliseconds).
202    pub compilation_time_ms: u64,
203    /// Code size increase (bytes).
204    pub code_size_increase: usize,
205    /// LLVM IR complexity score.
206    pub ir_complexity_score: u32,
207    /// Optimization difficulty level.
208    pub optimization_difficulty: OptimizationDifficulty,
209}
210
211/// Optimization difficulty levels.
212#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
213pub enum OptimizationDifficulty {
214    /// Easy optimization difficulty.
215    Easy,
216    /// Moderate optimization difficulty.
217    Moderate,
218    /// Hard optimization difficulty.
219    Hard,
220    /// Very hard optimization difficulty.
221    VeryHard,
222}
223
224/// Performance characteristics of instantiated types.
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
226pub struct PerformanceCharacteristics {
227    /// Average allocation time (nanoseconds).
228    pub avg_allocation_time_ns: f64,
229    /// Average deallocation time (nanoseconds).
230    pub avg_deallocation_time_ns: f64,
231    /// Memory access pattern.
232    pub access_pattern: MemoryAccessPattern,
233    /// Cache performance impact.
234    pub cache_impact: CacheImpact,
235    /// Branch prediction impact.
236    pub branch_prediction_impact: BranchPredictionImpact,
237}
238
239impl Default for PerformanceCharacteristics {
240    fn default() -> Self {
241        Self {
242            avg_allocation_time_ns: 0.0,
243            avg_deallocation_time_ns: 0.0,
244            access_pattern: MemoryAccessPattern::Sequential,
245            cache_impact: CacheImpact::default(),
246            branch_prediction_impact: BranchPredictionImpact::default(),
247        }
248    }
249}
250
251/// Cache impact assessment.
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253pub struct CacheImpact {
254    /// L1 cache impact score.
255    pub l1_impact_score: f64,
256    /// L2 cache impact score.
257    pub l2_impact_score: f64,
258    /// L3 cache impact score.
259    pub l3_impact_score: f64,
260    /// Cache line utilization efficiency.
261    pub cache_line_efficiency: f64,
262}
263
264impl Default for CacheImpact {
265    fn default() -> Self {
266        Self {
267            l1_impact_score: 0.0,
268            l2_impact_score: 0.0,
269            l3_impact_score: 0.0,
270            cache_line_efficiency: 0.0,
271        }
272    }
273}
274
275/// Branch prediction impact.
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
277pub struct BranchPredictionImpact {
278    /// Branch misprediction rate.
279    pub misprediction_rate: f64,
280    /// Impact on pipeline stalls.
281    pub pipeline_stall_impact: f64,
282    /// Predictability score.
283    pub predictability_score: f64,
284}
285
286impl Default for BranchPredictionImpact {
287    fn default() -> Self {
288        Self {
289            misprediction_rate: 0.0,
290            pipeline_stall_impact: 0.0,
291            predictability_score: 0.0,
292        }
293    }
294}
295
296// Implement From trait for converting from core::types to capture::types
297impl From<crate::core::types::GenericTypeInfo> for GenericTypeInfo {
298    fn from(old: crate::core::types::GenericTypeInfo) -> Self {
299        Self {
300            base_type: old.base_type,
301            type_parameters: old
302                .type_parameters
303                .into_iter()
304                .map(|p| TypeParameter {
305                    name: p.name,
306                    concrete_type: p.concrete_type,
307                    size: p.size,
308                    alignment: p.alignment,
309                    is_lifetime: p.is_lifetime,
310                })
311                .collect(),
312            monomorphization_info: MonomorphizationInfo {
313                instance_count: old.monomorphization_info.instance_count,
314                per_instance_memory: old.monomorphization_info.per_instance_memory,
315                total_memory_usage: old.monomorphization_info.total_memory_usage,
316                code_bloat_assessment: match old.monomorphization_info.code_bloat_assessment {
317                    crate::core::types::CodeBloatLevel::Low => CodeBloatLevel::Low,
318                    crate::core::types::CodeBloatLevel::Moderate => CodeBloatLevel::Moderate,
319                    crate::core::types::CodeBloatLevel::High => CodeBloatLevel::High,
320                    crate::core::types::CodeBloatLevel::Excessive => CodeBloatLevel::Excessive,
321                },
322            },
323            constraints: old
324                .constraints
325                .into_iter()
326                .map(|c| GenericConstraint {
327                    constraint_type: match c.constraint_type {
328                        crate::core::types::ConstraintType::Trait(s) => ConstraintType::Trait(s),
329                        crate::core::types::ConstraintType::Lifetime(s) => {
330                            ConstraintType::Lifetime(s)
331                        }
332                        crate::core::types::ConstraintType::Associated(s) => {
333                            ConstraintType::Associated(s)
334                        }
335                        crate::core::types::ConstraintType::Where(s) => ConstraintType::Where(s),
336                    },
337                    description: c.description,
338                    memory_impact: match c.memory_impact {
339                        crate::core::types::MemoryImpact::None => MemoryImpact::None,
340                        crate::core::types::MemoryImpact::SizeIncrease(s) => {
341                            MemoryImpact::SizeIncrease(s)
342                        }
343                        crate::core::types::MemoryImpact::AlignmentChange(s) => {
344                            MemoryImpact::AlignmentChange(s)
345                        }
346                        crate::core::types::MemoryImpact::LayoutChange(s) => {
347                            MemoryImpact::LayoutChange(s)
348                        }
349                    },
350                })
351                .collect(),
352        }
353    }
354}
355
356impl From<crate::core::types::GenericInstantiationInfo> for GenericInstantiationInfo {
357    fn from(old: crate::core::types::GenericInstantiationInfo) -> Self {
358        Self {
359            base_type: old.base_type,
360            concrete_parameters: old
361                .concrete_parameters
362                .into_iter()
363                .map(|p| ConcreteTypeParameter {
364                    name: p.name,
365                    concrete_type: p.concrete_type,
366                    complexity_score: p.complexity_score,
367                    memory_footprint: p.memory_footprint,
368                    alignment: p.alignment,
369                    trait_implementations: p.trait_implementations,
370                    type_category: match p.type_category {
371                        crate::core::types::TypeCategory::Primitive => TypeCategory::Primitive,
372                        crate::core::types::TypeCategory::Struct => TypeCategory::Struct,
373                        crate::core::types::TypeCategory::Enum => TypeCategory::Enum,
374                        crate::core::types::TypeCategory::Union => TypeCategory::Union,
375                        crate::core::types::TypeCategory::Tuple => TypeCategory::Tuple,
376                        crate::core::types::TypeCategory::Slice => TypeCategory::Slice,
377                        crate::core::types::TypeCategory::Array => TypeCategory::Array,
378                        crate::core::types::TypeCategory::Pointer => TypeCategory::Pointer,
379                        crate::core::types::TypeCategory::Reference => TypeCategory::Reference,
380                        crate::core::types::TypeCategory::Function => TypeCategory::Function,
381                        crate::core::types::TypeCategory::TraitObject => TypeCategory::TraitObject,
382                        crate::core::types::TypeCategory::Generic => TypeCategory::Generic,
383                        crate::core::types::TypeCategory::Associated => TypeCategory::Associated,
384                    },
385                })
386                .collect(),
387            instantiation_location: SourceLocation {
388                file: old.instantiation_location.file,
389                line: old.instantiation_location.line,
390                column: old.instantiation_location.column,
391            },
392            instantiation_count: old.instantiation_count,
393            memory_per_instance: old.memory_per_instance,
394            total_memory_usage: old.total_memory_usage,
395            compilation_impact: CompilationImpact {
396                compilation_time_ms: old.compilation_impact.compilation_time_ms,
397                code_size_increase: old.compilation_impact.code_size_increase,
398                ir_complexity_score: old.compilation_impact.ir_complexity_score,
399                optimization_difficulty: match old.compilation_impact.optimization_difficulty {
400                    crate::core::types::OptimizationDifficulty::Easy => {
401                        OptimizationDifficulty::Easy
402                    }
403                    crate::core::types::OptimizationDifficulty::Moderate => {
404                        OptimizationDifficulty::Moderate
405                    }
406                    crate::core::types::OptimizationDifficulty::Hard => {
407                        OptimizationDifficulty::Hard
408                    }
409                    crate::core::types::OptimizationDifficulty::VeryHard => {
410                        OptimizationDifficulty::VeryHard
411                    }
412                },
413            },
414            performance_characteristics: PerformanceCharacteristics {
415                avg_allocation_time_ns: old.performance_characteristics.avg_allocation_time_ns,
416                avg_deallocation_time_ns: old.performance_characteristics.avg_deallocation_time_ns,
417                access_pattern: match old.performance_characteristics.access_pattern {
418                    crate::core::types::MemoryAccessPattern::Sequential => {
419                        MemoryAccessPattern::Sequential
420                    }
421                    crate::core::types::MemoryAccessPattern::Random => MemoryAccessPattern::Random,
422                    crate::core::types::MemoryAccessPattern::Strided { stride } => {
423                        MemoryAccessPattern::Strided { stride }
424                    }
425                    crate::core::types::MemoryAccessPattern::Clustered => {
426                        MemoryAccessPattern::Clustered
427                    }
428                    crate::core::types::MemoryAccessPattern::Mixed => MemoryAccessPattern::Mixed,
429                },
430                cache_impact: CacheImpact {
431                    l1_impact_score: old.performance_characteristics.cache_impact.l1_impact_score,
432                    l2_impact_score: old.performance_characteristics.cache_impact.l2_impact_score,
433                    l3_impact_score: old.performance_characteristics.cache_impact.l3_impact_score,
434                    cache_line_efficiency: old
435                        .performance_characteristics
436                        .cache_impact
437                        .cache_line_efficiency,
438                },
439                branch_prediction_impact: BranchPredictionImpact {
440                    misprediction_rate: old
441                        .performance_characteristics
442                        .branch_prediction_impact
443                        .misprediction_rate,
444                    pipeline_stall_impact: old
445                        .performance_characteristics
446                        .branch_prediction_impact
447                        .pipeline_stall_impact,
448                    predictability_score: old
449                        .performance_characteristics
450                        .branch_prediction_impact
451                        .predictability_score,
452                },
453            },
454        }
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn test_generic_type_info() {
464        let info = GenericTypeInfo {
465            base_type: "Vec".to_string(),
466            type_parameters: vec![],
467            monomorphization_info: MonomorphizationInfo {
468                instance_count: 1,
469                per_instance_memory: 24,
470                total_memory_usage: 24,
471                code_bloat_assessment: CodeBloatLevel::Low,
472            },
473            constraints: vec![],
474        };
475
476        assert_eq!(info.base_type, "Vec");
477    }
478
479    #[test]
480    fn test_performance_characteristics_default() {
481        let chars = PerformanceCharacteristics::default();
482        assert_eq!(chars.avg_allocation_time_ns, 0.0);
483    }
484
485    #[test]
486    fn test_cache_impact_default() {
487        let impact = CacheImpact::default();
488        assert_eq!(impact.l1_impact_score, 0.0);
489    }
490
491    #[test]
492    fn test_branch_prediction_impact_default() {
493        let impact = BranchPredictionImpact::default();
494        assert_eq!(impact.misprediction_rate, 0.0);
495        assert_eq!(impact.pipeline_stall_impact, 0.0);
496        assert_eq!(impact.predictability_score, 0.0);
497    }
498
499    #[test]
500    fn test_memory_access_pattern_variants() {
501        let patterns = vec![
502            MemoryAccessPattern::Sequential,
503            MemoryAccessPattern::Random,
504            MemoryAccessPattern::Strided { stride: 64 },
505            MemoryAccessPattern::Clustered,
506            MemoryAccessPattern::Mixed,
507        ];
508
509        for pattern in patterns {
510            let chars = PerformanceCharacteristics {
511                avg_allocation_time_ns: 0.0,
512                avg_deallocation_time_ns: 0.0,
513                access_pattern: pattern.clone(),
514                cache_impact: CacheImpact::default(),
515                branch_prediction_impact: BranchPredictionImpact::default(),
516            };
517            assert_eq!(chars.access_pattern, pattern);
518        }
519    }
520
521    #[test]
522    fn test_code_bloat_level_variants() {
523        let levels = vec![
524            CodeBloatLevel::Low,
525            CodeBloatLevel::Moderate,
526            CodeBloatLevel::High,
527            CodeBloatLevel::Excessive,
528        ];
529
530        for level in levels {
531            let info = MonomorphizationInfo {
532                instance_count: 0,
533                per_instance_memory: 0,
534                total_memory_usage: 0,
535                code_bloat_assessment: level.clone(),
536            };
537            assert_eq!(info.code_bloat_assessment, level);
538        }
539    }
540
541    #[test]
542    fn test_constraint_type_variants() {
543        let constraints = vec![
544            ConstraintType::Trait("Clone".to_string()),
545            ConstraintType::Lifetime("'static".to_string()),
546            ConstraintType::Associated("Item".to_string()),
547            ConstraintType::Where("T: Send".to_string()),
548        ];
549
550        for constraint_type in constraints {
551            let constraint = GenericConstraint {
552                constraint_type: constraint_type.clone(),
553                description: String::new(),
554                memory_impact: MemoryImpact::None,
555            };
556            assert_eq!(constraint.constraint_type, constraint_type);
557        }
558    }
559
560    #[test]
561    fn test_memory_impact_variants() {
562        let impacts = vec![
563            MemoryImpact::None,
564            MemoryImpact::SizeIncrease(64),
565            MemoryImpact::AlignmentChange(8),
566            MemoryImpact::LayoutChange("Reordered".to_string()),
567        ];
568
569        for impact in impacts {
570            let constraint = GenericConstraint {
571                constraint_type: ConstraintType::Trait("Clone".to_string()),
572                description: String::new(),
573                memory_impact: impact.clone(),
574            };
575            assert_eq!(constraint.memory_impact, impact);
576        }
577    }
578
579    #[test]
580    fn test_type_parameter_creation() {
581        let param = TypeParameter {
582            name: "T".to_string(),
583            concrete_type: "i32".to_string(),
584            size: 4,
585            alignment: 4,
586            is_lifetime: false,
587        };
588
589        assert_eq!(param.name, "T");
590        assert_eq!(param.concrete_type, "i32");
591        assert!(!param.is_lifetime);
592    }
593
594    #[test]
595    fn test_type_parameter_lifetime() {
596        let param = TypeParameter {
597            name: "'a".to_string(),
598            concrete_type: "".to_string(),
599            size: 0,
600            alignment: 0,
601            is_lifetime: true,
602        };
603
604        assert!(param.is_lifetime);
605    }
606
607    #[test]
608    fn test_monomorphization_info_creation() {
609        let info = MonomorphizationInfo {
610            instance_count: 10,
611            per_instance_memory: 24,
612            total_memory_usage: 240,
613            code_bloat_assessment: CodeBloatLevel::Moderate,
614        };
615
616        assert_eq!(info.instance_count, 10);
617        assert_eq!(info.total_memory_usage, 240);
618    }
619
620    #[test]
621    fn test_generic_constraint_creation() {
622        let constraint = GenericConstraint {
623            constraint_type: ConstraintType::Trait("Send".to_string()),
624            description: "Type must be thread-safe".to_string(),
625            memory_impact: MemoryImpact::None,
626        };
627
628        assert!(matches!(
629            constraint.constraint_type,
630            ConstraintType::Trait(_)
631        ));
632    }
633
634    #[test]
635    fn test_generic_type_info_with_parameters() {
636        let info = GenericTypeInfo {
637            base_type: "HashMap".to_string(),
638            type_parameters: vec![
639                TypeParameter {
640                    name: "K".to_string(),
641                    concrete_type: "String".to_string(),
642                    size: 24,
643                    alignment: 8,
644                    is_lifetime: false,
645                },
646                TypeParameter {
647                    name: "V".to_string(),
648                    concrete_type: "i32".to_string(),
649                    size: 4,
650                    alignment: 4,
651                    is_lifetime: false,
652                },
653            ],
654            monomorphization_info: MonomorphizationInfo {
655                instance_count: 1,
656                per_instance_memory: 48,
657                total_memory_usage: 48,
658                code_bloat_assessment: CodeBloatLevel::Low,
659            },
660            constraints: vec![GenericConstraint {
661                constraint_type: ConstraintType::Trait("Hash".to_string()),
662                description: "Key must be hashable".to_string(),
663                memory_impact: MemoryImpact::None,
664            }],
665        };
666
667        assert_eq!(info.type_parameters.len(), 2);
668        assert_eq!(info.constraints.len(), 1);
669    }
670
671    #[test]
672    fn test_generic_instantiation_info_creation() {
673        let info = GenericInstantiationInfo {
674            base_type: "Vec".to_string(),
675            concrete_parameters: vec![],
676            instantiation_location: SourceLocation {
677                file: "main.rs".to_string(),
678                line: 10,
679                column: 5,
680            },
681            instantiation_count: 5,
682            memory_per_instance: 24,
683            total_memory_usage: 120,
684            compilation_impact: CompilationImpact {
685                compilation_time_ms: 10,
686                code_size_increase: 256,
687                ir_complexity_score: 5,
688                optimization_difficulty: OptimizationDifficulty::Easy,
689            },
690            performance_characteristics: PerformanceCharacteristics::default(),
691        };
692
693        assert_eq!(info.base_type, "Vec");
694        assert_eq!(info.instantiation_count, 5);
695    }
696
697    #[test]
698    fn test_concrete_type_parameter_creation() {
699        let param = ConcreteTypeParameter {
700            name: "T".to_string(),
701            concrete_type: "String".to_string(),
702            complexity_score: 3,
703            memory_footprint: 24,
704            alignment: 8,
705            trait_implementations: vec!["Clone".to_string(), "Debug".to_string()],
706            type_category: TypeCategory::Struct,
707        };
708
709        assert_eq!(param.name, "T");
710        assert_eq!(param.trait_implementations.len(), 2);
711    }
712
713    #[test]
714    fn test_type_category_all_variants() {
715        let categories = vec![
716            TypeCategory::Primitive,
717            TypeCategory::Struct,
718            TypeCategory::Enum,
719            TypeCategory::Union,
720            TypeCategory::Tuple,
721            TypeCategory::Array,
722            TypeCategory::Slice,
723            TypeCategory::Reference,
724            TypeCategory::Pointer,
725            TypeCategory::Function,
726            TypeCategory::TraitObject,
727            TypeCategory::Generic,
728            TypeCategory::Associated,
729        ];
730
731        for category in categories {
732            let param = ConcreteTypeParameter {
733                name: String::new(),
734                concrete_type: String::new(),
735                complexity_score: 0,
736                memory_footprint: 0,
737                alignment: 0,
738                trait_implementations: vec![],
739                type_category: category.clone(),
740            };
741            assert_eq!(param.type_category, category);
742        }
743    }
744
745    #[test]
746    fn test_source_location_creation() {
747        let loc = SourceLocation {
748            file: "src/main.rs".to_string(),
749            line: 42,
750            column: 10,
751        };
752
753        assert_eq!(loc.file, "src/main.rs");
754        assert_eq!(loc.line, 42);
755        assert_eq!(loc.column, 10);
756    }
757
758    #[test]
759    fn test_compilation_impact_creation() {
760        let impact = CompilationImpact {
761            compilation_time_ms: 100,
762            code_size_increase: 1024,
763            ir_complexity_score: 50,
764            optimization_difficulty: OptimizationDifficulty::Hard,
765        };
766
767        assert_eq!(impact.compilation_time_ms, 100);
768        assert_eq!(impact.code_size_increase, 1024);
769    }
770
771    #[test]
772    fn test_optimization_difficulty_variants() {
773        let difficulties = vec![
774            OptimizationDifficulty::Easy,
775            OptimizationDifficulty::Moderate,
776            OptimizationDifficulty::Hard,
777            OptimizationDifficulty::VeryHard,
778        ];
779
780        for difficulty in difficulties {
781            let impact = CompilationImpact {
782                compilation_time_ms: 0,
783                code_size_increase: 0,
784                ir_complexity_score: 0,
785                optimization_difficulty: difficulty.clone(),
786            };
787            assert_eq!(impact.optimization_difficulty, difficulty);
788        }
789    }
790
791    #[test]
792    fn test_performance_characteristics_creation() {
793        let chars = PerformanceCharacteristics {
794            avg_allocation_time_ns: 50.0,
795            avg_deallocation_time_ns: 30.0,
796            access_pattern: MemoryAccessPattern::Random,
797            cache_impact: CacheImpact {
798                l1_impact_score: 0.8,
799                l2_impact_score: 0.6,
800                l3_impact_score: 0.4,
801                cache_line_efficiency: 0.75,
802            },
803            branch_prediction_impact: BranchPredictionImpact {
804                misprediction_rate: 0.1,
805                pipeline_stall_impact: 0.05,
806                predictability_score: 0.9,
807            },
808        };
809
810        assert!((chars.avg_allocation_time_ns - 50.0).abs() < f64::EPSILON);
811        assert!((chars.cache_impact.l1_impact_score - 0.8).abs() < f64::EPSILON);
812    }
813
814    #[test]
815    fn test_cache_impact_creation() {
816        let impact = CacheImpact {
817            l1_impact_score: 0.9,
818            l2_impact_score: 0.7,
819            l3_impact_score: 0.5,
820            cache_line_efficiency: 0.85,
821        };
822
823        assert!((impact.l1_impact_score - 0.9).abs() < f64::EPSILON);
824        assert!((impact.cache_line_efficiency - 0.85).abs() < f64::EPSILON);
825    }
826
827    #[test]
828    fn test_branch_prediction_impact_creation() {
829        let impact = BranchPredictionImpact {
830            misprediction_rate: 0.15,
831            pipeline_stall_impact: 0.08,
832            predictability_score: 0.92,
833        };
834
835        assert!((impact.misprediction_rate - 0.15).abs() < f64::EPSILON);
836        assert!((impact.predictability_score - 0.92).abs() < f64::EPSILON);
837    }
838
839    #[test]
840    fn test_generic_type_info_serialization() {
841        let info = GenericTypeInfo {
842            base_type: "Option".to_string(),
843            type_parameters: vec![TypeParameter {
844                name: "T".to_string(),
845                concrete_type: "i32".to_string(),
846                size: 4,
847                alignment: 4,
848                is_lifetime: false,
849            }],
850            monomorphization_info: MonomorphizationInfo {
851                instance_count: 1,
852                per_instance_memory: 4,
853                total_memory_usage: 4,
854                code_bloat_assessment: CodeBloatLevel::Low,
855            },
856            constraints: vec![],
857        };
858
859        let json = serde_json::to_string(&info).unwrap();
860        let deserialized: GenericTypeInfo = serde_json::from_str(&json).unwrap();
861        assert_eq!(deserialized.base_type, info.base_type);
862    }
863
864    #[test]
865    fn test_memory_access_pattern_serialization() {
866        let patterns = vec![
867            MemoryAccessPattern::Sequential,
868            MemoryAccessPattern::Random,
869            MemoryAccessPattern::Strided { stride: 128 },
870            MemoryAccessPattern::Clustered,
871            MemoryAccessPattern::Mixed,
872        ];
873
874        for pattern in patterns {
875            let json = serde_json::to_string(&pattern).unwrap();
876            let deserialized: MemoryAccessPattern = serde_json::from_str(&json).unwrap();
877            assert_eq!(deserialized, pattern);
878        }
879    }
880
881    #[test]
882    fn test_code_bloat_level_serialization() {
883        let levels = vec![
884            CodeBloatLevel::Low,
885            CodeBloatLevel::Moderate,
886            CodeBloatLevel::High,
887            CodeBloatLevel::Excessive,
888        ];
889
890        for level in levels {
891            let json = serde_json::to_string(&level).unwrap();
892            let deserialized: CodeBloatLevel = serde_json::from_str(&json).unwrap();
893            assert_eq!(deserialized, level);
894        }
895    }
896
897    #[test]
898    fn test_constraint_type_serialization() {
899        let constraint_types = vec![
900            ConstraintType::Trait("Clone".to_string()),
901            ConstraintType::Lifetime("'static".to_string()),
902            ConstraintType::Associated("Item".to_string()),
903            ConstraintType::Where("T: Send".to_string()),
904        ];
905
906        for ct in constraint_types {
907            let json = serde_json::to_string(&ct).unwrap();
908            let deserialized: ConstraintType = serde_json::from_str(&json).unwrap();
909            assert_eq!(deserialized, ct);
910        }
911    }
912
913    #[test]
914    fn test_memory_impact_serialization() {
915        let impacts = vec![
916            MemoryImpact::None,
917            MemoryImpact::SizeIncrease(64),
918            MemoryImpact::AlignmentChange(8),
919            MemoryImpact::LayoutChange("Reordered".to_string()),
920        ];
921
922        for impact in impacts {
923            let json = serde_json::to_string(&impact).unwrap();
924            let deserialized: MemoryImpact = serde_json::from_str(&json).unwrap();
925            assert_eq!(deserialized, impact);
926        }
927    }
928
929    #[test]
930    fn test_type_category_serialization() {
931        let categories = vec![
932            TypeCategory::Primitive,
933            TypeCategory::Struct,
934            TypeCategory::Enum,
935            TypeCategory::Union,
936            TypeCategory::Tuple,
937            TypeCategory::Array,
938            TypeCategory::Slice,
939            TypeCategory::Reference,
940            TypeCategory::Pointer,
941            TypeCategory::Function,
942            TypeCategory::TraitObject,
943            TypeCategory::Generic,
944            TypeCategory::Associated,
945        ];
946
947        for category in categories {
948            let json = serde_json::to_string(&category).unwrap();
949            let deserialized: TypeCategory = serde_json::from_str(&json).unwrap();
950            assert_eq!(deserialized, category);
951        }
952    }
953
954    #[test]
955    fn test_optimization_difficulty_serialization() {
956        let difficulties = vec![
957            OptimizationDifficulty::Easy,
958            OptimizationDifficulty::Moderate,
959            OptimizationDifficulty::Hard,
960            OptimizationDifficulty::VeryHard,
961        ];
962
963        for difficulty in difficulties {
964            let json = serde_json::to_string(&difficulty).unwrap();
965            let deserialized: OptimizationDifficulty = serde_json::from_str(&json).unwrap();
966            assert_eq!(deserialized, difficulty);
967        }
968    }
969
970    #[test]
971    fn test_generic_instantiation_info_serialization() {
972        let info = GenericInstantiationInfo {
973            base_type: "Vec".to_string(),
974            concrete_parameters: vec![ConcreteTypeParameter {
975                name: "T".to_string(),
976                concrete_type: "u8".to_string(),
977                complexity_score: 1,
978                memory_footprint: 1,
979                alignment: 1,
980                trait_implementations: vec![],
981                type_category: TypeCategory::Primitive,
982            }],
983            instantiation_location: SourceLocation {
984                file: "lib.rs".to_string(),
985                line: 1,
986                column: 1,
987            },
988            instantiation_count: 1,
989            memory_per_instance: 24,
990            total_memory_usage: 24,
991            compilation_impact: CompilationImpact {
992                compilation_time_ms: 5,
993                code_size_increase: 64,
994                ir_complexity_score: 1,
995                optimization_difficulty: OptimizationDifficulty::Easy,
996            },
997            performance_characteristics: PerformanceCharacteristics::default(),
998        };
999
1000        let json = serde_json::to_string(&info).unwrap();
1001        let deserialized: GenericInstantiationInfo = serde_json::from_str(&json).unwrap();
1002        assert_eq!(deserialized.base_type, info.base_type);
1003    }
1004
1005    #[test]
1006    fn test_generic_type_info_clone() {
1007        let info = GenericTypeInfo {
1008            base_type: "Box".to_string(),
1009            type_parameters: vec![],
1010            monomorphization_info: MonomorphizationInfo {
1011                instance_count: 1,
1012                per_instance_memory: 8,
1013                total_memory_usage: 8,
1014                code_bloat_assessment: CodeBloatLevel::Low,
1015            },
1016            constraints: vec![],
1017        };
1018
1019        let cloned = info.clone();
1020        assert_eq!(cloned.base_type, info.base_type);
1021    }
1022
1023    #[test]
1024    fn test_generic_type_info_debug() {
1025        let info = GenericTypeInfo {
1026            base_type: "Rc".to_string(),
1027            type_parameters: vec![],
1028            monomorphization_info: MonomorphizationInfo {
1029                instance_count: 0,
1030                per_instance_memory: 0,
1031                total_memory_usage: 0,
1032                code_bloat_assessment: CodeBloatLevel::Low,
1033            },
1034            constraints: vec![],
1035        };
1036
1037        let debug_str = format!("{:?}", info);
1038        assert!(debug_str.contains("GenericTypeInfo"));
1039        assert!(debug_str.contains("base_type"));
1040    }
1041
1042    #[test]
1043    fn test_boundary_values_monomorphization() {
1044        let info = MonomorphizationInfo {
1045            instance_count: usize::MAX,
1046            per_instance_memory: usize::MAX,
1047            total_memory_usage: usize::MAX,
1048            code_bloat_assessment: CodeBloatLevel::Excessive,
1049        };
1050
1051        assert_eq!(info.instance_count, usize::MAX);
1052        assert_eq!(info.total_memory_usage, usize::MAX);
1053    }
1054
1055    #[test]
1056    fn test_boundary_values_compilation_impact() {
1057        let impact = CompilationImpact {
1058            compilation_time_ms: u64::MAX,
1059            code_size_increase: usize::MAX,
1060            ir_complexity_score: u32::MAX,
1061            optimization_difficulty: OptimizationDifficulty::VeryHard,
1062        };
1063
1064        assert_eq!(impact.compilation_time_ms, u64::MAX);
1065        assert_eq!(impact.ir_complexity_score, u32::MAX);
1066    }
1067
1068    #[test]
1069    fn test_boundary_values_performance_chars() {
1070        let chars = PerformanceCharacteristics {
1071            avg_allocation_time_ns: f64::MAX,
1072            avg_deallocation_time_ns: f64::MAX,
1073            access_pattern: MemoryAccessPattern::Mixed,
1074            cache_impact: CacheImpact {
1075                l1_impact_score: f64::MAX,
1076                l2_impact_score: f64::MAX,
1077                l3_impact_score: f64::MAX,
1078                cache_line_efficiency: 1.0,
1079            },
1080            branch_prediction_impact: BranchPredictionImpact {
1081                misprediction_rate: 1.0,
1082                pipeline_stall_impact: 1.0,
1083                predictability_score: 1.0,
1084            },
1085        };
1086
1087        assert!(chars.avg_allocation_time_ns.is_finite());
1088    }
1089}