1use crate::core::types::AllocationInfo;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub enum AdvancedTypeCategory {
15 InteriorMutability,
17 Synchronization,
19 Channel,
21 Atomic,
23 ThreadLocal,
25 MemoryManagement,
27 Async,
29}
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct TypeBehaviorPattern {
34 pub has_interior_mutability: bool,
36 pub is_thread_safe: bool,
38 pub can_block: bool,
40 pub manages_memory_layout: bool,
42 pub deadlock_potential: bool,
44 pub has_runtime_borrow_check: bool,
46 pub has_runtime_overhead: bool,
48}
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52pub struct AdvancedTypeInfo {
53 pub category: AdvancedTypeCategory,
55 pub behavior: TypeBehaviorPattern,
57 pub state_info: TypeStateInfo,
59 pub potential_issues: Vec<TypeIssue>,
61 pub performance_info: PerformanceInfo,
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TypeStateInfo {
68 pub is_borrowed: Option<bool>,
70 pub borrow_count: Option<usize>,
72 pub is_locked: Option<bool>,
74 pub lock_owner_thread: Option<String>,
76 pub wait_queue_length: Option<usize>,
78 pub channel_info: Option<ChannelStateInfo>,
80}
81
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct ChannelStateInfo {
85 pub capacity: Option<usize>,
87 pub current_size: usize,
89 pub sender_count: usize,
91 pub receiver_count: usize,
93 pub is_closed: bool,
95}
96
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub struct TypeIssue {
100 pub severity: IssueSeverity,
102 pub description: String,
104 pub suggestion: Option<String>,
106 pub location: Option<String>,
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub enum IssueSeverity {
113 Info,
115 Warning,
117 Error,
119 Critical,
121}
122
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125pub struct PerformanceInfo {
126 pub overhead_factor: f64,
128 pub memory_overhead: usize,
130 pub is_lock_free: bool,
132 pub latency_category: LatencyCategory,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
138pub enum LatencyCategory {
139 Immediate,
141 Fast,
143 Moderate,
145 Slow,
147 VerySlow,
149}
150
151pub trait AdvancedTypeAnalyzer {
153 fn analyze_advanced_type(&self) -> AdvancedTypeInfo;
155
156 fn get_current_state(&self) -> TypeStateInfo;
158
159 fn check_issues(&self) -> Vec<TypeIssue>;
161
162 fn get_performance_info(&self) -> PerformanceInfo;
164}
165
166pub struct GenericAdvancedTypeAnalyzer;
168
169impl GenericAdvancedTypeAnalyzer {
170 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 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 AdvancedTypeCategory::MemoryManagement
221 }
222 }
223
224 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"), 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, 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, 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, manages_memory_layout: true,
289 deadlock_potential: false,
290 has_runtime_borrow_check: false,
291 has_runtime_overhead: true,
292 },
293 }
294 }
295
296 fn extract_state_info(_type_name: &str, _allocation: &AllocationInfo) -> TypeStateInfo {
298 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 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 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 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, memory_overhead: 0,
365 is_lock_free: true,
366 latency_category: LatencyCategory::Immediate,
367 }
368 } else {
369 PerformanceInfo {
370 overhead_factor: 2.0, memory_overhead: std::mem::size_of::<usize>(), is_lock_free: true,
373 latency_category: LatencyCategory::Fast,
374 }
375 }
376 }
377 AdvancedTypeCategory::Synchronization => PerformanceInfo {
378 overhead_factor: 10.0, memory_overhead: std::mem::size_of::<usize>() * 2, is_lock_free: false,
381 latency_category: LatencyCategory::Moderate,
382 },
383 AdvancedTypeCategory::Channel => PerformanceInfo {
384 overhead_factor: 5.0, memory_overhead: 64, is_lock_free: false,
387 latency_category: LatencyCategory::Moderate,
388 },
389 AdvancedTypeCategory::Atomic => PerformanceInfo {
390 overhead_factor: 1.5, memory_overhead: 0,
392 is_lock_free: true,
393 latency_category: LatencyCategory::Immediate,
394 },
395 AdvancedTypeCategory::ThreadLocal => PerformanceInfo {
396 overhead_factor: 3.0, memory_overhead: std::mem::size_of::<usize>(), is_lock_free: true,
399 latency_category: LatencyCategory::Fast,
400 },
401 AdvancedTypeCategory::MemoryManagement => PerformanceInfo {
402 overhead_factor: 1.0, memory_overhead: 0,
404 is_lock_free: true,
405 latency_category: LatencyCategory::Immediate,
406 },
407 AdvancedTypeCategory::Async => PerformanceInfo {
408 overhead_factor: 4.0, memory_overhead: 32, is_lock_free: true,
411 latency_category: LatencyCategory::Fast,
412 },
413 }
414 }
415}
416
417#[derive(Debug, Clone, Serialize, Deserialize)]
419pub struct AdvancedTypeAnalysisReport {
420 pub by_category: HashMap<String, Vec<AdvancedTypeInfo>>,
422 pub all_issues: Vec<TypeIssue>,
424 pub performance_summary: PerformanceSummary,
426 pub statistics: AdvancedTypeStatistics,
428}
429
430#[derive(Debug, Clone, Serialize, Deserialize)]
432pub struct PerformanceSummary {
433 pub total_overhead_factor: f64,
435 pub total_memory_overhead: usize,
437 pub lock_free_percentage: f64,
439 pub dominant_latency_category: LatencyCategory,
441}
442
443#[derive(Debug, Clone, Serialize, Deserialize)]
445pub struct AdvancedTypeStatistics {
446 pub by_category: HashMap<String, usize>,
448 pub by_issue_severity: HashMap<String, usize>,
450 pub by_latency_category: HashMap<String, usize>,
452 pub total_advanced_types: usize,
454}
455
456pub 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 if is_advanced_type(type_name) {
470 let analysis =
471 GenericAdvancedTypeAnalyzer::analyze_by_type_name(type_name, allocation);
472
473 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 by_category.entry(category_key).or_default().push(analysis);
483
484 all_issues.extend(issues);
486
487 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 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 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
532pub 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
558pub 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
595pub 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<"), 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
675pub 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 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
744fn calculate_overhead(type_name: &str) -> usize {
746 if type_name.contains("RefCell<") {
747 std::mem::size_of::<isize>() } else if type_name.contains("Mutex<") {
749 64 } else if type_name.contains("RwLock<") {
751 96 } else if type_name.contains("Arc<") || type_name.contains("Rc<") {
753 std::mem::size_of::<usize>() * 2 } else {
755 0
756 }
757}
758
759fn 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
790pub 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 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, zero_cost: true, });
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
858pub 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, 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
917fn 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
927fn 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 (total_locks as f64).log2() / 10.0
937}
938
939#[derive(Debug, Clone, Serialize, Deserialize)]
943pub struct InteriorMutabilityReport {
944 pub cell_instances: Vec<CellInstance>,
946 pub refcell_instances: Vec<RefCellInstance>,
948 pub unsafe_cell_instances: Vec<UnsafeCellInstance>,
950 pub runtime_borrow_violations: Vec<BorrowViolation>,
952 pub total_interior_mutability_types: usize,
954 pub analysis_timestamp: u64,
956}
957
958#[derive(Debug, Clone, Serialize, Deserialize)]
960pub struct CellInstance {
961 pub ptr: usize,
963 pub type_name: String,
965 pub size: usize,
967 pub thread_safe: bool,
969 pub zero_cost: bool,
971}
972
973#[derive(Debug, Clone, Serialize, Deserialize)]
975pub struct RefCellInstance {
976 pub ptr: usize,
978 pub type_name: String,
980 pub size: usize,
982 pub current_borrow_count: usize,
984 pub has_active_mut_borrow: bool,
986 pub runtime_check_overhead: bool,
988}
989
990#[derive(Debug, Clone, Serialize, Deserialize)]
992pub struct UnsafeCellInstance {
993 pub ptr: usize,
995 pub type_name: String,
997 pub size: usize,
999 pub requires_unsafe_access: bool,
1001}
1002
1003#[derive(Debug, Clone, Serialize, Deserialize)]
1005pub struct BorrowViolation {
1006 pub ptr: usize,
1008 pub violation_type: BorrowViolationType,
1010 pub borrow_count: usize,
1012 pub timestamp: u64,
1014}
1015
1016#[derive(Debug, Clone, Serialize, Deserialize)]
1018pub enum BorrowViolationType {
1019 MultipleBorrows,
1021 MutableBorrowConflict,
1023 BorrowAfterMove,
1025}
1026
1027#[derive(Debug, Clone, Serialize, Deserialize)]
1029pub struct ConcurrencyPrimitiveReport {
1030 pub mutex_instances: Vec<MutexInstance>,
1032 pub rwlock_instances: Vec<RwLockInstance>,
1034 pub condvar_instances: Vec<CondvarInstance>,
1036 pub lock_contentions: Vec<LockContention>,
1038 pub deadlock_potential_score: f64,
1040 pub analysis_timestamp: u64,
1042}
1043
1044#[derive(Debug, Clone, Serialize, Deserialize)]
1046pub struct MutexInstance {
1047 pub ptr: usize,
1049 pub type_name: String,
1051 pub size: usize,
1053 pub is_locked: bool,
1055 pub lock_owner_thread: Option<String>,
1057 pub waiting_threads: usize,
1059 pub total_lock_acquisitions: u64,
1061 pub total_wait_time_ns: u64,
1063}
1064
1065#[derive(Debug, Clone, Serialize, Deserialize)]
1067pub struct RwLockInstance {
1068 pub ptr: usize,
1070 pub type_name: String,
1072 pub size: usize,
1074 pub read_count: usize,
1076 pub has_write_lock: bool,
1078 pub waiting_readers: usize,
1080 pub waiting_writers: usize,
1082 pub total_read_acquisitions: u64,
1084 pub total_write_acquisitions: u64,
1086}
1087
1088#[derive(Debug, Clone, Serialize, Deserialize)]
1090pub struct CondvarInstance {
1091 pub ptr: usize,
1093 pub type_name: String,
1095 pub size: usize,
1097 pub waiting_threads: usize,
1099 pub total_notifications: u64,
1101}
1102
1103#[derive(Debug, Clone, Serialize, Deserialize)]
1105pub struct LockContention {
1106 pub lock_ptr: usize,
1108 pub contention_type: ContentionType,
1110 pub waiting_time_ns: u64,
1112 pub thread_id: String,
1114 pub timestamp: u64,
1116}
1117
1118#[derive(Debug, Clone, Serialize, Deserialize)]
1120pub enum ContentionType {
1121 MutexContention,
1123 RwLockReadContention,
1125 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); }
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 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), ];
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; 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 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}