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}