howmany 3.0.0

A blazingly fast, intelligent code analysis tool with parallel processing, caching, and beautiful visualizations
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use super::analyzer::{CodeAnalyzer, FileAnalysis};
use super::quality::QualityCalculator;
use super::types::{
    ComplexityDistribution, ComplexityStats, ExtensionComplexity, FunctionInfo,
    StructureDistribution, StructureInfo, StructureType,
};
use crate::core::types::{CodeStats, FileStats};
use crate::utils::errors::Result;
use rayon::prelude::*;
use std::collections::BTreeMap;
use std::path::Path;

/// Main complexity statistics calculator
pub struct ComplexityCalculator {
    analyzer: CodeAnalyzer,
    quality_calculator: QualityCalculator,
}

impl ComplexityCalculator {
    pub fn new() -> Self {
        Self {
            analyzer: CodeAnalyzer::new(),
            quality_calculator: QualityCalculator::new(),
        }
    }

    /// Calculate complexity statistics for a single file
    pub fn calculate_complexity_stats(
        &self,
        file_stats: &FileStats,
        file_path: &str,
    ) -> Result<ComplexityStats> {
        // A file that cannot be re-read contributes no structures rather than
        // failing the statistics for the whole run: its line counts are already
        // known, and the file may simply have been moved since it was counted.
        let FileAnalysis {
            functions,
            structures,
        } = self.analyzer.analyze_file(file_path).unwrap_or_default();

        let function_count = functions.len();

        // Calculate cyclomatic complexity
        let total_cyclomatic = functions
            .iter()
            .map(|f| f.cyclomatic_complexity as f64)
            .sum::<f64>();
        let cyclomatic_complexity = if function_count > 0 {
            total_cyclomatic / function_count as f64
        } else {
            0.0
        };

        // Calculate cognitive complexity
        let total_cognitive = functions
            .iter()
            .map(|f| f.cognitive_complexity as f64)
            .sum::<f64>();
        let cognitive_complexity = if function_count > 0 {
            total_cognitive / function_count as f64
        } else {
            0.0
        };

        // Calculate maintainability index
        let maintainability_index = self.calculate_maintainability_index(&functions, file_stats);

        let average_function_length = if function_count > 0 {
            functions.iter().map(|f| f.line_count as f64).sum::<f64>() / function_count as f64
        } else {
            0.0
        };

        let max_function_length = functions.iter().map(|f| f.line_count).max().unwrap_or(0);
        let min_function_length = functions.iter().map(|f| f.line_count).min().unwrap_or(0);
        let max_nesting_depth = functions.iter().map(|f| f.nesting_depth).max().unwrap_or(0);
        let average_nesting_depth = if function_count > 0 {
            functions
                .iter()
                .map(|f| f.nesting_depth as f64)
                .sum::<f64>()
                / function_count as f64
        } else {
            0.0
        };

        let average_parameters_per_function = if function_count > 0 {
            functions
                .iter()
                .map(|f| f.parameter_count as f64)
                .sum::<f64>()
                / function_count as f64
        } else {
            0.0
        };

        let max_parameters_per_function = functions
            .iter()
            .map(|f| f.parameter_count)
            .max()
            .unwrap_or(0);

        let complexity_distribution = self.calculate_complexity_distribution(&functions);
        let structure_distribution = self.calculate_structure_distribution(&structures);

        let class_count = structures
            .iter()
            .filter(|s| s.structure_type == StructureType::Class)
            .count();
        let interface_count = structures
            .iter()
            .filter(|s| s.structure_type == StructureType::Interface)
            .count();
        let trait_count = structures
            .iter()
            .filter(|s| s.structure_type == StructureType::Trait)
            .count();
        let enum_count = structures
            .iter()
            .filter(|s| s.structure_type == StructureType::Enum)
            .count();
        let struct_count = structures
            .iter()
            .filter(|s| s.structure_type == StructureType::Struct)
            .count();
        let module_count = structures
            .iter()
            .filter(|s| {
                s.structure_type == StructureType::Module
                    || s.structure_type == StructureType::Namespace
            })
            .count();
        let total_structures = structures.len();

        let methods_per_class = if class_count > 0 {
            structures
                .iter()
                .filter(|s| s.structure_type == StructureType::Class)
                .map(|s| s.methods.len())
                .sum::<usize>() as f64
                / class_count as f64
        } else {
            0.0
        };

        let function_complexity_details = self
            .quality_calculator
            .create_function_complexity_details(&functions, file_path);
        let quality_metrics =
            self.quality_calculator
                .calculate_quality_metrics(&functions, file_stats, &structures);

        Ok(ComplexityStats {
            function_count,
            class_count,
            interface_count,
            trait_count,
            enum_count,
            struct_count,
            module_count,
            total_structures,
            cyclomatic_complexity,
            cognitive_complexity,
            maintainability_index,
            average_function_length,
            max_function_length,
            min_function_length,
            max_nesting_depth,
            average_nesting_depth,
            methods_per_class,
            average_parameters_per_function,
            max_parameters_per_function,
            complexity_by_extension: BTreeMap::new(),
            complexity_distribution,
            structure_distribution,
            function_complexity_details,
            quality_metrics,
        })
    }

    /// Calculate complexity statistics for a project
    pub fn calculate_project_complexity_stats(
        &self,
        code_stats: &CodeStats,
        individual_files: &[(String, FileStats)],
    ) -> Result<ComplexityStats> {
        let mut total_classes = 0;
        let mut total_interfaces = 0;
        let mut total_traits = 0;
        let mut total_enums = 0;
        let mut total_structs = 0;
        let mut total_modules = 0;
        let mut total_complexity = 0.0;
        let mut total_function_lines = 0;
        let mut max_function_length = 0;
        let mut min_function_length = usize::MAX;
        let mut max_nesting_depth = 0;
        let mut total_nesting_depth = 0.0;
        let mut complexity_by_extension = BTreeMap::new();
        let mut all_functions = Vec::new();
        let mut all_structures = Vec::new();

        // Analyze every file exactly once, in parallel.
        //
        // Reading and parsing the sources dominates project-level analysis, so
        // this is where the wall-clock time goes. `collect` preserves input
        // order, which keeps the per-extension running averages below -- and
        // therefore the report -- identical on every run.
        let analyses: Vec<(&String, FileAnalysis)> = individual_files
            .par_iter()
            .filter_map(|(file_path, _)| {
                self.analyzer
                    .analyze_file(file_path)
                    .ok()
                    .map(|analysis| (file_path, analysis))
            })
            .collect();

        for (file_path, analysis) in analyses {
            let FileAnalysis {
                functions,
                structures,
            } = analysis;

            {
                total_classes += structures
                    .iter()
                    .filter(|s| s.structure_type == StructureType::Class)
                    .count();
                total_interfaces += structures
                    .iter()
                    .filter(|s| s.structure_type == StructureType::Interface)
                    .count();
                total_traits += structures
                    .iter()
                    .filter(|s| s.structure_type == StructureType::Trait)
                    .count();
                total_enums += structures
                    .iter()
                    .filter(|s| s.structure_type == StructureType::Enum)
                    .count();
                total_structs += structures
                    .iter()
                    .filter(|s| s.structure_type == StructureType::Struct)
                    .count();
                total_modules += structures
                    .iter()
                    .filter(|s| {
                        s.structure_type == StructureType::Module
                            || s.structure_type == StructureType::Namespace
                    })
                    .count();
            }

            {
                let extension = Path::new(file_path)
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or("unknown")
                    .to_lowercase();

                let function_count = functions.len();
                if function_count > 0 {
                    let ext_complexity = functions
                        .iter()
                        .map(|f| f.cyclomatic_complexity as f64)
                        .sum::<f64>()
                        / function_count as f64;
                    let ext_avg_length = functions.iter().map(|f| f.line_count as f64).sum::<f64>()
                        / function_count as f64;
                    let ext_max_nesting =
                        functions.iter().map(|f| f.nesting_depth).max().unwrap_or(0);
                    let ext_avg_nesting = functions
                        .iter()
                        .map(|f| f.nesting_depth as f64)
                        .sum::<f64>()
                        / function_count as f64;

                    let entry =
                        complexity_by_extension
                            .entry(extension)
                            .or_insert(ExtensionComplexity {
                                function_count: 0,
                                class_count: 0,
                                interface_count: 0,
                                trait_count: 0,
                                enum_count: 0,
                                struct_count: 0,
                                total_structures: 0,
                                cyclomatic_complexity: 0.0,
                                cognitive_complexity: 0.0,
                                maintainability_index: 0.0,
                                average_function_length: 0.0,
                                max_nesting_depth: 0,
                                average_nesting_depth: 0.0,
                                methods_per_class: 0.0,
                                average_parameters_per_function: 0.0,
                                quality_score: 0.0,
                            });

                    entry.function_count += function_count;
                    entry.cyclomatic_complexity = (entry.cyclomatic_complexity
                        * (entry.function_count - function_count) as f64
                        + ext_complexity * function_count as f64)
                        / entry.function_count as f64;
                    entry.average_function_length = (entry.average_function_length
                        * (entry.function_count - function_count) as f64
                        + ext_avg_length * function_count as f64)
                        / entry.function_count as f64;
                    entry.max_nesting_depth = entry.max_nesting_depth.max(ext_max_nesting);
                    entry.average_nesting_depth = (entry.average_nesting_depth
                        * (entry.function_count - function_count) as f64
                        + ext_avg_nesting * function_count as f64)
                        / entry.function_count as f64;
                }
            }

            // Exactly once per file. The previous implementation extended
            // `all_functions` from two separate analysis passes, so every
            // function was counted twice and `function_count`,
            // `average_function_length` and the complexity distribution were all
            // reported at double their true size.
            all_functions.extend(functions);
            all_structures.extend(structures);
        }

        // Calculate aggregate statistics
        let total_functions = all_functions.len();
        if total_functions > 0 {
            total_complexity = all_functions
                .iter()
                .map(|f| f.cyclomatic_complexity as f64)
                .sum::<f64>();
            total_function_lines = all_functions.iter().map(|f| f.line_count).sum();
            max_function_length = all_functions
                .iter()
                .map(|f| f.line_count)
                .max()
                .unwrap_or(0);
            min_function_length = all_functions
                .iter()
                .map(|f| f.line_count)
                .min()
                .unwrap_or(0);
            max_nesting_depth = all_functions
                .iter()
                .map(|f| f.nesting_depth)
                .max()
                .unwrap_or(0);
            total_nesting_depth = all_functions
                .iter()
                .map(|f| f.nesting_depth as f64)
                .sum::<f64>();
        }

        // Calculate cognitive complexity and other metrics
        let total_cognitive_complexity = all_functions
            .iter()
            .map(|f| f.cognitive_complexity as f64)
            .sum::<f64>();
        let cognitive_complexity = if total_functions > 0 {
            total_cognitive_complexity / total_functions as f64
        } else {
            0.0
        };

        let total_parameters = all_functions
            .iter()
            .map(|f| f.parameter_count)
            .sum::<usize>();
        let average_parameters_per_function = if total_functions > 0 {
            total_parameters as f64 / total_functions as f64
        } else {
            0.0
        };
        let max_parameters_per_function = all_functions
            .iter()
            .map(|f| f.parameter_count)
            .max()
            .unwrap_or(0);

        // Calculate maintainability index for the project
        let maintainability_index = if total_functions > 0 {
            let avg_complexity = total_complexity / total_functions as f64;
            let avg_length = total_function_lines as f64 / total_functions as f64;
            let avg_cognitive = cognitive_complexity;
            let avg_params = average_parameters_per_function;

            // Simplified maintainability calculation
            let length_score = (50.0 - avg_length).max(0.0);
            let complexity_score = (30.0 - avg_complexity * 2.0).max(0.0);
            let cognitive_score = (30.0 - avg_cognitive * 2.0).max(0.0);
            let param_score = (20.0 - avg_params * 3.0).max(0.0);

            let base_score =
                (length_score + complexity_score + cognitive_score + param_score).clamp(0.0, 100.0);

            // Apply file length penalty based on project file size distribution
            let large_files_count = individual_files
                .iter()
                .filter(|(_, stats)| stats.total_lines > 500)
                .count();
            let very_large_files_count = individual_files
                .iter()
                .filter(|(_, stats)| stats.total_lines > 1000)
                .count();
            let extremely_large_files_count = individual_files
                .iter()
                .filter(|(_, stats)| stats.total_lines > 2000)
                .count();

            let total_files = individual_files.len().max(1);
            let large_file_ratio = large_files_count as f64 / total_files as f64;
            let very_large_file_ratio = very_large_files_count as f64 / total_files as f64;
            let extremely_large_file_ratio =
                extremely_large_files_count as f64 / total_files as f64;

            // Progressive penalty based on proportion of large files
            let file_size_penalty = (large_file_ratio * 10.0)
                + (very_large_file_ratio * 15.0)
                + (extremely_large_file_ratio * 20.0);

            (base_score - file_size_penalty.min(35.0)).max(0.0)
        } else {
            100.0
        };

        let complexity_distribution = self.calculate_complexity_distribution(&all_functions);
        let structure_distribution = self.calculate_structure_distribution(&all_structures);

        let total_structures = all_structures.len();
        let methods_per_class = if total_classes > 0 {
            all_structures
                .iter()
                .filter(|s| s.structure_type == StructureType::Class)
                .map(|s| s.methods.len())
                .sum::<usize>() as f64
                / total_classes as f64
        } else {
            0.0
        };

        // Calculate quality metrics for the project
        let quality_metrics = self.quality_calculator.calculate_project_quality_metrics(
            &all_functions,
            code_stats,
            &all_structures,
        );

        Ok(ComplexityStats {
            function_count: total_functions,
            class_count: total_classes,
            interface_count: total_interfaces,
            trait_count: total_traits,
            enum_count: total_enums,
            struct_count: total_structs,
            module_count: total_modules,
            total_structures,
            cyclomatic_complexity: if total_functions > 0 {
                total_complexity / total_functions as f64
            } else {
                0.0
            },
            cognitive_complexity,
            maintainability_index,
            average_function_length: if total_functions > 0 {
                total_function_lines as f64 / total_functions as f64
            } else {
                0.0
            },
            max_function_length,
            min_function_length: if min_function_length == usize::MAX {
                0
            } else {
                min_function_length
            },
            max_nesting_depth,
            average_nesting_depth: if total_functions > 0 {
                total_nesting_depth / total_functions as f64
            } else {
                0.0
            },
            methods_per_class,
            average_parameters_per_function,
            max_parameters_per_function,
            complexity_by_extension,
            complexity_distribution,
            structure_distribution,
            function_complexity_details: Vec::new(), // Will be populated by calling code if needed
            quality_metrics,
        })
    }

    /// Calculate complexity distribution
    fn calculate_complexity_distribution(
        &self,
        functions: &[FunctionInfo],
    ) -> ComplexityDistribution {
        let mut distribution = ComplexityDistribution {
            very_low_complexity: 0,
            low_complexity: 0,
            medium_complexity: 0,
            high_complexity: 0,
            very_high_complexity: 0,
        };

        for func in functions {
            match func.cyclomatic_complexity {
                1..=5 => distribution.very_low_complexity += 1,
                6..=10 => distribution.low_complexity += 1,
                11..=20 => distribution.medium_complexity += 1,
                21..=50 => distribution.high_complexity += 1,
                _ => distribution.very_high_complexity += 1,
            }
        }

        distribution
    }

    /// Calculate structure distribution
    fn calculate_structure_distribution(
        &self,
        structures: &[StructureInfo],
    ) -> StructureDistribution {
        StructureDistribution {
            classes: structures
                .iter()
                .filter(|s| s.structure_type == StructureType::Class)
                .count(),
            interfaces: structures
                .iter()
                .filter(|s| s.structure_type == StructureType::Interface)
                .count(),
            traits: structures
                .iter()
                .filter(|s| s.structure_type == StructureType::Trait)
                .count(),
            enums: structures
                .iter()
                .filter(|s| s.structure_type == StructureType::Enum)
                .count(),
            structs: structures
                .iter()
                .filter(|s| s.structure_type == StructureType::Struct)
                .count(),
            modules: structures
                .iter()
                .filter(|s| {
                    s.structure_type == StructureType::Module
                        || s.structure_type == StructureType::Namespace
                })
                .count(),
        }
    }

    /// Calculate maintainability index (simplified version)
    fn calculate_maintainability_index(
        &self,
        functions: &[FunctionInfo],
        file_stats: &FileStats,
    ) -> f64 {
        if functions.is_empty() {
            return 100.0; // Perfect score for empty files
        }

        let mut total_score = 0.0;

        for func in functions {
            // Simplified maintainability calculation based on:
            // - Function length (shorter is better)
            // - Cyclomatic complexity (lower is better)
            // - Cognitive complexity (lower is better)
            // - Parameter count (fewer is better)

            let length_score = (50.0 - func.line_count as f64).max(0.0);
            let cyclomatic_score = (30.0 - func.cyclomatic_complexity as f64 * 2.0).max(0.0);
            let cognitive_score = (30.0 - func.cognitive_complexity as f64 * 2.0).max(0.0);
            let param_score = (20.0 - func.parameter_count as f64 * 3.0).max(0.0);

            total_score += length_score + cyclomatic_score + cognitive_score + param_score;
        }

        let base_score = (total_score / functions.len() as f64).clamp(0.0, 100.0);

        // Apply file length penalty - files over 500 lines are considered less maintainable
        let file_length_penalty = if file_stats.total_lines > 500 {
            // Progressive penalty: 0.5 points per 100 lines over 500, capped at 25 points
            let excess_lines = file_stats.total_lines - 500;
            ((excess_lines as f64 / 100.0) * 0.5).min(25.0)
        } else {
            0.0
        };

        (base_score - file_length_penalty).max(0.0)
    }

    /// Get complexity level description
    pub fn get_complexity_level(&self, complexity: f64) -> String {
        match complexity as usize {
            1..=5 => "Very Low".to_string(),
            6..=10 => "Low".to_string(),
            11..=20 => "Medium".to_string(),
            21..=50 => "High".to_string(),
            _ => "Very High".to_string(),
        }
    }

    /// Get complexity level CSS class
    pub fn get_complexity_class(&self, complexity: f64) -> String {
        match complexity as usize {
            1..=5 => "complexity-very-low".to_string(),
            6..=10 => "complexity-low".to_string(),
            11..=20 => "complexity-medium".to_string(),
            21..=50 => "complexity-high".to_string(),
            _ => "complexity-very-high".to_string(),
        }
    }
}

impl Default for ComplexityCalculator {
    fn default() -> Self {
        Self::new()
    }
}