memscope_rs/
advanced_types.rs

1//! Advanced type analysis framework for complex Rust types
2//!
3//! This module provides a unified framework for analyzing complex Rust types
4//! like Cell, RefCell, Mutex, RwLock, channels, etc. Instead of implementing
5//! each type individually, we identify common patterns and provide a generic
6//! analysis framework.
7
8use crate::core::types::AllocationInfo;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12/// Categories of advanced Rust types based on their memory and concurrency characteristics
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub enum AdvancedTypeCategory {
15    /// Interior mutability types (Cell, RefCell, UnsafeCell)
16    InteriorMutability,
17    /// Synchronization primitives (Mutex, RwLock, Condvar)
18    Synchronization,
19    /// Channel types (Sender, Receiver, mpsc, etc.)
20    Channel,
21    /// Atomic types (AtomicBool, AtomicUsize, etc.)
22    Atomic,
23    /// Thread-local storage (ThreadLocal, LocalKey)
24    ThreadLocal,
25    /// Memory management (ManuallyDrop, MaybeUninit, Pin)
26    MemoryManagement,
27    /// Async primitives (Future, Waker, Context)
28    Async,
29}
30
31/// Behavioral patterns that advanced types exhibit
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct TypeBehaviorPattern {
34    /// Does this type provide interior mutability?
35    pub has_interior_mutability: bool,
36    /// Can this type be shared across threads?
37    pub is_thread_safe: bool,
38    /// Does this type involve blocking operations?
39    pub can_block: bool,
40    /// Does this type manage its own memory layout?
41    pub manages_memory_layout: bool,
42    /// Can this type cause deadlocks?
43    pub deadlock_potential: bool,
44    /// Does this type have runtime borrow checking?
45    pub has_runtime_borrow_check: bool,
46    /// Is this type zero-cost or has runtime overhead?
47    pub has_runtime_overhead: bool,
48}
49
50/// Advanced type analysis information
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52pub struct AdvancedTypeInfo {
53    /// Category of this advanced type
54    pub category: AdvancedTypeCategory,
55    /// Behavioral pattern
56    pub behavior: TypeBehaviorPattern,
57    /// Current state information
58    pub state_info: TypeStateInfo,
59    /// Potential issues or warnings
60    pub potential_issues: Vec<TypeIssue>,
61    /// Performance characteristics
62    pub performance_info: PerformanceInfo,
63}
64
65/// Current state of the advanced type
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TypeStateInfo {
68    /// Is currently borrowed (for RefCell-like types)?
69    pub is_borrowed: Option<bool>,
70    /// Current borrow count (if applicable)
71    pub borrow_count: Option<usize>,
72    /// Is currently locked (for Mutex-like types)?
73    pub is_locked: Option<bool>,
74    /// Thread that currently owns the lock (if applicable)
75    pub lock_owner_thread: Option<String>,
76    /// Queue length for waiting threads/operations
77    pub wait_queue_length: Option<usize>,
78    /// Channel capacity and current usage
79    pub channel_info: Option<ChannelStateInfo>,
80}
81
82/// Channel-specific state information
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct ChannelStateInfo {
85    /// Channel capacity (None for unbounded)
86    pub capacity: Option<usize>,
87    /// Current number of items in channel
88    pub current_size: usize,
89    /// Number of active senders
90    pub sender_count: usize,
91    /// Number of active receivers
92    pub receiver_count: usize,
93    /// Is the channel closed?
94    pub is_closed: bool,
95}
96
97/// Potential issues with advanced types
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub struct TypeIssue {
100    /// Severity of the issue
101    pub severity: IssueSeverity,
102    /// Description of the issue
103    pub description: String,
104    /// Suggested fix or mitigation
105    pub suggestion: Option<String>,
106    /// Related code location if available
107    pub location: Option<String>,
108}
109
110/// Severity levels for type issues
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub enum IssueSeverity {
113    /// Informational level
114    Info,
115    /// Warning level
116    Warning,
117    /// Error level
118    Error,
119    /// Critical level
120    Critical,
121}
122
123/// Performance characteristics
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125pub struct PerformanceInfo {
126    /// Estimated overhead compared to direct access
127    pub overhead_factor: f64,
128    /// Memory overhead in bytes
129    pub memory_overhead: usize,
130    /// Whether operations are lock-free
131    pub is_lock_free: bool,
132    /// Typical operation latency category
133    pub latency_category: LatencyCategory,
134}
135
136/// Latency categories for operations
137#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
138pub enum LatencyCategory {
139    /// < 1ns (atomic operations)
140    Immediate,
141    /// 1-10ns (simple operations)
142    Fast,
143    /// 10-100ns (syscalls, locks)
144    Moderate,
145    /// 100ns-1μs (complex operations)
146    Slow,
147    /// > 1μs (blocking operations)
148    VerySlow,
149}
150
151/// Trait for advanced type analysis
152pub trait AdvancedTypeAnalyzer {
153    /// Analyze the advanced type and return analysis information
154    fn analyze_advanced_type(&self) -> AdvancedTypeInfo;
155
156    /// Get current state snapshot
157    fn get_current_state(&self) -> TypeStateInfo;
158
159    /// Check for potential issues
160    fn check_issues(&self) -> Vec<TypeIssue>;
161
162    /// Get performance characteristics
163    fn get_performance_info(&self) -> PerformanceInfo;
164}
165
166/// Generic analyzer that can handle most advanced types through pattern matching
167pub struct GenericAdvancedTypeAnalyzer;
168
169impl GenericAdvancedTypeAnalyzer {
170    /// Analyze a type by its name and characteristics
171    pub fn analyze_by_type_name(type_name: &str, allocation: &AllocationInfo) -> AdvancedTypeInfo {
172        let category = Self::categorize_type(type_name);
173        let behavior = Self::analyze_behavior_pattern(type_name, &category);
174        let state_info = Self::extract_state_info(type_name, allocation);
175        let potential_issues = Self::check_potential_issues(type_name, &category, &behavior);
176        let performance_info = Self::analyze_performance(type_name, &category);
177
178        AdvancedTypeInfo {
179            category,
180            behavior,
181            state_info,
182            potential_issues,
183            performance_info,
184        }
185    }
186
187    /// Categorize type based on its name
188    fn categorize_type(type_name: &str) -> AdvancedTypeCategory {
189        if type_name.contains("Cell") || type_name.contains("UnsafeCell") {
190            AdvancedTypeCategory::InteriorMutability
191        } else if type_name.contains("Mutex")
192            || type_name.contains("RwLock")
193            || type_name.contains("Condvar")
194            || type_name.contains("Barrier")
195        {
196            AdvancedTypeCategory::Synchronization
197        } else if type_name.contains("Sender")
198            || type_name.contains("Receiver")
199            || type_name.contains("mpsc")
200            || type_name.contains("channel")
201        {
202            AdvancedTypeCategory::Channel
203        } else if type_name.contains("Atomic") {
204            AdvancedTypeCategory::Atomic
205        } else if type_name.contains("ThreadLocal") || type_name.contains("LocalKey") {
206            AdvancedTypeCategory::ThreadLocal
207        } else if type_name.contains("ManuallyDrop")
208            || type_name.contains("MaybeUninit")
209            || type_name.contains("Pin")
210        {
211            AdvancedTypeCategory::MemoryManagement
212        } else if type_name.contains("Future")
213            || type_name.contains("Waker")
214            || type_name.contains("Context")
215            || type_name.contains("async")
216        {
217            AdvancedTypeCategory::Async
218        } else {
219            // Default fallback - try to infer from other characteristics
220            AdvancedTypeCategory::MemoryManagement
221        }
222    }
223
224    /// Analyze behavioral patterns
225    fn analyze_behavior_pattern(
226        type_name: &str,
227        category: &AdvancedTypeCategory,
228    ) -> TypeBehaviorPattern {
229        match category {
230            AdvancedTypeCategory::InteriorMutability => TypeBehaviorPattern {
231                has_interior_mutability: true,
232                is_thread_safe: !type_name.contains("Cell"), // RefCell is not thread-safe, Cell might be
233                can_block: false,
234                manages_memory_layout: false,
235                deadlock_potential: false,
236                has_runtime_borrow_check: type_name.contains("RefCell"),
237                has_runtime_overhead: type_name.contains("RefCell"),
238            },
239            AdvancedTypeCategory::Synchronization => TypeBehaviorPattern {
240                has_interior_mutability: true,
241                is_thread_safe: true,
242                can_block: true,
243                manages_memory_layout: false,
244                deadlock_potential: true,
245                has_runtime_borrow_check: false,
246                has_runtime_overhead: true,
247            },
248            AdvancedTypeCategory::Channel => TypeBehaviorPattern {
249                has_interior_mutability: true,
250                is_thread_safe: true,
251                can_block: true,
252                manages_memory_layout: true,
253                deadlock_potential: false,
254                has_runtime_borrow_check: false,
255                has_runtime_overhead: true,
256            },
257            AdvancedTypeCategory::Atomic => TypeBehaviorPattern {
258                has_interior_mutability: true,
259                is_thread_safe: true,
260                can_block: false,
261                manages_memory_layout: false,
262                deadlock_potential: false,
263                has_runtime_borrow_check: false,
264                has_runtime_overhead: false,
265            },
266            AdvancedTypeCategory::ThreadLocal => TypeBehaviorPattern {
267                has_interior_mutability: true,
268                is_thread_safe: false, // Thread-local by definition
269                can_block: false,
270                manages_memory_layout: true,
271                deadlock_potential: false,
272                has_runtime_borrow_check: false,
273                has_runtime_overhead: true,
274            },
275            AdvancedTypeCategory::MemoryManagement => TypeBehaviorPattern {
276                has_interior_mutability: false,
277                is_thread_safe: true, // Usually just wrappers
278                can_block: false,
279                manages_memory_layout: true,
280                deadlock_potential: false,
281                has_runtime_borrow_check: false,
282                has_runtime_overhead: false,
283            },
284            AdvancedTypeCategory::Async => TypeBehaviorPattern {
285                has_interior_mutability: true,
286                is_thread_safe: true,
287                can_block: true, // Can suspend execution
288                manages_memory_layout: true,
289                deadlock_potential: false,
290                has_runtime_borrow_check: false,
291                has_runtime_overhead: true,
292            },
293        }
294    }
295
296    /// Extract current state information (limited without runtime introspection)
297    fn extract_state_info(_type_name: &str, _allocation: &AllocationInfo) -> TypeStateInfo {
298        // Note: Without runtime introspection, we can only provide limited state info
299        // In a real implementation, this would require unsafe code or cooperation from the types
300        TypeStateInfo {
301            is_borrowed: None,
302            borrow_count: None,
303            is_locked: None,
304            lock_owner_thread: None,
305            wait_queue_length: None,
306            channel_info: None,
307        }
308    }
309
310    /// Check for potential issues based on type characteristics
311    fn check_potential_issues(
312        type_name: &str,
313        category: &AdvancedTypeCategory,
314        behavior: &TypeBehaviorPattern,
315    ) -> Vec<TypeIssue> {
316        let mut issues = Vec::new();
317
318        // Check for common issues based on category
319        match category {
320            AdvancedTypeCategory::InteriorMutability => {
321                if type_name.contains("RefCell") {
322                    issues.push(TypeIssue {
323                        severity: IssueSeverity::Warning,
324                        description: "RefCell has runtime borrow checking overhead".to_string(),
325                        suggestion: Some("Consider using Cell for Copy types or redesign to avoid interior mutability".to_string()),
326                        location: None,
327                    });
328                }
329            }
330            AdvancedTypeCategory::Synchronization => {
331                if behavior.deadlock_potential {
332                    issues.push(TypeIssue {
333                        severity: IssueSeverity::Warning,
334                        description: "Synchronization primitive has deadlock potential".to_string(),
335                        suggestion: Some(
336                            "Ensure consistent lock ordering and consider using try_lock()"
337                                .to_string(),
338                        ),
339                        location: None,
340                    });
341                }
342            }
343            AdvancedTypeCategory::Channel => {
344                issues.push(TypeIssue {
345                    severity: IssueSeverity::Info,
346                    description: "Channel operations can block indefinitely".to_string(),
347                    suggestion: Some("Consider using try_send/try_recv or timeouts".to_string()),
348                    location: None,
349                });
350            }
351            _ => {}
352        }
353
354        issues
355    }
356
357    /// Analyze performance characteristics
358    fn analyze_performance(type_name: &str, category: &AdvancedTypeCategory) -> PerformanceInfo {
359        match category {
360            AdvancedTypeCategory::InteriorMutability => {
361                if type_name.contains("Cell") {
362                    PerformanceInfo {
363                        overhead_factor: 1.0, // Zero-cost abstraction
364                        memory_overhead: 0,
365                        is_lock_free: true,
366                        latency_category: LatencyCategory::Immediate,
367                    }
368                } else {
369                    PerformanceInfo {
370                        overhead_factor: 2.0,                          // RefCell has runtime checks
371                        memory_overhead: std::mem::size_of::<usize>(), // Borrow counter
372                        is_lock_free: true,
373                        latency_category: LatencyCategory::Fast,
374                    }
375                }
376            }
377            AdvancedTypeCategory::Synchronization => PerformanceInfo {
378                overhead_factor: 10.0, // Significant overhead for locking
379                memory_overhead: std::mem::size_of::<usize>() * 2, // Lock state + wait queue
380                is_lock_free: false,
381                latency_category: LatencyCategory::Moderate,
382            },
383            AdvancedTypeCategory::Channel => PerformanceInfo {
384                overhead_factor: 5.0, // Moderate overhead
385                memory_overhead: 64,  // Estimated buffer overhead
386                is_lock_free: false,
387                latency_category: LatencyCategory::Moderate,
388            },
389            AdvancedTypeCategory::Atomic => PerformanceInfo {
390                overhead_factor: 1.5, // Slight overhead for atomic operations
391                memory_overhead: 0,
392                is_lock_free: true,
393                latency_category: LatencyCategory::Immediate,
394            },
395            AdvancedTypeCategory::ThreadLocal => PerformanceInfo {
396                overhead_factor: 3.0,                          // TLS lookup overhead
397                memory_overhead: std::mem::size_of::<usize>(), // TLS key
398                is_lock_free: true,
399                latency_category: LatencyCategory::Fast,
400            },
401            AdvancedTypeCategory::MemoryManagement => PerformanceInfo {
402                overhead_factor: 1.0, // Usually zero-cost
403                memory_overhead: 0,
404                is_lock_free: true,
405                latency_category: LatencyCategory::Immediate,
406            },
407            AdvancedTypeCategory::Async => PerformanceInfo {
408                overhead_factor: 4.0, // State machine overhead
409                memory_overhead: 32,  // Estimated state machine size
410                is_lock_free: true,
411                latency_category: LatencyCategory::Fast,
412            },
413        }
414    }
415}
416
417/// Analysis results for all advanced types in an allocation set
418#[derive(Debug, Clone, Serialize, Deserialize)]
419pub struct AdvancedTypeAnalysisReport {
420    /// Analysis by type category
421    pub by_category: HashMap<String, Vec<AdvancedTypeInfo>>,
422    /// All detected issues
423    pub all_issues: Vec<TypeIssue>,
424    /// Performance summary
425    pub performance_summary: PerformanceSummary,
426    /// Statistics
427    pub statistics: AdvancedTypeStatistics,
428}
429
430/// Performance summary across all advanced types
431#[derive(Debug, Clone, Serialize, Deserialize)]
432pub struct PerformanceSummary {
433    /// Total estimated overhead factor
434    pub total_overhead_factor: f64,
435    /// Total memory overhead in bytes
436    pub total_memory_overhead: usize,
437    /// Percentage of types that are lock-free
438    pub lock_free_percentage: f64,
439    /// Most common latency category
440    pub dominant_latency_category: LatencyCategory,
441}
442
443/// Statistics for advanced type usage
444#[derive(Debug, Clone, Serialize, Deserialize)]
445pub struct AdvancedTypeStatistics {
446    /// Count by category
447    pub by_category: HashMap<String, usize>,
448    /// Count by issue severity
449    pub by_issue_severity: HashMap<String, usize>,
450    /// Count by latency category
451    pub by_latency_category: HashMap<String, usize>,
452    /// Total advanced types analyzed
453    pub total_advanced_types: usize,
454}
455
456/// Analyze all advanced types in a set of allocations
457pub fn analyze_advanced_types(allocations: &[AllocationInfo]) -> AdvancedTypeAnalysisReport {
458    let mut by_category: HashMap<String, Vec<AdvancedTypeInfo>> = HashMap::new();
459    let mut all_issues = Vec::new();
460    let mut total_overhead_factor = 0.0;
461    let mut total_memory_overhead = 0;
462    let mut lock_free_count = 0;
463    let mut total_count = 0;
464    let mut latency_counts: HashMap<LatencyCategory, usize> = HashMap::new();
465
466    for allocation in allocations {
467        if let Some(type_name) = &allocation.type_name {
468            // Check if this is an advanced type we should analyze
469            if is_advanced_type(type_name) {
470                let analysis =
471                    GenericAdvancedTypeAnalyzer::analyze_by_type_name(type_name, allocation);
472
473                // Clone data before moving analysis
474                let category_key = format!("{:?}", analysis.category);
475                let issues = analysis.potential_issues.clone();
476                let overhead_factor = analysis.performance_info.overhead_factor;
477                let memory_overhead = analysis.performance_info.memory_overhead;
478                let is_lock_free = analysis.performance_info.is_lock_free;
479                let latency_category = analysis.performance_info.latency_category.clone();
480
481                // Move analysis to category
482                by_category.entry(category_key).or_default().push(analysis);
483
484                // Collect issues
485                all_issues.extend(issues);
486
487                // Aggregate performance data
488                total_overhead_factor += overhead_factor;
489                total_memory_overhead += memory_overhead;
490                if is_lock_free {
491                    lock_free_count += 1;
492                }
493                *latency_counts.entry(latency_category).or_insert(0) += 1;
494                total_count += 1;
495            }
496        }
497    }
498
499    // Calculate performance summary
500    let performance_summary = if total_count > 0 {
501        PerformanceSummary {
502            total_overhead_factor: total_overhead_factor / total_count as f64,
503            total_memory_overhead,
504            lock_free_percentage: (lock_free_count as f64 / total_count as f64) * 100.0,
505            dominant_latency_category: latency_counts
506                .iter()
507                .max_by_key(|(_, count)| *count)
508                .map(|(category, _)| category.clone())
509                .unwrap_or(LatencyCategory::Fast),
510        }
511    } else {
512        PerformanceSummary {
513            total_overhead_factor: 1.0,
514            total_memory_overhead: 0,
515            lock_free_percentage: 100.0,
516            dominant_latency_category: LatencyCategory::Immediate,
517        }
518    };
519
520    // Generate statistics
521    let statistics =
522        generate_advanced_type_statistics(&by_category, &all_issues, &latency_counts, total_count);
523
524    AdvancedTypeAnalysisReport {
525        by_category,
526        all_issues,
527        performance_summary,
528        statistics,
529    }
530}
531
532/// Check if a type name represents an advanced type we should analyze
533pub fn is_advanced_type(type_name: &str) -> bool {
534    type_name.contains("Cell")
535        || type_name.contains("Mutex")
536        || type_name.contains("RwLock")
537        || type_name.contains("Atomic")
538        || type_name.contains("Sender")
539        || type_name.contains("Receiver")
540        || type_name.contains("ThreadLocal")
541        || type_name.contains("ManuallyDrop")
542        || type_name.contains("MaybeUninit")
543        || type_name.contains("Pin")
544        || type_name.contains("Future")
545        || type_name.contains("Waker")
546        || type_name.contains("Condvar")
547        || type_name.contains("Barrier")
548        || type_name.contains("Arc<")
549        || type_name.contains("Rc<")
550        || type_name.contains("Weak<")
551        || type_name.contains("Box<dyn")
552        || type_name.contains("Cow<")
553        || type_name.contains("HashMap<")
554        || type_name.contains("BTreeMap<")
555        || type_name.contains("PhantomData<")
556}
557
558/// Analyze a type and return its category
559pub fn get_type_category(type_name: &str) -> Option<AdvancedTypeCategory> {
560    if type_name.contains("Cell<")
561        || type_name.contains("RefCell<")
562        || type_name.contains("UnsafeCell<")
563    {
564        Some(AdvancedTypeCategory::InteriorMutability)
565    } else if type_name.contains("Mutex<")
566        || type_name.contains("RwLock<")
567        || type_name.contains("Condvar")
568    {
569        Some(AdvancedTypeCategory::Synchronization)
570    } else if type_name.contains("mpsc::")
571        || type_name.contains("Sender<")
572        || type_name.contains("Receiver<")
573    {
574        Some(AdvancedTypeCategory::Channel)
575    } else if type_name.contains("Atomic") {
576        Some(AdvancedTypeCategory::Atomic)
577    } else if type_name.contains("ThreadLocal<") || type_name.contains("LocalKey<") {
578        Some(AdvancedTypeCategory::ThreadLocal)
579    } else if type_name.contains("ManuallyDrop<")
580        || type_name.contains("MaybeUninit<")
581        || type_name.contains("Pin<")
582    {
583        Some(AdvancedTypeCategory::MemoryManagement)
584    } else if type_name.contains("Future")
585        || type_name.contains("Stream")
586        || type_name.contains("Waker")
587        || type_name.contains("Context")
588    {
589        Some(AdvancedTypeCategory::Async)
590    } else {
591        None
592    }
593}
594
595/// Create behavior pattern for a type
596pub fn create_behavior_pattern(type_name: &str) -> TypeBehaviorPattern {
597    let category = get_type_category(type_name);
598
599    match category {
600        Some(AdvancedTypeCategory::InteriorMutability) => TypeBehaviorPattern {
601            has_interior_mutability: true,
602            is_thread_safe: !type_name.contains("Cell<"), // Cell is not thread-safe, RefCell is not either
603            can_block: false,
604            manages_memory_layout: false,
605            deadlock_potential: false,
606            has_runtime_borrow_check: type_name.contains("RefCell<"),
607            has_runtime_overhead: type_name.contains("RefCell<"),
608        },
609        Some(AdvancedTypeCategory::Synchronization) => TypeBehaviorPattern {
610            has_interior_mutability: true,
611            is_thread_safe: true,
612            can_block: true,
613            manages_memory_layout: false,
614            deadlock_potential: true,
615            has_runtime_borrow_check: false,
616            has_runtime_overhead: true,
617        },
618        Some(AdvancedTypeCategory::Channel) => TypeBehaviorPattern {
619            has_interior_mutability: false,
620            is_thread_safe: true,
621            can_block: true,
622            manages_memory_layout: true,
623            deadlock_potential: false,
624            has_runtime_borrow_check: false,
625            has_runtime_overhead: true,
626        },
627        Some(AdvancedTypeCategory::Atomic) => TypeBehaviorPattern {
628            has_interior_mutability: true,
629            is_thread_safe: true,
630            can_block: false,
631            manages_memory_layout: false,
632            deadlock_potential: false,
633            has_runtime_borrow_check: false,
634            has_runtime_overhead: false,
635        },
636        Some(AdvancedTypeCategory::ThreadLocal) => TypeBehaviorPattern {
637            has_interior_mutability: true,
638            is_thread_safe: false,
639            can_block: false,
640            manages_memory_layout: true,
641            deadlock_potential: false,
642            has_runtime_borrow_check: false,
643            has_runtime_overhead: true,
644        },
645        Some(AdvancedTypeCategory::MemoryManagement) => TypeBehaviorPattern {
646            has_interior_mutability: type_name.contains("Pin<"),
647            is_thread_safe: false,
648            can_block: false,
649            manages_memory_layout: true,
650            deadlock_potential: false,
651            has_runtime_borrow_check: false,
652            has_runtime_overhead: false,
653        },
654        Some(AdvancedTypeCategory::Async) => TypeBehaviorPattern {
655            has_interior_mutability: false,
656            is_thread_safe: false,
657            can_block: false,
658            manages_memory_layout: true,
659            deadlock_potential: false,
660            has_runtime_borrow_check: false,
661            has_runtime_overhead: true,
662        },
663        None => TypeBehaviorPattern {
664            has_interior_mutability: false,
665            is_thread_safe: false,
666            can_block: false,
667            manages_memory_layout: false,
668            deadlock_potential: false,
669            has_runtime_borrow_check: false,
670            has_runtime_overhead: false,
671        },
672    }
673}
674
675/// Analyze a type and create AdvancedTypeInfo
676pub fn analyze_type(allocation: &AllocationInfo) -> Option<AdvancedTypeInfo> {
677    let type_name = allocation.type_name.as_ref()?;
678
679    if !is_advanced_type(type_name) {
680        return None;
681    }
682
683    let category = get_type_category(type_name)?;
684    let behavior = create_behavior_pattern(type_name);
685
686    let mut issues = Vec::new();
687    let _recommendations: Vec<String> = Vec::new();
688
689    // Analyze potential issues based on type behavior
690    if behavior.deadlock_potential {
691        issues.push(TypeIssue {
692            severity: IssueSeverity::Warning,
693            description: "Type has deadlock potential - ensure proper lock ordering".to_string(),
694            location: Some(format!("ptr: 0x{:x}", allocation.ptr)),
695            suggestion: Some(
696                "Consider using timeout-based locking or lock hierarchies".to_string(),
697            ),
698        });
699    }
700
701    if behavior.has_runtime_overhead && allocation.size > 1024 {
702        issues.push(TypeIssue {
703            severity: IssueSeverity::Warning,
704            description: "Large allocation with runtime overhead".to_string(),
705            location: Some(format!(
706                "ptr: 0x{:x}, size: {}",
707                allocation.ptr, allocation.size
708            )),
709            suggestion: Some(
710                "Consider using more efficient alternatives for large data".to_string(),
711            ),
712        });
713    }
714
715    Some(AdvancedTypeInfo {
716        category,
717        behavior: behavior.clone(),
718        state_info: TypeStateInfo {
719            is_borrowed: None,
720            borrow_count: Some(allocation.borrow_count),
721            is_locked: None,
722            lock_owner_thread: None,
723            wait_queue_length: None,
724            channel_info: None,
725        },
726        potential_issues: issues,
727        performance_info: PerformanceInfo {
728            overhead_factor: if behavior.has_runtime_overhead {
729                2.0
730            } else {
731                1.0
732            },
733            memory_overhead: calculate_overhead(type_name),
734            is_lock_free: !behavior.can_block,
735            latency_category: if behavior.can_block {
736                LatencyCategory::Moderate
737            } else {
738                LatencyCategory::Fast
739            },
740        },
741    })
742}
743
744/// Calculate overhead for a type
745fn calculate_overhead(type_name: &str) -> usize {
746    if type_name.contains("RefCell<") {
747        std::mem::size_of::<isize>() // BorrowFlag is private, use isize
748    } else if type_name.contains("Mutex<") {
749        64 // Approximate mutex overhead
750    } else if type_name.contains("RwLock<") {
751        96 // Approximate RwLock overhead
752    } else if type_name.contains("Arc<") || type_name.contains("Rc<") {
753        std::mem::size_of::<usize>() * 2 // Strong + weak counts
754    } else {
755        0
756    }
757}
758
759/// Generate statistics for the analysis
760fn generate_advanced_type_statistics(
761    by_category: &HashMap<String, Vec<AdvancedTypeInfo>>,
762    all_issues: &[TypeIssue],
763    latency_counts: &HashMap<LatencyCategory, usize>,
764    total_count: usize,
765) -> AdvancedTypeStatistics {
766    let mut by_category_stats = HashMap::new();
767    for (category, types) in by_category {
768        by_category_stats.insert(category.clone(), types.len());
769    }
770
771    let mut by_issue_severity = HashMap::new();
772    for issue in all_issues {
773        let severity_key = format!("{:?}", issue.severity);
774        *by_issue_severity.entry(severity_key).or_insert(0) += 1;
775    }
776
777    let mut by_latency_category = HashMap::new();
778    for (category, count) in latency_counts {
779        by_latency_category.insert(format!("{category:?}"), *count);
780    }
781
782    AdvancedTypeStatistics {
783        by_category: by_category_stats,
784        by_issue_severity,
785        by_latency_category,
786        total_advanced_types: total_count,
787    }
788}
789
790// ===== Enhanced Interior Mutability Detection =====
791
792/// Enhanced interior mutability detection for Cell/RefCell types
793pub fn detect_interior_mutability_patterns(
794    allocations: &[AllocationInfo],
795) -> InteriorMutabilityReport {
796    let mut cell_instances = Vec::new();
797    let mut refcell_instances = Vec::new();
798    let mut unsafe_cell_instances = Vec::new();
799    let mut runtime_borrow_violations = Vec::new();
800
801    for allocation in allocations {
802        if let Some(type_name) = &allocation.type_name {
803            if type_name.contains("UnsafeCell<") {
804                unsafe_cell_instances.push(UnsafeCellInstance {
805                    ptr: allocation.ptr,
806                    type_name: type_name.clone(),
807                    size: allocation.size,
808                    requires_unsafe_access: true,
809                });
810            } else if type_name.contains("RefCell<") {
811                let instance = RefCellInstance {
812                    ptr: allocation.ptr,
813                    type_name: type_name.clone(),
814                    size: allocation.size,
815                    current_borrow_count: allocation.borrow_count,
816                    has_active_mut_borrow: allocation.borrow_count > 0,
817                    runtime_check_overhead: true,
818                };
819
820                // Check for potential runtime borrow violations
821                if allocation.borrow_count > 1 {
822                    runtime_borrow_violations.push(BorrowViolation {
823                        ptr: allocation.ptr,
824                        violation_type: BorrowViolationType::MultipleBorrows,
825                        borrow_count: allocation.borrow_count,
826                        timestamp: allocation.timestamp_alloc,
827                    });
828                }
829
830                refcell_instances.push(instance);
831            } else if type_name.contains("Cell<")
832                && !type_name.contains("RefCell<")
833                && !type_name.contains("UnsafeCell<")
834            {
835                cell_instances.push(CellInstance {
836                    ptr: allocation.ptr,
837                    type_name: type_name.clone(),
838                    size: allocation.size,
839                    thread_safe: true, // Cell is always thread-safe
840                    zero_cost: true,   // Cell has no runtime overhead
841                });
842            }
843        }
844    }
845
846    let total_types = cell_instances.len() + refcell_instances.len() + unsafe_cell_instances.len();
847
848    InteriorMutabilityReport {
849        cell_instances,
850        refcell_instances,
851        unsafe_cell_instances,
852        runtime_borrow_violations,
853        total_interior_mutability_types: total_types,
854        analysis_timestamp: current_timestamp(),
855    }
856}
857
858/// Enhanced concurrency primitive monitoring for Mutex/RwLock types
859pub fn monitor_concurrency_primitives(
860    allocations: &[AllocationInfo],
861) -> ConcurrencyPrimitiveReport {
862    let mut mutex_instances = Vec::new();
863    let mut rwlock_instances = Vec::new();
864    let mut condvar_instances = Vec::new();
865    let lock_contentions = Vec::new();
866
867    for allocation in allocations {
868        if let Some(type_name) = &allocation.type_name {
869            if type_name.contains("Mutex<") {
870                mutex_instances.push(MutexInstance {
871                    ptr: allocation.ptr,
872                    type_name: type_name.clone(),
873                    size: allocation.size,
874                    is_locked: false, // Would need runtime tracking
875                    lock_owner_thread: None,
876                    waiting_threads: 0,
877                    total_lock_acquisitions: 0,
878                    total_wait_time_ns: 0,
879                });
880            } else if type_name.contains("RwLock<") {
881                rwlock_instances.push(RwLockInstance {
882                    ptr: allocation.ptr,
883                    type_name: type_name.clone(),
884                    size: allocation.size,
885                    read_count: 0,
886                    has_write_lock: false,
887                    waiting_readers: 0,
888                    waiting_writers: 0,
889                    total_read_acquisitions: 0,
890                    total_write_acquisitions: 0,
891                });
892            } else if type_name.contains("Condvar") {
893                condvar_instances.push(CondvarInstance {
894                    ptr: allocation.ptr,
895                    type_name: type_name.clone(),
896                    size: allocation.size,
897                    waiting_threads: 0,
898                    total_notifications: 0,
899                });
900            }
901        }
902    }
903
904    let deadlock_score =
905        calculate_deadlock_potential_by_count(mutex_instances.len(), rwlock_instances.len());
906
907    ConcurrencyPrimitiveReport {
908        mutex_instances,
909        rwlock_instances,
910        condvar_instances,
911        lock_contentions,
912        deadlock_potential_score: deadlock_score,
913        analysis_timestamp: current_timestamp(),
914    }
915}
916
917// ===== Supporting Types and Functions =====
918
919/// Get current timestamp
920fn current_timestamp() -> u64 {
921    std::time::SystemTime::now()
922        .duration_since(std::time::UNIX_EPOCH)
923        .unwrap_or_default()
924        .as_nanos() as u64
925}
926
927/// Calculate deadlock potential based on lock count
928fn calculate_deadlock_potential_by_count(mutex_count: usize, rwlock_count: usize) -> f64 {
929    let total_locks = mutex_count + rwlock_count;
930    if total_locks <= 1 {
931        return 0.0;
932    }
933
934    // Simple heuristic: more locks = higher deadlock potential
935    // In reality, this would analyze lock ordering and dependency graphs
936    (total_locks as f64).log2() / 10.0
937}
938
939// ===== Type Definitions =====
940
941/// Interior mutability report
942#[derive(Debug, Clone, Serialize, Deserialize)]
943pub struct InteriorMutabilityReport {
944    /// Cell instances
945    pub cell_instances: Vec<CellInstance>,
946    /// RefCell instances
947    pub refcell_instances: Vec<RefCellInstance>,
948    /// UnsafeCell instances
949    pub unsafe_cell_instances: Vec<UnsafeCellInstance>,
950    /// Runtime borrow violations
951    pub runtime_borrow_violations: Vec<BorrowViolation>,
952    /// Total number of interior mutability types
953    pub total_interior_mutability_types: usize,
954    /// Analysis timestamp
955    pub analysis_timestamp: u64,
956}
957
958/// Cell instance
959#[derive(Debug, Clone, Serialize, Deserialize)]
960pub struct CellInstance {
961    /// Pointer to the instance
962    pub ptr: usize,
963    /// Type name of the instance
964    pub type_name: String,
965    /// Size of the instance
966    pub size: usize,
967    /// Whether the instance is thread-safe
968    pub thread_safe: bool,
969    /// Whether the instance is zero-cost
970    pub zero_cost: bool,
971}
972
973/// RefCell instance
974#[derive(Debug, Clone, Serialize, Deserialize)]
975pub struct RefCellInstance {
976    /// Pointer to the instance
977    pub ptr: usize,
978    /// Type name of the instance
979    pub type_name: String,
980    /// Size of the instance
981    pub size: usize,
982    /// Current borrow count
983    pub current_borrow_count: usize,
984    /// Whether there is an active mutable borrow
985    pub has_active_mut_borrow: bool,
986    /// Whether runtime borrow checks are enabled
987    pub runtime_check_overhead: bool,
988}
989
990/// UnsafeCell instance
991#[derive(Debug, Clone, Serialize, Deserialize)]
992pub struct UnsafeCellInstance {
993    /// Pointer to the instance
994    pub ptr: usize,
995    /// Type name of the instance
996    pub type_name: String,
997    /// Size of the instance
998    pub size: usize,
999    /// Whether unsafe access is required
1000    pub requires_unsafe_access: bool,
1001}
1002
1003/// Borrow violation
1004#[derive(Debug, Clone, Serialize, Deserialize)]
1005pub struct BorrowViolation {
1006    /// Pointer to the instance
1007    pub ptr: usize,
1008    /// Type of violation
1009    pub violation_type: BorrowViolationType,
1010    /// Number of borrows
1011    pub borrow_count: usize,
1012    /// Timestamp of the violation
1013    pub timestamp: u64,
1014}
1015
1016/// Borrow violation type
1017#[derive(Debug, Clone, Serialize, Deserialize)]
1018pub enum BorrowViolationType {
1019    /// Multiple borrows    
1020    MultipleBorrows,
1021    /// Mutable borrow conflict
1022    MutableBorrowConflict,
1023    /// Borrow after move
1024    BorrowAfterMove,
1025}
1026
1027/// Concurrency primitive report
1028#[derive(Debug, Clone, Serialize, Deserialize)]
1029pub struct ConcurrencyPrimitiveReport {
1030    /// Mutex instances
1031    pub mutex_instances: Vec<MutexInstance>,
1032    /// RwLock instances
1033    pub rwlock_instances: Vec<RwLockInstance>,
1034    /// Condvar instances
1035    pub condvar_instances: Vec<CondvarInstance>,
1036    /// Lock contentions
1037    pub lock_contentions: Vec<LockContention>,
1038    /// Deadlock potential score
1039    pub deadlock_potential_score: f64,
1040    /// Analysis timestamp
1041    pub analysis_timestamp: u64,
1042}
1043
1044/// Mutex instance
1045#[derive(Debug, Clone, Serialize, Deserialize)]
1046pub struct MutexInstance {
1047    /// Pointer to the instance
1048    pub ptr: usize,
1049    /// Type name of the instance
1050    pub type_name: String,
1051    /// Size of the instance
1052    pub size: usize,
1053    /// Whether the mutex is locked
1054    pub is_locked: bool,
1055    /// Lock owner thread
1056    pub lock_owner_thread: Option<String>,
1057    /// Number of waiting threads
1058    pub waiting_threads: usize,
1059    /// Total number of lock acquisitions
1060    pub total_lock_acquisitions: u64,
1061    /// Total wait time in nanoseconds
1062    pub total_wait_time_ns: u64,
1063}
1064
1065/// RwLock instance
1066#[derive(Debug, Clone, Serialize, Deserialize)]
1067pub struct RwLockInstance {
1068    /// Pointer to the instance
1069    pub ptr: usize,
1070    /// Type name of the instance
1071    pub type_name: String,
1072    /// Size of the instance
1073    pub size: usize,
1074    /// Number of read locks
1075    pub read_count: usize,
1076    /// Whether the rwlock has a write lock
1077    pub has_write_lock: bool,
1078    /// Number of waiting readers
1079    pub waiting_readers: usize,
1080    /// Number of waiting writers
1081    pub waiting_writers: usize,
1082    /// Total number of read acquisitions
1083    pub total_read_acquisitions: u64,
1084    /// Total number of write acquisitions
1085    pub total_write_acquisitions: u64,
1086}
1087
1088/// Condvar instance
1089#[derive(Debug, Clone, Serialize, Deserialize)]
1090pub struct CondvarInstance {
1091    /// Pointer to the instance
1092    pub ptr: usize,
1093    /// Type name of the instance
1094    pub type_name: String,
1095    /// Size of the instance
1096    pub size: usize,
1097    /// Number of waiting threads
1098    pub waiting_threads: usize,
1099    /// Total number of notifications
1100    pub total_notifications: u64,
1101}
1102
1103/// Lock contention
1104#[derive(Debug, Clone, Serialize, Deserialize)]
1105pub struct LockContention {
1106    /// Pointer to the lock
1107    pub lock_ptr: usize,
1108    /// Type of contention
1109    pub contention_type: ContentionType,
1110    /// Waiting time in nanoseconds
1111    pub waiting_time_ns: u64,
1112    /// Thread ID
1113    pub thread_id: String,
1114    /// Timestamp
1115    pub timestamp: u64,
1116}
1117
1118/// Contention type
1119#[derive(Debug, Clone, Serialize, Deserialize)]
1120pub enum ContentionType {
1121    /// Mutex contention
1122    MutexContention,
1123    /// RwLock read contention
1124    RwLockReadContention,
1125    /// RwLock write contention
1126    RwLockWriteContention,
1127}
1128
1129#[cfg(test)]
1130mod tests {
1131    use super::*;
1132    use crate::core::types::AllocationInfo;
1133
1134    fn create_test_allocation(type_name: &str, size: usize) -> AllocationInfo {
1135        AllocationInfo {
1136            ptr: 0x12345678,
1137            size,
1138            var_name: Some("test_var".to_string()),
1139            type_name: Some(type_name.to_string()),
1140            timestamp_alloc: 1000,
1141            borrow_count: 0,
1142            scope_name: None,
1143            timestamp_dealloc: None,
1144            thread_id: "test_thread".to_string(),
1145            stack_trace: None,
1146            is_leaked: false,
1147            lifetime_ms: None,
1148            borrow_info: None,
1149            clone_info: None,
1150            ownership_history_available: false,
1151            smart_pointer_info: None,
1152            memory_layout: None,
1153            generic_info: None,
1154            dynamic_type_info: None,
1155            runtime_state: None,
1156            stack_allocation: None,
1157            temporary_object: None,
1158            fragmentation_analysis: None,
1159            generic_instantiation: None,
1160            type_relationships: None,
1161            type_usage: None,
1162            function_call_tracking: None,
1163            lifecycle_tracking: None,
1164            access_tracking: None,
1165            drop_chain_analysis: None,
1166        }
1167    }
1168
1169    #[test]
1170    fn test_is_advanced_type() {
1171        assert!(is_advanced_type("std::cell::RefCell<i32>"));
1172        assert!(is_advanced_type("std::sync::Mutex<String>"));
1173        assert!(is_advanced_type("std::sync::RwLock<Vec<u8>>"));
1174        assert!(is_advanced_type("std::sync::atomic::AtomicBool"));
1175        assert!(is_advanced_type("std::sync::mpsc::Sender<i32>"));
1176        assert!(is_advanced_type("std::sync::Arc<i32>"));
1177        assert!(is_advanced_type("std::collections::HashMap<String, i32>"));
1178
1179        assert!(!is_advanced_type("i32"));
1180        assert!(!is_advanced_type("String"));
1181        assert!(!is_advanced_type("Vec<u8>"));
1182    }
1183
1184    #[test]
1185    fn test_get_type_category() {
1186        assert_eq!(
1187            get_type_category("std::cell::Cell<i32>"),
1188            Some(AdvancedTypeCategory::InteriorMutability)
1189        );
1190        assert_eq!(
1191            get_type_category("std::cell::RefCell<String>"),
1192            Some(AdvancedTypeCategory::InteriorMutability)
1193        );
1194        assert_eq!(
1195            get_type_category("std::sync::Mutex<i32>"),
1196            Some(AdvancedTypeCategory::Synchronization)
1197        );
1198        assert_eq!(
1199            get_type_category("std::sync::RwLock<String>"),
1200            Some(AdvancedTypeCategory::Synchronization)
1201        );
1202        assert_eq!(
1203            get_type_category("std::sync::mpsc::Sender<i32>"),
1204            Some(AdvancedTypeCategory::Channel)
1205        );
1206        assert_eq!(
1207            get_type_category("std::sync::atomic::AtomicBool"),
1208            Some(AdvancedTypeCategory::Atomic)
1209        );
1210        assert_eq!(
1211            get_type_category("std::mem::ManuallyDrop<String>"),
1212            Some(AdvancedTypeCategory::MemoryManagement)
1213        );
1214        assert_eq!(
1215            get_type_category("std::future::Future"),
1216            Some(AdvancedTypeCategory::Async)
1217        );
1218        assert_eq!(get_type_category("i32"), None);
1219    }
1220
1221    #[test]
1222    fn test_create_behavior_pattern() {
1223        let refcell_pattern = create_behavior_pattern("std::cell::RefCell<i32>");
1224        assert!(refcell_pattern.has_interior_mutability);
1225        assert!(!refcell_pattern.is_thread_safe);
1226        assert!(refcell_pattern.has_runtime_borrow_check);
1227        assert!(refcell_pattern.has_runtime_overhead);
1228
1229        let mutex_pattern = create_behavior_pattern("std::sync::Mutex<i32>");
1230        assert!(mutex_pattern.has_interior_mutability);
1231        assert!(mutex_pattern.is_thread_safe);
1232        assert!(mutex_pattern.can_block);
1233        assert!(mutex_pattern.deadlock_potential);
1234
1235        let atomic_pattern = create_behavior_pattern("std::sync::atomic::AtomicBool");
1236        assert!(atomic_pattern.has_interior_mutability);
1237        assert!(atomic_pattern.is_thread_safe);
1238        assert!(!atomic_pattern.can_block);
1239        assert!(!atomic_pattern.has_runtime_overhead);
1240    }
1241
1242    #[test]
1243    fn test_generic_advanced_type_analyzer() {
1244        let allocation = create_test_allocation("std::cell::RefCell<i32>", 1024);
1245        let analysis = GenericAdvancedTypeAnalyzer::analyze_by_type_name(
1246            "std::cell::RefCell<i32>",
1247            &allocation,
1248        );
1249
1250        assert_eq!(analysis.category, AdvancedTypeCategory::InteriorMutability);
1251        assert!(analysis.behavior.has_interior_mutability);
1252        assert!(analysis.behavior.has_runtime_borrow_check);
1253        assert!(!analysis.potential_issues.is_empty());
1254        assert!(analysis.performance_info.overhead_factor >= 1.0); // RefCell has 2.0, Cell has 1.0
1255    }
1256
1257    #[test]
1258    fn test_analyze_type() {
1259        let allocation = create_test_allocation("std::sync::Mutex<String>", 2048);
1260        let analysis = analyze_type(&allocation).unwrap();
1261
1262        assert_eq!(analysis.category, AdvancedTypeCategory::Synchronization);
1263        assert!(analysis.behavior.deadlock_potential);
1264        assert!(!analysis.potential_issues.is_empty());
1265
1266        // Test with non-advanced type
1267        let simple_allocation = create_test_allocation("i32", 4);
1268        assert!(analyze_type(&simple_allocation).is_none());
1269    }
1270
1271    #[test]
1272    fn test_analyze_advanced_types() {
1273        let allocations = vec![
1274            create_test_allocation("std::cell::RefCell<i32>", 1024),
1275            create_test_allocation("std::sync::Mutex<String>", 2048),
1276            create_test_allocation("i32", 4), // Should be ignored
1277        ];
1278
1279        let report = analyze_advanced_types(&allocations);
1280
1281        assert_eq!(report.statistics.total_advanced_types, 2);
1282        assert!(!report.all_issues.is_empty());
1283        assert!(!report.by_category.is_empty());
1284        assert!(report.performance_summary.total_overhead_factor > 1.0);
1285    }
1286
1287    #[test]
1288    fn test_detect_interior_mutability_patterns() {
1289        let mut allocation = create_test_allocation("std::cell::RefCell<i32>", 1024);
1290        allocation.borrow_count = 2; // Multiple borrows
1291
1292        let allocations = vec![
1293            create_test_allocation("std::cell::Cell<i32>", 512),
1294            allocation,
1295            create_test_allocation("std::cell::UnsafeCell<String>", 256),
1296        ];
1297
1298        let report = detect_interior_mutability_patterns(&allocations);
1299
1300        assert_eq!(report.cell_instances.len(), 1);
1301        assert_eq!(report.refcell_instances.len(), 1);
1302        assert_eq!(report.unsafe_cell_instances.len(), 1);
1303        assert_eq!(report.runtime_borrow_violations.len(), 1);
1304        assert_eq!(report.total_interior_mutability_types, 3);
1305    }
1306
1307    #[test]
1308    fn test_monitor_concurrency_primitives() {
1309        let allocations = vec![
1310            create_test_allocation("std::sync::Mutex<i32>", 1024),
1311            create_test_allocation("std::sync::RwLock<String>", 2048),
1312            create_test_allocation("std::sync::Condvar", 512),
1313        ];
1314
1315        let report = monitor_concurrency_primitives(&allocations);
1316
1317        assert_eq!(report.mutex_instances.len(), 1);
1318        assert_eq!(report.rwlock_instances.len(), 1);
1319        assert_eq!(report.condvar_instances.len(), 1);
1320        assert!(report.deadlock_potential_score > 0.0);
1321    }
1322
1323    #[test]
1324    fn test_advanced_type_category_variants() {
1325        // Test all enum variants can be created
1326        let categories = vec![
1327            AdvancedTypeCategory::InteriorMutability,
1328            AdvancedTypeCategory::Synchronization,
1329            AdvancedTypeCategory::Channel,
1330            AdvancedTypeCategory::Atomic,
1331            AdvancedTypeCategory::ThreadLocal,
1332            AdvancedTypeCategory::MemoryManagement,
1333            AdvancedTypeCategory::Async,
1334        ];
1335
1336        for category in categories {
1337            assert!(!format!("{category:?}").is_empty());
1338        }
1339    }
1340
1341    #[test]
1342    fn test_issue_severity_variants() {
1343        let severities = vec![
1344            IssueSeverity::Info,
1345            IssueSeverity::Warning,
1346            IssueSeverity::Error,
1347            IssueSeverity::Critical,
1348        ];
1349
1350        for severity in severities {
1351            assert!(!format!("{severity:?}").is_empty());
1352        }
1353    }
1354
1355    #[test]
1356    fn test_latency_category_variants() {
1357        let categories = vec![
1358            LatencyCategory::Immediate,
1359            LatencyCategory::Fast,
1360            LatencyCategory::Moderate,
1361            LatencyCategory::Slow,
1362            LatencyCategory::VerySlow,
1363        ];
1364
1365        for category in categories {
1366            assert!(!format!("{category:?}").is_empty());
1367        }
1368    }
1369
1370    #[test]
1371    fn test_type_behavior_pattern_creation() {
1372        let pattern = TypeBehaviorPattern {
1373            has_interior_mutability: true,
1374            is_thread_safe: false,
1375            can_block: true,
1376            manages_memory_layout: false,
1377            deadlock_potential: true,
1378            has_runtime_borrow_check: false,
1379            has_runtime_overhead: true,
1380        };
1381
1382        assert!(pattern.has_interior_mutability);
1383        assert!(!pattern.is_thread_safe);
1384        assert!(pattern.can_block);
1385        assert!(pattern.deadlock_potential);
1386        assert!(pattern.has_runtime_overhead);
1387    }
1388
1389    #[test]
1390    fn test_performance_info_creation() {
1391        let perf_info = PerformanceInfo {
1392            overhead_factor: 2.5,
1393            memory_overhead: 64,
1394            is_lock_free: false,
1395            latency_category: LatencyCategory::Moderate,
1396        };
1397
1398        assert!((perf_info.overhead_factor - 2.5).abs() < f64::EPSILON);
1399        assert_eq!(perf_info.memory_overhead, 64);
1400        assert!(!perf_info.is_lock_free);
1401        assert_eq!(perf_info.latency_category, LatencyCategory::Moderate);
1402    }
1403
1404    #[test]
1405    fn test_channel_state_info() {
1406        let channel_info = ChannelStateInfo {
1407            capacity: Some(100),
1408            current_size: 50,
1409            sender_count: 2,
1410            receiver_count: 1,
1411            is_closed: false,
1412        };
1413
1414        assert_eq!(channel_info.capacity, Some(100));
1415        assert_eq!(channel_info.current_size, 50);
1416        assert_eq!(channel_info.sender_count, 2);
1417        assert_eq!(channel_info.receiver_count, 1);
1418        assert!(!channel_info.is_closed);
1419    }
1420
1421    #[test]
1422    fn test_contention_type_variants() {
1423        let types = vec![
1424            ContentionType::MutexContention,
1425            ContentionType::RwLockReadContention,
1426            ContentionType::RwLockWriteContention,
1427        ];
1428
1429        for contention_type in types {
1430            assert!(!format!("{contention_type:?}").is_empty());
1431        }
1432    }
1433}