debtmap 0.16.4

Code complexity and technical debt analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Code organization analysis and anti-pattern detection.
//!
//! This module provides comprehensive analysis of code organization quality, including
//! detection of god objects, feature envy, magic values, and other architectural
//! anti-patterns. It also provides guidance for decomposing large modules into
//! well-defined responsibilities.
//!
//! # Anti-Patterns Detected
//!
//! - **God objects**: Types with too many responsibilities
//! - **Feature envy**: Methods that use another type's data more than their own
//! - **Magic values**: Hard-coded literals that should be named constants
//! - **Long parameter lists**: Functions with too many parameters
//! - **Primitive obsession**: Overuse of primitives instead of domain types
//! - **Data clumps**: Groups of parameters that always appear together
//!
//! # Refactoring Guidance
//!
//! The module provides split recommendations, naming suggestions, and complexity
//! impact predictions to guide refactoring decisions.

use crate::common::SourceLocation;
use syn;

pub mod anti_pattern_detector;
pub mod architecture_utils;
pub mod behavioral_decomposition;
pub mod codebase_type_analyzer;
pub mod confidence;
pub mod data_flow_analyzer;
pub use behavioral_decomposition::{
    apply_hybrid_clustering, apply_production_ready_clustering,
    build_method_call_adjacency_matrix_with_functions, cluster_methods_by_behavior,
    suggest_trait_extraction, BehaviorCategory, BehavioralCategorizer, FieldAccessStats,
    FieldAccessTracker, MethodCluster,
};
pub mod boilerplate_detector;
pub mod builder_pattern;
pub mod call_graph_cohesion;
pub mod class_ownership;
pub mod clustering;
pub mod cohesion_calculator;
pub mod cohesion_priority;
pub mod complexity_weighting;
pub mod cycle_detector;
pub mod dependency_analyzer;
pub mod domain_classifier;
pub mod domain_diversity;
pub mod domain_patterns;
pub mod file_classifier;
pub mod god_object;
pub mod god_object_metrics;
pub mod hidden_type_extractor;
pub mod integrated_analyzer;
pub mod language;
pub mod layering;
pub mod macro_recommendations;
pub mod module_function_classifier;
pub mod parallel_execution_pattern;
pub mod purity_analyzer;
pub mod registry_pattern;
pub mod split_validator;
pub mod struct_initialization;
pub mod struct_ownership;
pub mod struct_patterns;
pub mod trait_pattern_analyzer;
pub mod type_based_clustering;

// Re-export god object functionality from new modular structure
// Spec 262: Recommendation functions removed
pub use god_object::{
    // Scoring
    calculate_god_object_score,
    calculate_god_object_score_weighted,
    calculate_struct_ratio,
    classify_struct_domain,
    count_distinct_domains,
    // Classification
    determine_confidence,
    extract_domain_from_name,
    group_methods_by_responsibility,
    infer_responsibility_with_confidence,
    // Types
    ClassificationResult,
    DetectionType,
    EnhancedGodObjectAnalysis,
    FunctionVisibilityBreakdown,
    GodObjectAnalysis,
    GodObjectConfidence,
    // Detector
    GodObjectDetector,
    // Thresholds
    GodObjectThresholds,
    GodObjectType,
    InterfaceEstimate,
    MergeRecord,
    MetricInconsistency,
    ModuleSplit,
    Priority,
    PurityDistribution,
    RecommendationSeverity,
    SignalType,
    SplitAnalysisMethod,
    StageType,
    StructMetrics,
    StructWithMethods,
};

pub use cohesion_calculator::{calculate_file_cohesion, FileCohesionResult};
pub use domain_classifier::classify_struct_domain_enhanced;
pub use domain_diversity::{
    CrossDomainSeverity, DiversityScore, DomainDiversityMetrics, StructDomainClassification,
};
pub use split_validator::{
    validate_and_refine_splits, validate_and_refine_splits_with_config, SplitSizeConfig,
};
pub use struct_ownership::StructOwnershipAnalyzer;

pub use god_object_metrics::{
    FileMetricHistory, FileTrend, GodObjectMetrics, GodObjectSnapshot, MetricsSummary,
    TrendDirection,
};

pub use complexity_weighting::{
    aggregate_weighted_complexity, calculate_avg_complexity, calculate_complexity_penalty,
    calculate_complexity_weight, ComplexityWeight, ComplexityWeightedAnalysis,
    FunctionComplexityInfo,
};

pub use confidence::{
    emit_classification_metrics, ClassificationMetrics, MINIMUM_CONFIDENCE, MIN_METHODS_FOR_SPLIT,
    MODULE_SPLIT_CONFIDENCE, UTILITIES_THRESHOLD,
};

pub use purity_analyzer::{PurityAnalyzer, PurityIndicators, PurityLevel};

pub use builder_pattern::{
    adjust_builder_score, BuilderPattern, BuilderPatternDetector, MethodInfo, MethodReturnType,
};

pub use registry_pattern::{
    adjust_registry_score, RegistryPattern, RegistryPatternDetector, TraitImplInfo,
};

pub use struct_initialization::{
    FieldDependency, ReturnAnalysis, StructInitPattern, StructInitPatternDetector,
};

pub use parallel_execution_pattern::{
    adjust_parallel_score, ClosureInfo, ParallelLibrary, ParallelPattern, ParallelPatternDetector,
};

pub use boilerplate_detector::{
    BoilerplateAnalysis, BoilerplateDetectionConfig, BoilerplateDetector, BoilerplatePattern,
    DetectionSignal,
};

pub use trait_pattern_analyzer::{TraitPatternAnalyzer, TraitPatternMetrics};

pub use type_based_clustering::{
    MethodSignature, TypeAffinityAnalyzer, TypeCluster, TypeInfo, TypeSignatureAnalyzer,
};

pub use domain_patterns::{
    cluster_methods_by_domain, DomainPattern, DomainPatternDetector, DomainPatternMatch,
    PatternEvidence, DOMAIN_PATTERN_THRESHOLD, MIN_DOMAIN_CLUSTER_SIZE,
};

pub use hidden_type_extractor::{
    HiddenType, HiddenTypeConfig, HiddenTypeExtractor, MethodPurpose, ParameterClump, TupleReturn,
    TypeField, TypeMethod, Visibility,
};

pub use data_flow_analyzer::{
    DataFlowAnalyzer, PipelineStage, TransformationType, TypeFlowEdge, TypeFlowGraph,
};

pub use macro_recommendations::MacroRecommendationEngine;

pub mod module_recommendations;
pub use module_recommendations::{
    generate_decomposition_plan, is_generic_name, DecompositionLevel, DecompositionPlan,
    ModuleRecommendation,
};

pub mod semantic_naming;
pub use semantic_naming::{
    DomainTermExtractor, NameCandidate, NameUniquenessValidator, NamingStrategy, PatternRecognizer,
    SemanticNameGenerator, SpecificityScorer,
};

pub use anti_pattern_detector::{
    is_primitive, AntiPattern, AntiPatternConfig, AntiPatternDetector, AntiPatternSeverity,
    AntiPatternType, SplitQualityReport,
};

pub use integrated_analyzer::{
    AnalysisConfig, AnalysisError, AnalysisMetadata, AntiPatternReport, ConflictResolutionStrategy,
    EnabledAnalyzers, IntegratedAnalysisResult, IntegratedArchitectureAnalyzer,
};

pub use architecture_utils::{
    extract_base_type, extract_noun, is_domain_term, is_domain_type, is_likely_verb,
    is_primitive_type, most_common, to_pascal_case, to_snake_case, types_equivalent,
};

pub use codebase_type_analyzer::{
    ActionType, CodebaseAnalysisConfig, CodebaseRecommendation, CodebaseSnapshot,
    CodebaseTypeAnalysis, CodebaseTypeAnalyzer, ComplexityLevel, EffortEstimate, FileSnapshot,
    OrphanedFunctionGroup, RefactoringAction, RiskLevel, ScatteredType, ScatteringSeverity,
    UtilitiesModule,
};

pub use file_classifier::{
    calculate_reduction_target, classify_file, get_threshold, recommendation_level, ConfigType,
    FileSizeAnalysis, FileSizeThresholds, FileType, RecommendationLevel, ReductionTarget, TestType,
};

#[derive(Debug, Clone, PartialEq)]
pub enum OrganizationAntiPattern {
    GodObject {
        type_name: String,
        method_count: usize,
        field_count: usize,
        responsibility_count: usize,
        suggested_split: Vec<ResponsibilityGroup>,
        location: SourceLocation,
    },
    MagicValue {
        value_type: MagicValueType,
        value: String,
        occurrence_count: usize,
        suggested_constant_name: String,
        context: ValueContext,
        locations: Vec<SourceLocation>,
    },
    LongParameterList {
        function_name: String,
        parameter_count: usize,
        data_clumps: Vec<ParameterGroup>,
        suggested_refactoring: ParameterRefactoring,
        location: SourceLocation,
    },
    FeatureEnvy {
        method_name: String,
        envied_type: String,
        external_calls: usize,
        internal_calls: usize,
        suggested_move: bool,
        location: SourceLocation,
    },
    PrimitiveObsession {
        primitive_type: String,
        usage_context: PrimitiveUsageContext,
        occurrence_count: usize,
        suggested_domain_type: String,
        locations: Vec<SourceLocation>,
    },
    DataClump {
        parameter_group: ParameterGroup,
        occurrence_count: usize,
        suggested_struct_name: String,
        locations: Vec<SourceLocation>,
    },
    StructInitialization {
        function_name: String,
        struct_name: String,
        field_count: usize,
        cyclomatic_complexity: usize,
        field_based_complexity: f64,
        confidence: f64,
        recommendation: String,
        location: SourceLocation,
    },
}

impl OrganizationAntiPattern {
    pub fn primary_location(&self) -> &SourceLocation {
        match self {
            OrganizationAntiPattern::GodObject { location, .. } => location,
            OrganizationAntiPattern::MagicValue { locations, .. } => &locations[0],
            OrganizationAntiPattern::LongParameterList { location, .. } => location,
            OrganizationAntiPattern::FeatureEnvy { location, .. } => location,
            OrganizationAntiPattern::PrimitiveObsession { locations, .. } => &locations[0],
            OrganizationAntiPattern::DataClump { locations, .. } => &locations[0],
            OrganizationAntiPattern::StructInitialization { location, .. } => location,
        }
    }

    pub fn all_locations(&self) -> Vec<&SourceLocation> {
        match self {
            OrganizationAntiPattern::GodObject { location, .. } => vec![location],
            OrganizationAntiPattern::MagicValue { locations, .. } => locations.iter().collect(),
            OrganizationAntiPattern::LongParameterList { location, .. } => vec![location],
            OrganizationAntiPattern::FeatureEnvy { location, .. } => vec![location],
            OrganizationAntiPattern::PrimitiveObsession { locations, .. } => {
                locations.iter().collect()
            }
            OrganizationAntiPattern::DataClump { locations, .. } => locations.iter().collect(),
            OrganizationAntiPattern::StructInitialization { location, .. } => vec![location],
        }
    }

    pub fn pattern_type(&self) -> &str {
        match self {
            OrganizationAntiPattern::GodObject { .. } => "God Object",
            OrganizationAntiPattern::MagicValue { .. } => "Magic Value",
            OrganizationAntiPattern::LongParameterList { .. } => "Long Parameter List",
            OrganizationAntiPattern::FeatureEnvy { .. } => "Feature Envy",
            OrganizationAntiPattern::PrimitiveObsession { .. } => "Primitive Obsession",
            OrganizationAntiPattern::DataClump { .. } => "Data Clump",
            OrganizationAntiPattern::StructInitialization { .. } => "Struct Initialization",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum MagicValueType {
    NumericLiteral,
    StringLiteral,
    ArraySize,
    ConfigurationValue,
    BusinessRule,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ValueContext {
    Comparison,
    ArrayIndexing,
    Calculation,
    Timeout,
    BufferSize,
    BusinessLogic,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ParameterRefactoring {
    ExtractStruct,
    UseBuilder,
    SplitFunction,
    UseConfiguration,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PrimitiveUsageContext {
    Identifier,
    Measurement,
    Status,
    Category,
    BusinessRule,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ResponsibilityGroup {
    pub name: String,
    pub methods: Vec<String>,
    pub fields: Vec<String>,
    pub responsibility: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ParameterGroup {
    pub parameters: Vec<Parameter>,
    pub group_name: String,
    pub semantic_relationship: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Parameter {
    pub name: String,
    pub type_name: String,
    pub position: usize,
}

pub trait OrganizationDetector {
    fn detect_anti_patterns(&self, file: &syn::File) -> Vec<OrganizationAntiPattern>;
    fn detector_name(&self) -> &'static str;
    fn estimate_maintainability_impact(
        &self,
        pattern: &OrganizationAntiPattern,
    ) -> MaintainabilityImpact;
}

#[derive(Debug, Clone, PartialEq)]
pub enum MaintainabilityImpact {
    Critical,
    High,
    Medium,
    Low,
}

mod feature_envy_detector;
mod magic_value_detector;
mod parameter_analyzer;
mod primitive_obsession_detector;
mod struct_init_detector;

pub use feature_envy_detector::FeatureEnvyDetector;
// GodObjectDetector is already exported above from god_object module
pub use magic_value_detector::MagicValueDetector;
pub use parameter_analyzer::ParameterAnalyzer;
pub use primitive_obsession_detector::PrimitiveObsessionDetector;
pub use struct_init_detector::StructInitOrganizationDetector;

// Multi-language support exports
pub use class_ownership::{ClassOwnership, ClassOwnershipAnalyzer};
pub use language::Language;
pub use layering::{
    calculate_layering_penalty, compute_layering_impact, compute_layering_score, path_to_module,
    LayeringAnalysis, LayeringImpact, ModuleDependency,
};