1use std::collections::{HashMap, HashSet};
7use std::fmt;
8use std::path::PathBuf;
9
10use crate::analyzer::ItemDependency;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
17pub enum Visibility {
18 Public,
20 PubCrate,
22 PubSuper,
24 PubIn,
26 #[default]
28 Private,
29}
30
31impl Visibility {
32 pub fn allows_external_access(&self) -> bool {
34 matches!(self, Visibility::Public | Visibility::PubCrate)
35 }
36
37 pub fn is_intrusive_from(&self, same_crate: bool, same_module: bool) -> bool {
42 if same_module {
43 return false;
45 }
46
47 match self {
48 Visibility::Public => false, Visibility::PubCrate => !same_crate, Visibility::PubSuper | Visibility::PubIn => true, Visibility::Private => true, }
53 }
54
55 pub fn intrusive_penalty(&self) -> f64 {
59 match self {
60 Visibility::Public => 0.0, Visibility::PubCrate => 0.25, Visibility::PubSuper => 0.5, Visibility::PubIn => 0.5, Visibility::Private => 1.0, }
66 }
67}
68
69impl fmt::Display for Visibility {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 match self {
72 Visibility::Public => write!(f, "pub"),
73 Visibility::PubCrate => write!(f, "pub(crate)"),
74 Visibility::PubSuper => write!(f, "pub(super)"),
75 Visibility::PubIn => write!(f, "pub(in ...)"),
76 Visibility::Private => write!(f, "private"),
77 }
78 }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq)]
83pub enum IntegrationStrength {
84 Intrusive,
86 Functional,
88 Model,
90 Contract,
92}
93
94impl IntegrationStrength {
95 pub fn value(&self) -> f64 {
97 match self {
98 IntegrationStrength::Intrusive => 1.0,
99 IntegrationStrength::Functional => 0.75,
100 IntegrationStrength::Model => 0.5,
101 IntegrationStrength::Contract => 0.25,
102 }
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq)]
108pub enum Distance {
109 SameFunction,
111 SameModule,
113 DifferentModule,
115 DifferentCrate,
117}
118
119impl Distance {
120 pub fn value(&self) -> f64 {
122 match self {
123 Distance::SameFunction => 0.0,
124 Distance::SameModule => 0.25,
125 Distance::DifferentModule => 0.5,
126 Distance::DifferentCrate => 1.0,
127 }
128 }
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
133pub enum Volatility {
134 Low,
136 Medium,
138 High,
140}
141
142impl Volatility {
143 pub fn value(&self) -> f64 {
145 match self {
146 Volatility::Low => 0.0,
147 Volatility::Medium => 0.5,
148 Volatility::High => 1.0,
149 }
150 }
151
152 pub fn from_count(count: usize) -> Self {
154 match count {
155 0..=2 => Volatility::Low,
156 3..=10 => Volatility::Medium,
157 _ => Volatility::High,
158 }
159 }
160}
161
162#[derive(Debug, Clone, Default)]
164pub struct CouplingLocation {
165 pub file_path: Option<PathBuf>,
167 pub line: usize,
169}
170
171#[derive(Debug, Clone)]
173pub struct CouplingMetrics {
174 pub source: String,
176 pub target: String,
178 pub strength: IntegrationStrength,
180 pub distance: Distance,
182 pub volatility: Volatility,
184 pub source_crate: Option<String>,
186 pub target_crate: Option<String>,
188 pub target_visibility: Visibility,
190 pub location: CouplingLocation,
192}
193
194impl CouplingMetrics {
195 pub fn new(
197 source: String,
198 target: String,
199 strength: IntegrationStrength,
200 distance: Distance,
201 volatility: Volatility,
202 ) -> Self {
203 Self {
204 source,
205 target,
206 strength,
207 distance,
208 volatility,
209 source_crate: None,
210 target_crate: None,
211 target_visibility: Visibility::default(),
212 location: CouplingLocation::default(),
213 }
214 }
215
216 pub fn with_visibility(
218 source: String,
219 target: String,
220 strength: IntegrationStrength,
221 distance: Distance,
222 volatility: Volatility,
223 visibility: Visibility,
224 ) -> Self {
225 Self {
226 source,
227 target,
228 strength,
229 distance,
230 volatility,
231 source_crate: None,
232 target_crate: None,
233 target_visibility: visibility,
234 location: CouplingLocation::default(),
235 }
236 }
237
238 #[allow(clippy::too_many_arguments)]
240 pub fn with_location(
241 source: String,
242 target: String,
243 strength: IntegrationStrength,
244 distance: Distance,
245 volatility: Volatility,
246 visibility: Visibility,
247 file_path: PathBuf,
248 line: usize,
249 ) -> Self {
250 Self {
251 source,
252 target,
253 strength,
254 distance,
255 volatility,
256 source_crate: None,
257 target_crate: None,
258 target_visibility: visibility,
259 location: CouplingLocation {
260 file_path: Some(file_path),
261 line,
262 },
263 }
264 }
265
266 pub fn is_visibility_intrusive(&self) -> bool {
271 let same_crate = self.source_crate == self.target_crate;
272 let same_module =
273 self.distance == Distance::SameModule || self.distance == Distance::SameFunction;
274 self.target_visibility
275 .is_intrusive_from(same_crate, same_module)
276 }
277
278 pub fn effective_strength(&self) -> IntegrationStrength {
283 if self.is_visibility_intrusive() && self.strength != IntegrationStrength::Intrusive {
284 match self.strength {
286 IntegrationStrength::Contract => IntegrationStrength::Model,
287 IntegrationStrength::Model => IntegrationStrength::Functional,
288 IntegrationStrength::Functional => IntegrationStrength::Intrusive,
289 IntegrationStrength::Intrusive => IntegrationStrength::Intrusive,
290 }
291 } else {
292 self.strength
293 }
294 }
295
296 pub fn effective_strength_value(&self) -> f64 {
298 self.effective_strength().value()
299 }
300
301 pub fn strength_value(&self) -> f64 {
303 self.strength.value()
304 }
305
306 pub fn distance_value(&self) -> f64 {
308 self.distance.value()
309 }
310
311 pub fn volatility_value(&self) -> f64 {
313 self.volatility.value()
314 }
315}
316
317#[derive(Debug, Clone)]
319pub struct TypeDefinition {
320 pub name: String,
322 pub visibility: Visibility,
324 pub is_trait: bool,
326 pub is_newtype: bool,
328 pub inner_type: Option<String>,
330 pub has_serde_derive: bool,
332 pub public_field_count: usize,
334 pub total_field_count: usize,
336}
337
338#[derive(Debug, Clone)]
340pub struct FunctionDefinition {
341 pub name: String,
343 pub visibility: Visibility,
345 pub param_count: usize,
347 pub primitive_param_count: usize,
349 pub param_types: Vec<String>,
351}
352
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum BalanceClassification {
356 HighCohesion,
358 LooseCoupling,
360 Acceptable,
362 Pain,
364 LocalComplexity,
366}
367
368impl BalanceClassification {
369 pub fn classify(
371 strength: IntegrationStrength,
372 distance: Distance,
373 volatility: Volatility,
374 ) -> Self {
375 let is_strong = strength.value() >= 0.5;
376 let is_far = distance.value() >= 0.5;
377 let is_volatile = volatility == Volatility::High;
378
379 match (is_strong, is_far, is_volatile) {
380 (true, false, _) => BalanceClassification::HighCohesion,
381 (false, true, _) => BalanceClassification::LooseCoupling,
382 (false, false, _) => BalanceClassification::LocalComplexity,
383 (true, true, false) => BalanceClassification::Acceptable,
384 (true, true, true) => BalanceClassification::Pain,
385 }
386 }
387
388 pub fn description_ja(&self) -> &'static str {
390 match self {
391 BalanceClassification::HighCohesion => "高凝集 (強+近)",
392 BalanceClassification::LooseCoupling => "疎結合 (弱+遠)",
393 BalanceClassification::Acceptable => "許容可能 (強+遠+安定)",
394 BalanceClassification::Pain => "要改善 (強+遠+変動)",
395 BalanceClassification::LocalComplexity => "局所複雑性 (弱+近)",
396 }
397 }
398
399 pub fn description_en(&self) -> &'static str {
401 match self {
402 BalanceClassification::HighCohesion => "High Cohesion",
403 BalanceClassification::LooseCoupling => "Loose Coupling",
404 BalanceClassification::Acceptable => "Acceptable",
405 BalanceClassification::Pain => "Needs Refactoring",
406 BalanceClassification::LocalComplexity => "Local Complexity",
407 }
408 }
409
410 pub fn is_ideal(&self) -> bool {
412 matches!(
413 self,
414 BalanceClassification::HighCohesion | BalanceClassification::LooseCoupling
415 )
416 }
417
418 pub fn needs_attention(&self) -> bool {
420 matches!(
421 self,
422 BalanceClassification::Pain | BalanceClassification::LocalComplexity
423 )
424 }
425}
426
427#[derive(Debug, Clone, Default)]
429pub struct DimensionStats {
430 pub strength_counts: StrengthCounts,
432 pub distance_counts: DistanceCounts,
434 pub volatility_counts: VolatilityCounts,
436 pub balance_counts: BalanceCounts,
438}
439
440impl DimensionStats {
441 pub fn total(&self) -> usize {
443 self.strength_counts.total()
444 }
445
446 pub fn strength_percentages(&self) -> (f64, f64, f64, f64) {
448 let total = self.total() as f64;
449 if total == 0.0 {
450 return (0.0, 0.0, 0.0, 0.0);
451 }
452 (
453 self.strength_counts.intrusive as f64 / total * 100.0,
454 self.strength_counts.functional as f64 / total * 100.0,
455 self.strength_counts.model as f64 / total * 100.0,
456 self.strength_counts.contract as f64 / total * 100.0,
457 )
458 }
459
460 pub fn distance_percentages(&self) -> (f64, f64, f64) {
462 let total = self.total() as f64;
463 if total == 0.0 {
464 return (0.0, 0.0, 0.0);
465 }
466 (
467 self.distance_counts.same_module as f64 / total * 100.0,
468 self.distance_counts.different_module as f64 / total * 100.0,
469 self.distance_counts.different_crate as f64 / total * 100.0,
470 )
471 }
472
473 pub fn volatility_percentages(&self) -> (f64, f64, f64) {
475 let total = self.total() as f64;
476 if total == 0.0 {
477 return (0.0, 0.0, 0.0);
478 }
479 (
480 self.volatility_counts.low as f64 / total * 100.0,
481 self.volatility_counts.medium as f64 / total * 100.0,
482 self.volatility_counts.high as f64 / total * 100.0,
483 )
484 }
485
486 pub fn ideal_count(&self) -> usize {
488 self.balance_counts.high_cohesion + self.balance_counts.loose_coupling
489 }
490
491 pub fn problematic_count(&self) -> usize {
493 self.balance_counts.pain + self.balance_counts.local_complexity
494 }
495
496 pub fn ideal_percentage(&self) -> f64 {
498 let total = self.total() as f64;
499 if total == 0.0 {
500 return 0.0;
501 }
502 self.ideal_count() as f64 / total * 100.0
503 }
504}
505
506#[derive(Debug, Clone, Default)]
508pub struct StrengthCounts {
509 pub intrusive: usize,
510 pub functional: usize,
511 pub model: usize,
512 pub contract: usize,
513}
514
515impl StrengthCounts {
516 pub fn total(&self) -> usize {
518 self.intrusive + self.functional + self.model + self.contract
519 }
520}
521
522#[derive(Debug, Clone, Default)]
524pub struct DistanceCounts {
525 pub same_module: usize,
526 pub different_module: usize,
527 pub different_crate: usize,
528}
529
530#[derive(Debug, Clone, Default)]
532pub struct VolatilityCounts {
533 pub low: usize,
534 pub medium: usize,
535 pub high: usize,
536}
537
538#[derive(Debug, Clone, Default)]
540pub struct BalanceCounts {
541 pub high_cohesion: usize,
542 pub loose_coupling: usize,
543 pub acceptable: usize,
544 pub pain: usize,
545 pub local_complexity: usize,
546}
547
548#[derive(Debug, Clone, Default)]
550pub struct ModuleMetrics {
551 pub path: PathBuf,
553 pub name: String,
555 pub trait_impl_count: usize,
557 pub inherent_impl_count: usize,
559 pub function_call_count: usize,
561 pub type_usage_count: usize,
563 pub external_deps: Vec<String>,
565 pub internal_deps: Vec<String>,
567 pub type_definitions: HashMap<String, TypeDefinition>,
569 pub function_definitions: HashMap<String, FunctionDefinition>,
571 pub item_dependencies: Vec<ItemDependency>,
573}
574
575impl ModuleMetrics {
576 pub fn new(path: PathBuf, name: String) -> Self {
577 Self {
578 path,
579 name,
580 ..Default::default()
581 }
582 }
583
584 pub fn add_type_definition(&mut self, name: String, visibility: Visibility, is_trait: bool) {
586 self.type_definitions.insert(
587 name.clone(),
588 TypeDefinition {
589 name,
590 visibility,
591 is_trait,
592 is_newtype: false,
593 inner_type: None,
594 has_serde_derive: false,
595 public_field_count: 0,
596 total_field_count: 0,
597 },
598 );
599 }
600
601 #[allow(clippy::too_many_arguments)]
603 pub fn add_type_definition_full(
604 &mut self,
605 name: String,
606 visibility: Visibility,
607 is_trait: bool,
608 is_newtype: bool,
609 inner_type: Option<String>,
610 has_serde_derive: bool,
611 public_field_count: usize,
612 total_field_count: usize,
613 ) {
614 self.type_definitions.insert(
615 name.clone(),
616 TypeDefinition {
617 name,
618 visibility,
619 is_trait,
620 is_newtype,
621 inner_type,
622 has_serde_derive,
623 public_field_count,
624 total_field_count,
625 },
626 );
627 }
628
629 pub fn add_function_definition(&mut self, name: String, visibility: Visibility) {
631 self.function_definitions.insert(
632 name.clone(),
633 FunctionDefinition {
634 name,
635 visibility,
636 param_count: 0,
637 primitive_param_count: 0,
638 param_types: Vec::new(),
639 },
640 );
641 }
642
643 pub fn add_function_definition_full(
645 &mut self,
646 name: String,
647 visibility: Visibility,
648 param_count: usize,
649 primitive_param_count: usize,
650 param_types: Vec<String>,
651 ) {
652 self.function_definitions.insert(
653 name.clone(),
654 FunctionDefinition {
655 name,
656 visibility,
657 param_count,
658 primitive_param_count,
659 param_types,
660 },
661 );
662 }
663
664 pub fn get_type_visibility(&self, name: &str) -> Option<Visibility> {
666 self.type_definitions.get(name).map(|t| t.visibility)
667 }
668
669 pub fn public_type_count(&self) -> usize {
671 self.type_definitions
672 .values()
673 .filter(|t| t.visibility == Visibility::Public)
674 .count()
675 }
676
677 pub fn private_type_count(&self) -> usize {
679 self.type_definitions
680 .values()
681 .filter(|t| t.visibility != Visibility::Public)
682 .count()
683 }
684
685 pub fn average_strength(&self) -> f64 {
687 let total = self.trait_impl_count + self.inherent_impl_count;
688 if total == 0 {
689 return 0.0;
690 }
691
692 let contract_weight = self.trait_impl_count as f64 * IntegrationStrength::Contract.value();
693 let intrusive_weight =
694 self.inherent_impl_count as f64 * IntegrationStrength::Intrusive.value();
695
696 (contract_weight + intrusive_weight) / total as f64
697 }
698
699 pub fn newtype_count(&self) -> usize {
701 self.type_definitions
702 .values()
703 .filter(|t| t.is_newtype)
704 .count()
705 }
706
707 pub fn serde_type_count(&self) -> usize {
709 self.type_definitions
710 .values()
711 .filter(|t| t.has_serde_derive)
712 .count()
713 }
714
715 pub fn newtype_ratio(&self) -> f64 {
717 let non_trait_types = self
718 .type_definitions
719 .values()
720 .filter(|t| !t.is_trait)
721 .count();
722 if non_trait_types == 0 {
723 return 0.0;
724 }
725 self.newtype_count() as f64 / non_trait_types as f64
726 }
727
728 pub fn types_with_public_fields(&self) -> usize {
730 self.type_definitions
731 .values()
732 .filter(|t| t.public_field_count > 0)
733 .count()
734 }
735
736 pub fn function_count(&self) -> usize {
738 self.function_definitions.len()
739 }
740
741 pub fn functions_with_primitive_obsession(&self) -> Vec<&FunctionDefinition> {
744 self.function_definitions
745 .values()
746 .filter(|f| {
747 f.param_count >= 3 && f.primitive_param_count as f64 / f.param_count as f64 >= 0.6
748 })
749 .collect()
750 }
751
752 pub fn is_god_module(&self, max_functions: usize, max_types: usize, max_impls: usize) -> bool {
755 self.function_count() > max_functions
756 || self.type_definitions.len() > max_types
757 || (self.trait_impl_count + self.inherent_impl_count) > max_impls
758 }
759}
760
761#[derive(Debug, Default)]
763pub struct ProjectMetrics {
764 pub modules: HashMap<String, ModuleMetrics>,
766 pub couplings: Vec<CouplingMetrics>,
768 pub file_changes: HashMap<String, usize>,
770 pub total_files: usize,
772 pub workspace_name: Option<String>,
774 pub workspace_members: Vec<String>,
776 pub crate_dependencies: HashMap<String, Vec<String>>,
778 pub type_registry: HashMap<String, (String, Visibility)>,
780}
781
782impl ProjectMetrics {
783 pub fn new() -> Self {
784 Self::default()
785 }
786
787 pub fn add_module(&mut self, metrics: ModuleMetrics) {
789 self.modules.insert(metrics.name.clone(), metrics);
790 }
791
792 pub fn add_coupling(&mut self, coupling: CouplingMetrics) {
794 self.couplings.push(coupling);
795 }
796
797 pub fn register_type(
799 &mut self,
800 type_name: String,
801 module_name: String,
802 visibility: Visibility,
803 ) {
804 self.type_registry
805 .insert(type_name, (module_name, visibility));
806 }
807
808 pub fn get_type_visibility(&self, type_name: &str) -> Option<Visibility> {
810 self.type_registry.get(type_name).map(|(_, vis)| *vis)
811 }
812
813 pub fn get_type_module(&self, type_name: &str) -> Option<&str> {
815 self.type_registry
816 .get(type_name)
817 .map(|(module, _)| module.as_str())
818 }
819
820 pub fn update_coupling_visibility(&mut self) {
825 let visibility_updates: Vec<(usize, Visibility)> = self
827 .couplings
828 .iter()
829 .enumerate()
830 .filter_map(|(idx, coupling)| {
831 let target_type = coupling
832 .target
833 .split("::")
834 .last()
835 .unwrap_or(&coupling.target);
836 self.type_registry
837 .get(target_type)
838 .map(|(_, vis)| (idx, *vis))
839 })
840 .collect();
841
842 for (idx, visibility) in visibility_updates {
844 self.couplings[idx].target_visibility = visibility;
845 }
846 }
847
848 pub fn module_count(&self) -> usize {
850 self.modules.len()
851 }
852
853 pub fn coupling_count(&self) -> usize {
855 self.couplings.len()
856 }
857
858 pub fn average_strength(&self) -> Option<f64> {
860 if self.couplings.is_empty() {
861 return None;
862 }
863 let sum: f64 = self.couplings.iter().map(|c| c.strength_value()).sum();
864 Some(sum / self.couplings.len() as f64)
865 }
866
867 pub fn average_distance(&self) -> Option<f64> {
869 if self.couplings.is_empty() {
870 return None;
871 }
872 let sum: f64 = self.couplings.iter().map(|c| c.distance_value()).sum();
873 Some(sum / self.couplings.len() as f64)
874 }
875
876 pub fn update_volatility_from_git(&mut self) {
882 if self.file_changes.is_empty() {
883 return;
884 }
885
886 #[cfg(test)]
888 {
889 eprintln!("DEBUG: file_changes = {:?}", self.file_changes);
890 }
891
892 for coupling in &mut self.couplings {
893 let target_parts: Vec<&str> = coupling.target.split("::").collect();
904
905 let mut max_changes = 0usize;
907 for (file_path, &changes) in &self.file_changes {
908 let file_name = file_path
910 .rsplit('/')
911 .next()
912 .unwrap_or(file_path)
913 .trim_end_matches(".rs");
914
915 let matches = target_parts.iter().any(|part| {
917 let part_lower = part.to_lowercase();
918 let file_lower = file_name.to_lowercase();
919
920 if part_lower == file_lower {
922 return true;
923 }
924
925 if file_lower == "lib" && !part.is_empty() && *part != "*" {
928 if target_parts.len() >= 2 && target_parts[1] == *part {
931 return true;
932 }
933 }
934
935 let part_normalized = part_lower.replace('-', "_");
938 let file_normalized = file_lower.replace('-', "_");
939 if part_normalized == file_normalized {
940 return true;
941 }
942
943 if file_path.to_lowercase().contains(&part_lower) {
945 return true;
946 }
947
948 false
949 });
950
951 if matches {
952 max_changes = max_changes.max(changes);
953 }
954 }
955
956 coupling.volatility = Volatility::from_count(max_changes);
957 }
958 }
959
960 fn build_dependency_graph(&self) -> HashMap<String, HashSet<String>> {
962 let mut graph: HashMap<String, HashSet<String>> = HashMap::new();
963
964 for coupling in &self.couplings {
965 if coupling.distance == Distance::DifferentCrate {
967 continue;
968 }
969
970 let source = coupling.source.clone();
972 let target = coupling.target.clone();
973
974 graph.entry(source).or_default().insert(target);
975 }
976
977 graph
978 }
979
980 pub fn detect_circular_dependencies(&self) -> Vec<Vec<String>> {
985 let graph = self.build_dependency_graph();
986 let mut cycles: Vec<Vec<String>> = Vec::new();
987 let mut visited: HashSet<String> = HashSet::new();
988 let mut rec_stack: HashSet<String> = HashSet::new();
989
990 for node in graph.keys() {
991 if !visited.contains(node) {
992 let mut path = Vec::new();
993 self.dfs_find_cycles(
994 node,
995 &graph,
996 &mut visited,
997 &mut rec_stack,
998 &mut path,
999 &mut cycles,
1000 );
1001 }
1002 }
1003
1004 let mut unique_cycles: Vec<Vec<String>> = Vec::new();
1006 for cycle in cycles {
1007 let normalized = Self::normalize_cycle(&cycle);
1008 if !unique_cycles
1009 .iter()
1010 .any(|c| Self::normalize_cycle(c) == normalized)
1011 {
1012 unique_cycles.push(cycle);
1013 }
1014 }
1015
1016 unique_cycles
1017 }
1018
1019 fn dfs_find_cycles(
1021 &self,
1022 node: &str,
1023 graph: &HashMap<String, HashSet<String>>,
1024 visited: &mut HashSet<String>,
1025 rec_stack: &mut HashSet<String>,
1026 path: &mut Vec<String>,
1027 cycles: &mut Vec<Vec<String>>,
1028 ) {
1029 visited.insert(node.to_string());
1030 rec_stack.insert(node.to_string());
1031 path.push(node.to_string());
1032
1033 if let Some(neighbors) = graph.get(node) {
1034 for neighbor in neighbors {
1035 if !visited.contains(neighbor) {
1036 self.dfs_find_cycles(neighbor, graph, visited, rec_stack, path, cycles);
1037 } else if rec_stack.contains(neighbor) {
1038 if let Some(start_idx) = path.iter().position(|n| n == neighbor) {
1040 let cycle: Vec<String> = path[start_idx..].to_vec();
1041 if cycle.len() >= 2 {
1042 cycles.push(cycle);
1043 }
1044 }
1045 }
1046 }
1047 }
1048
1049 path.pop();
1050 rec_stack.remove(node);
1051 }
1052
1053 fn normalize_cycle(cycle: &[String]) -> Vec<String> {
1056 if cycle.is_empty() {
1057 return Vec::new();
1058 }
1059
1060 let min_pos = cycle
1062 .iter()
1063 .enumerate()
1064 .min_by_key(|(_, s)| s.as_str())
1065 .map(|(i, _)| i)
1066 .unwrap_or(0);
1067
1068 let mut normalized: Vec<String> = cycle[min_pos..].to_vec();
1070 normalized.extend_from_slice(&cycle[..min_pos]);
1071 normalized
1072 }
1073
1074 pub fn circular_dependency_summary(&self) -> CircularDependencySummary {
1076 let cycles = self.detect_circular_dependencies();
1077 let affected_modules: HashSet<String> = cycles.iter().flatten().cloned().collect();
1078
1079 CircularDependencySummary {
1080 total_cycles: cycles.len(),
1081 affected_modules: affected_modules.len(),
1082 cycles,
1083 }
1084 }
1085
1086 pub fn calculate_dimension_stats(&self) -> DimensionStats {
1091 let mut stats = DimensionStats::default();
1092
1093 for coupling in &self.couplings {
1094 match coupling.strength {
1096 IntegrationStrength::Intrusive => stats.strength_counts.intrusive += 1,
1097 IntegrationStrength::Functional => stats.strength_counts.functional += 1,
1098 IntegrationStrength::Model => stats.strength_counts.model += 1,
1099 IntegrationStrength::Contract => stats.strength_counts.contract += 1,
1100 }
1101
1102 match coupling.distance {
1104 Distance::SameFunction | Distance::SameModule => {
1105 stats.distance_counts.same_module += 1
1106 }
1107 Distance::DifferentModule => stats.distance_counts.different_module += 1,
1108 Distance::DifferentCrate => stats.distance_counts.different_crate += 1,
1109 }
1110
1111 match coupling.volatility {
1113 Volatility::Low => stats.volatility_counts.low += 1,
1114 Volatility::Medium => stats.volatility_counts.medium += 1,
1115 Volatility::High => stats.volatility_counts.high += 1,
1116 }
1117
1118 let classification = BalanceClassification::classify(
1120 coupling.strength,
1121 coupling.distance,
1122 coupling.volatility,
1123 );
1124 match classification {
1125 BalanceClassification::HighCohesion => stats.balance_counts.high_cohesion += 1,
1126 BalanceClassification::LooseCoupling => stats.balance_counts.loose_coupling += 1,
1127 BalanceClassification::Acceptable => stats.balance_counts.acceptable += 1,
1128 BalanceClassification::Pain => stats.balance_counts.pain += 1,
1129 BalanceClassification::LocalComplexity => {
1130 stats.balance_counts.local_complexity += 1
1131 }
1132 }
1133 }
1134
1135 stats
1136 }
1137
1138 pub fn total_newtype_count(&self) -> usize {
1140 self.modules.values().map(|m| m.newtype_count()).sum()
1141 }
1142
1143 pub fn total_type_count(&self) -> usize {
1145 self.modules
1146 .values()
1147 .flat_map(|m| m.type_definitions.values())
1148 .filter(|t| !t.is_trait)
1149 .count()
1150 }
1151
1152 pub fn newtype_ratio(&self) -> f64 {
1154 let total = self.total_type_count();
1155 if total == 0 {
1156 return 0.0;
1157 }
1158 self.total_newtype_count() as f64 / total as f64
1159 }
1160
1161 pub fn serde_types(&self) -> Vec<(&str, &TypeDefinition)> {
1163 self.modules
1164 .iter()
1165 .flat_map(|(module_name, m)| {
1166 m.type_definitions
1167 .values()
1168 .filter(|t| t.has_serde_derive)
1169 .map(move |t| (module_name.as_str(), t))
1170 })
1171 .collect()
1172 }
1173
1174 pub fn god_modules(
1176 &self,
1177 max_functions: usize,
1178 max_types: usize,
1179 max_impls: usize,
1180 ) -> Vec<&str> {
1181 self.modules
1182 .iter()
1183 .filter(|(_, m)| m.is_god_module(max_functions, max_types, max_impls))
1184 .map(|(name, _)| name.as_str())
1185 .collect()
1186 }
1187
1188 pub fn functions_with_primitive_obsession(&self) -> Vec<(&str, &FunctionDefinition)> {
1190 self.modules
1191 .iter()
1192 .flat_map(|(module_name, m)| {
1193 m.functions_with_primitive_obsession()
1194 .into_iter()
1195 .map(move |f| (module_name.as_str(), f))
1196 })
1197 .collect()
1198 }
1199
1200 pub fn types_with_public_fields(&self) -> Vec<(&str, &TypeDefinition)> {
1202 self.modules
1203 .iter()
1204 .flat_map(|(module_name, m)| {
1205 m.type_definitions
1206 .values()
1207 .filter(|t| t.public_field_count > 0 && !t.is_trait)
1208 .map(move |t| (module_name.as_str(), t))
1209 })
1210 .collect()
1211 }
1212}
1213
1214#[derive(Debug, Clone)]
1216pub struct CircularDependencySummary {
1217 pub total_cycles: usize,
1219 pub affected_modules: usize,
1221 pub cycles: Vec<Vec<String>>,
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227 use super::*;
1228
1229 #[test]
1230 fn test_integration_strength_values() {
1231 assert_eq!(IntegrationStrength::Intrusive.value(), 1.0);
1232 assert_eq!(IntegrationStrength::Contract.value(), 0.25);
1233 }
1234
1235 #[test]
1236 fn test_distance_values() {
1237 assert_eq!(Distance::SameFunction.value(), 0.0);
1238 assert_eq!(Distance::DifferentCrate.value(), 1.0);
1239 }
1240
1241 #[test]
1242 fn test_volatility_from_count() {
1243 assert_eq!(Volatility::from_count(0), Volatility::Low);
1244 assert_eq!(Volatility::from_count(5), Volatility::Medium);
1245 assert_eq!(Volatility::from_count(15), Volatility::High);
1246 }
1247
1248 #[test]
1249 fn test_module_metrics_average_strength() {
1250 let mut metrics = ModuleMetrics::new(PathBuf::from("test.rs"), "test".to_string());
1251 metrics.trait_impl_count = 3;
1252 metrics.inherent_impl_count = 1;
1253
1254 let avg = metrics.average_strength();
1255 assert!(avg > 0.0 && avg < 1.0);
1256 }
1257
1258 #[test]
1259 fn test_project_metrics() {
1260 let mut project = ProjectMetrics::new();
1261
1262 let module = ModuleMetrics::new(PathBuf::from("lib.rs"), "lib".to_string());
1263 project.add_module(module);
1264
1265 assert_eq!(project.module_count(), 1);
1266 assert_eq!(project.coupling_count(), 0);
1267 }
1268
1269 #[test]
1270 fn test_circular_dependency_detection() {
1271 let mut project = ProjectMetrics::new();
1272
1273 project.add_coupling(CouplingMetrics::new(
1275 "module_a".to_string(),
1276 "module_b".to_string(),
1277 IntegrationStrength::Model,
1278 Distance::DifferentModule,
1279 Volatility::Low,
1280 ));
1281 project.add_coupling(CouplingMetrics::new(
1282 "module_b".to_string(),
1283 "module_c".to_string(),
1284 IntegrationStrength::Model,
1285 Distance::DifferentModule,
1286 Volatility::Low,
1287 ));
1288 project.add_coupling(CouplingMetrics::new(
1289 "module_c".to_string(),
1290 "module_a".to_string(),
1291 IntegrationStrength::Model,
1292 Distance::DifferentModule,
1293 Volatility::Low,
1294 ));
1295
1296 let cycles = project.detect_circular_dependencies();
1297 assert_eq!(cycles.len(), 1);
1298 assert_eq!(cycles[0].len(), 3);
1299 }
1300
1301 #[test]
1302 fn test_no_circular_dependencies() {
1303 let mut project = ProjectMetrics::new();
1304
1305 project.add_coupling(CouplingMetrics::new(
1307 "module_a".to_string(),
1308 "module_b".to_string(),
1309 IntegrationStrength::Model,
1310 Distance::DifferentModule,
1311 Volatility::Low,
1312 ));
1313 project.add_coupling(CouplingMetrics::new(
1314 "module_b".to_string(),
1315 "module_c".to_string(),
1316 IntegrationStrength::Model,
1317 Distance::DifferentModule,
1318 Volatility::Low,
1319 ));
1320
1321 let cycles = project.detect_circular_dependencies();
1322 assert!(cycles.is_empty());
1323 }
1324
1325 #[test]
1326 fn test_external_crates_excluded_from_cycles() {
1327 let mut project = ProjectMetrics::new();
1328
1329 project.add_coupling(CouplingMetrics::new(
1331 "module_a".to_string(),
1332 "serde::Serialize".to_string(),
1333 IntegrationStrength::Contract,
1334 Distance::DifferentCrate, Volatility::Low,
1336 ));
1337 project.add_coupling(CouplingMetrics::new(
1338 "serde::Serialize".to_string(),
1339 "module_a".to_string(),
1340 IntegrationStrength::Contract,
1341 Distance::DifferentCrate, Volatility::Low,
1343 ));
1344
1345 let cycles = project.detect_circular_dependencies();
1346 assert!(cycles.is_empty());
1347 }
1348
1349 #[test]
1350 fn test_circular_dependency_summary() {
1351 let mut project = ProjectMetrics::new();
1352
1353 project.add_coupling(CouplingMetrics::new(
1355 "module_a".to_string(),
1356 "module_b".to_string(),
1357 IntegrationStrength::Functional,
1358 Distance::DifferentModule,
1359 Volatility::Low,
1360 ));
1361 project.add_coupling(CouplingMetrics::new(
1362 "module_b".to_string(),
1363 "module_a".to_string(),
1364 IntegrationStrength::Functional,
1365 Distance::DifferentModule,
1366 Volatility::Low,
1367 ));
1368
1369 let summary = project.circular_dependency_summary();
1370 assert!(summary.total_cycles > 0);
1371 assert!(summary.affected_modules >= 2);
1372 }
1373
1374 #[test]
1375 fn test_visibility_intrusive_detection() {
1376 assert!(!Visibility::Public.is_intrusive_from(true, false));
1378 assert!(!Visibility::Public.is_intrusive_from(false, false));
1379
1380 assert!(!Visibility::PubCrate.is_intrusive_from(true, false));
1382 assert!(Visibility::PubCrate.is_intrusive_from(false, false));
1383
1384 assert!(Visibility::Private.is_intrusive_from(true, false));
1386 assert!(Visibility::Private.is_intrusive_from(false, false));
1387
1388 assert!(!Visibility::Private.is_intrusive_from(true, true));
1390 assert!(!Visibility::Private.is_intrusive_from(false, true));
1391 }
1392
1393 #[test]
1394 fn test_visibility_penalty() {
1395 assert_eq!(Visibility::Public.intrusive_penalty(), 0.0);
1396 assert_eq!(Visibility::PubCrate.intrusive_penalty(), 0.25);
1397 assert_eq!(Visibility::Private.intrusive_penalty(), 1.0);
1398 }
1399
1400 #[test]
1401 fn test_effective_strength() {
1402 let coupling = CouplingMetrics::with_visibility(
1404 "source".to_string(),
1405 "target".to_string(),
1406 IntegrationStrength::Model,
1407 Distance::DifferentModule,
1408 Volatility::Low,
1409 Visibility::Public,
1410 );
1411 assert_eq!(coupling.effective_strength(), IntegrationStrength::Model);
1412
1413 let coupling = CouplingMetrics::with_visibility(
1415 "source".to_string(),
1416 "target".to_string(),
1417 IntegrationStrength::Model,
1418 Distance::DifferentModule,
1419 Volatility::Low,
1420 Visibility::Private,
1421 );
1422 assert_eq!(
1423 coupling.effective_strength(),
1424 IntegrationStrength::Functional
1425 );
1426 }
1427
1428 #[test]
1429 fn test_type_registry() {
1430 let mut project = ProjectMetrics::new();
1431
1432 project.register_type(
1433 "MyStruct".to_string(),
1434 "my_module".to_string(),
1435 Visibility::Public,
1436 );
1437 project.register_type(
1438 "InternalType".to_string(),
1439 "my_module".to_string(),
1440 Visibility::PubCrate,
1441 );
1442
1443 assert_eq!(
1444 project.get_type_visibility("MyStruct"),
1445 Some(Visibility::Public)
1446 );
1447 assert_eq!(
1448 project.get_type_visibility("InternalType"),
1449 Some(Visibility::PubCrate)
1450 );
1451 assert_eq!(project.get_type_visibility("Unknown"), None);
1452
1453 assert_eq!(project.get_type_module("MyStruct"), Some("my_module"));
1454 }
1455
1456 #[test]
1457 fn test_module_type_definitions() {
1458 let mut module = ModuleMetrics::new(PathBuf::from("test.rs"), "test".to_string());
1459
1460 module.add_type_definition("PublicStruct".to_string(), Visibility::Public, false);
1461 module.add_type_definition("PrivateStruct".to_string(), Visibility::Private, false);
1462 module.add_type_definition("PublicTrait".to_string(), Visibility::Public, true);
1463
1464 assert_eq!(module.public_type_count(), 2);
1465 assert_eq!(module.private_type_count(), 1);
1466 assert_eq!(
1467 module.get_type_visibility("PublicStruct"),
1468 Some(Visibility::Public)
1469 );
1470 }
1471
1472 #[test]
1473 fn test_update_volatility_from_git() {
1474 let mut project = ProjectMetrics::new();
1475
1476 project.add_coupling(CouplingMetrics::new(
1478 "crate::main".to_string(),
1479 "crate::balance".to_string(),
1480 IntegrationStrength::Functional,
1481 Distance::DifferentModule,
1482 Volatility::Low, ));
1484 project.add_coupling(CouplingMetrics::new(
1485 "crate::main".to_string(),
1486 "crate::analyzer".to_string(),
1487 IntegrationStrength::Functional,
1488 Distance::DifferentModule,
1489 Volatility::Low,
1490 ));
1491 project.add_coupling(CouplingMetrics::new(
1492 "crate::main".to_string(),
1493 "crate::report".to_string(),
1494 IntegrationStrength::Functional,
1495 Distance::DifferentModule,
1496 Volatility::Low,
1497 ));
1498
1499 project
1501 .file_changes
1502 .insert("src/balance.rs".to_string(), 15); project
1504 .file_changes
1505 .insert("src/analyzer.rs".to_string(), 7); project.file_changes.insert("src/report.rs".to_string(), 2); project.update_volatility_from_git();
1510
1511 let balance_coupling = project
1513 .couplings
1514 .iter()
1515 .find(|c| c.target == "crate::balance")
1516 .unwrap();
1517 assert_eq!(balance_coupling.volatility, Volatility::High);
1518
1519 let analyzer_coupling = project
1520 .couplings
1521 .iter()
1522 .find(|c| c.target == "crate::analyzer")
1523 .unwrap();
1524 assert_eq!(analyzer_coupling.volatility, Volatility::Medium);
1525
1526 let report_coupling = project
1527 .couplings
1528 .iter()
1529 .find(|c| c.target == "crate::report")
1530 .unwrap();
1531 assert_eq!(report_coupling.volatility, Volatility::Low);
1532 }
1533
1534 #[test]
1535 fn test_volatility_with_type_targets() {
1536 let mut project = ProjectMetrics::new();
1538
1539 project.add_coupling(CouplingMetrics::new(
1541 "crate::main".to_string(),
1542 "crate::balance::BalanceScore".to_string(), IntegrationStrength::Functional,
1544 Distance::DifferentModule,
1545 Volatility::Low,
1546 ));
1547 project.add_coupling(CouplingMetrics::new(
1548 "crate::main".to_string(),
1549 "cargo-coupling::analyzer::analyze_file".to_string(), IntegrationStrength::Functional,
1551 Distance::DifferentModule,
1552 Volatility::Low,
1553 ));
1554
1555 project
1557 .file_changes
1558 .insert("src/balance.rs".to_string(), 15); project
1560 .file_changes
1561 .insert("src/analyzer.rs".to_string(), 7); project.update_volatility_from_git();
1565
1566 let balance_coupling = project
1568 .couplings
1569 .iter()
1570 .find(|c| c.target.contains("balance"))
1571 .unwrap();
1572 assert_eq!(
1573 balance_coupling.volatility,
1574 Volatility::High,
1575 "Expected High volatility for balance module (15 changes)"
1576 );
1577
1578 let analyzer_coupling = project
1579 .couplings
1580 .iter()
1581 .find(|c| c.target.contains("analyzer"))
1582 .unwrap();
1583 assert_eq!(
1584 analyzer_coupling.volatility,
1585 Volatility::Medium,
1586 "Expected Medium volatility for analyzer module (7 changes)"
1587 );
1588 }
1589
1590 #[test]
1591 fn test_volatility_extracted_module_targets() {
1592 let mut project = ProjectMetrics::new();
1595
1596 project.add_coupling(CouplingMetrics::new(
1598 "cargo-coupling::main".to_string(),
1599 "balance".to_string(), IntegrationStrength::Functional,
1601 Distance::DifferentModule,
1602 Volatility::Low,
1603 ));
1604 project.add_coupling(CouplingMetrics::new(
1605 "cargo-coupling::main".to_string(),
1606 "analyzer".to_string(), IntegrationStrength::Functional,
1608 Distance::DifferentModule,
1609 Volatility::Low,
1610 ));
1611 project.add_coupling(CouplingMetrics::new(
1612 "cargo-coupling::main".to_string(),
1613 "cli_output".to_string(), IntegrationStrength::Functional,
1615 Distance::DifferentModule,
1616 Volatility::Low,
1617 ));
1618
1619 project
1621 .file_changes
1622 .insert("src/balance.rs".to_string(), 15); project
1624 .file_changes
1625 .insert("src/analyzer.rs".to_string(), 7); project
1627 .file_changes
1628 .insert("src/cli_output.rs".to_string(), 3); project.update_volatility_from_git();
1632
1633 let balance = project
1635 .couplings
1636 .iter()
1637 .find(|c| c.target == "balance")
1638 .unwrap();
1639 assert_eq!(
1640 balance.volatility,
1641 Volatility::High,
1642 "balance should be High (15 changes)"
1643 );
1644
1645 let analyzer = project
1646 .couplings
1647 .iter()
1648 .find(|c| c.target == "analyzer")
1649 .unwrap();
1650 assert_eq!(
1651 analyzer.volatility,
1652 Volatility::Medium,
1653 "analyzer should be Medium (7 changes)"
1654 );
1655
1656 let cli_output = project
1657 .couplings
1658 .iter()
1659 .find(|c| c.target == "cli_output")
1660 .unwrap();
1661 assert_eq!(
1662 cli_output.volatility,
1663 Volatility::Medium,
1664 "cli_output should be Medium (3 changes)"
1665 );
1666 }
1667}