1use fallow_output::{DirectCallerEvidence, DirectCallerSymbolEvidence, FileHealthScore};
2
3use super::coverage_gaps::compute_coverage_gaps;
4pub(super) use super::coverage_gaps::{CoverageGapData, build_coverage_summary};
5
6pub struct FileScoreOutput {
8 pub scores: Vec<FileHealthScore>,
9 pub coverage: CoverageGapData,
11 pub circular_files: rustc_hash::FxHashSet<std::path::PathBuf>,
13 pub top_complex_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
15 pub entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
17 pub value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
19 pub unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
21 pub cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>>,
23 pub direct_callers: rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>>,
25 pub analysis_counts: crate::vital_signs::AnalysisCounts,
27 pub prop_drilling_chains: Vec<fallow_types::output_dead_code::PropDrillingChainFinding>,
32 pub render_fan_in: Option<fallow_types::results::RenderFanInMetric>,
38 pub analysis_snapshot: AnalysisCountsSnapshot,
42 pub istanbul_matched: usize,
44 pub istanbul_total: usize,
45 pub per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
49 pub template_inherit_provenance: rustc_hash::FxHashMap<std::path::PathBuf, std::path::PathBuf>,
56}
57
58struct FileScoreOutputParts<'a> {
59 graph: &'a fallow_graph::graph::ModuleGraph,
60 file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
61 results: &'a crate::results::AnalysisResults,
62 scores: Vec<FileHealthScore>,
63 coverage: CoverageGapData,
64 circular_files: rustc_hash::FxHashSet<std::path::PathBuf>,
65 top_complex_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
66 entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
67 value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
68 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
69 cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>>,
70 direct_callers: rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>>,
71 istanbul_matched: usize,
72 istanbul_total: usize,
73 per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
74 template_inherit: rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
75}
76
77#[derive(Clone, Default)]
83pub struct AnalysisCountsSnapshot {
84 pub unused_file_paths: Vec<std::path::PathBuf>,
86 pub unused_export_paths: Vec<std::path::PathBuf>,
89 pub unused_dep_package_paths: Vec<std::path::PathBuf>,
93 pub circular_dep_groups: Vec<Vec<std::path::PathBuf>>,
96 pub module_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
99}
100
101impl AnalysisCountsSnapshot {
102 pub fn counts_for(
118 &self,
119 subset: &crate::health::SubsetFilter<'_>,
120 defaults: &crate::vital_signs::AnalysisCounts,
121 ) -> crate::vital_signs::AnalysisCounts {
122 if subset.is_full() {
123 return *defaults;
124 }
125 let dead_files = self
126 .unused_file_paths
127 .iter()
128 .filter(|p| subset.matches(p))
129 .count();
130 let dead_exports = self
131 .unused_export_paths
132 .iter()
133 .filter(|p| subset.matches(p))
134 .count();
135 let unused_deps = self
136 .unused_dep_package_paths
137 .iter()
138 .filter(|dep_path| dep_in_subset(subset, dep_path))
139 .count();
140 let circular_deps = self
141 .circular_dep_groups
142 .iter()
143 .filter(|cycle| cycle.iter().any(|p| subset.matches(p)))
144 .count();
145 let total_exports = self
146 .module_export_counts
147 .iter()
148 .filter(|(p, _)| subset.matches(p))
149 .map(|(_, n)| *n)
150 .sum();
151 crate::vital_signs::AnalysisCounts {
152 total_exports,
153 dead_files,
154 dead_exports,
155 unused_deps,
156 circular_deps,
157 total_deps: defaults.total_deps,
158 }
159 }
160}
161
162fn dep_in_subset(subset: &crate::health::SubsetFilter<'_>, dep_path: &std::path::Path) -> bool {
169 match subset {
170 crate::health::SubsetFilter::Full => true,
171 crate::health::SubsetFilter::Paths(set) => {
172 let Some(workspace_root) = dep_path.parent() else {
173 return false;
174 };
175 set.iter().any(|p| p.starts_with(workspace_root))
176 }
177 }
178}
179
180#[expect(
184 clippy::cast_possible_truncation,
185 reason = "line count is bounded by source file size"
186)]
187pub(super) fn aggregate_complexity(module: &crate::source::ModuleInfo) -> (u32, u32, usize, u32) {
188 let cyc: u32 = module
189 .complexity
190 .iter()
191 .map(|f| u32::from(f.cyclomatic))
192 .sum();
193 let cog: u32 = module
194 .complexity
195 .iter()
196 .map(|f| u32::from(f.cognitive))
197 .sum();
198 let funcs = module.complexity.len();
199 let lines = module.line_offsets.len() as u32;
200 (cyc, cog, funcs, lines)
201}
202
203pub(super) fn compute_dead_code_ratio(
211 path: &std::path::Path,
212 exports: &[fallow_graph::graph::ExportSymbol],
213 unused_files: &rustc_hash::FxHashSet<&std::path::Path>,
214 unused_exports_by_path: &rustc_hash::FxHashMap<&std::path::Path, usize>,
215) -> f64 {
216 if unused_files.contains(path) {
217 return 1.0;
218 }
219 let value_exports = exports.iter().filter(|e| !e.is_type_only).count();
220 if value_exports == 0 {
221 return 0.0;
222 }
223 let unused = unused_exports_by_path.get(path).copied().unwrap_or(0);
224 (unused as f64 / value_exports as f64).min(1.0)
225}
226
227pub(super) fn compute_complexity_density(total_cyclomatic: u32, lines: u32) -> f64 {
231 if lines > 0 {
232 f64::from(total_cyclomatic) / f64::from(lines)
233 } else {
234 0.0
235 }
236}
237
238pub(super) const CRAP_THRESHOLD: f64 = 30.0;
241
242#[cfg(test)]
250#[expect(
251 clippy::suboptimal_flops,
252 reason = "cc * cc + cc matches the CRAP formula specification"
253)]
254fn compute_crap_scores_binary(
255 complexity: &[fallow_types::extract::FunctionComplexity],
256 is_test_reachable: bool,
257) -> (f64, usize) {
258 if complexity.is_empty() {
259 return (0.0, 0);
260 }
261 let mut max = 0.0_f64;
262 let mut above = 0usize;
263 for f in complexity {
264 let cc = f64::from(f.cyclomatic);
265 let crap = if is_test_reachable { cc } else { cc * cc + cc };
266 max = max.max(crap);
267 if crap >= CRAP_THRESHOLD {
268 above += 1;
269 }
270 }
271 ((max * 10.0).round() / 10.0, above)
272}
273
274#[derive(Debug, Clone, Copy)]
276pub struct PerFunctionCrap {
277 pub line: u32,
279 pub col: u32,
285 pub crap: f64,
287 pub coverage_pct: Option<f64>,
290 pub coverage_tier: fallow_output::CoverageTier,
294 pub coverage_source: fallow_output::CoverageSource,
301}
302
303pub(super) struct IstanbulCrapResult {
305 pub max_crap: f64,
306 pub above_threshold: usize,
307 pub matched: usize,
309 pub total: usize,
311 pub per_function: Vec<PerFunctionCrap>,
313}
314
315fn compute_crap_scores_istanbul(
326 complexity: &[fallow_types::extract::FunctionComplexity],
327 file_coverage: Option<&IstanbulFileCoverage>,
328 is_test_reachable: bool,
329) -> IstanbulCrapResult {
330 if complexity.is_empty() {
331 return IstanbulCrapResult {
332 max_crap: 0.0,
333 above_threshold: 0,
334 matched: 0,
335 total: 0,
336 per_function: Vec::new(),
337 };
338 }
339 let mut max = 0.0_f64;
340 let mut above = 0usize;
341 let mut matched = 0usize;
342 let mut per_function = Vec::with_capacity(complexity.len());
343 for f in complexity {
344 let (crap, coverage_pct, tier, source) =
345 crap_for_function(f, file_coverage, is_test_reachable, &mut matched);
346 let crap_rounded = (crap * 10.0).round() / 10.0;
347 max = max.max(crap);
348 if crap >= CRAP_THRESHOLD {
349 above += 1;
350 }
351 per_function.push(PerFunctionCrap {
352 line: f.line,
353 col: f.col,
354 crap: crap_rounded,
355 coverage_pct,
356 coverage_tier: tier,
357 coverage_source: source,
358 });
359 }
360 IstanbulCrapResult {
361 max_crap: (max * 10.0).round() / 10.0,
362 above_threshold: above,
363 matched,
364 total: complexity.len(),
365 per_function,
366 }
367}
368
369#[expect(
373 clippy::suboptimal_flops,
374 reason = "cc * cc + cc matches the CRAP formula specification"
375)]
376fn crap_for_function(
377 f: &fallow_types::extract::FunctionComplexity,
378 file_coverage: Option<&IstanbulFileCoverage>,
379 is_test_reachable: bool,
380 matched: &mut usize,
381) -> (
382 f64,
383 Option<f64>,
384 fallow_output::CoverageTier,
385 fallow_output::CoverageSource,
386) {
387 let cc = f64::from(f.cyclomatic);
388 let lookup = file_coverage.and_then(|fc| fc.lookup(f.name.as_str(), f.line, f.col));
389 if let Some(cov_pct) = lookup {
390 *matched += 1;
391 return (
392 crap_formula(cc, cov_pct),
393 Some(cov_pct),
394 fallow_output::CoverageTier::from_pct(cov_pct),
395 fallow_output::CoverageSource::Istanbul,
396 );
397 }
398 if is_test_reachable {
399 return (
400 cc,
401 None,
402 fallow_output::CoverageTier::from_pct(INDIRECT_TEST_COVERAGE_ESTIMATE),
403 fallow_output::CoverageSource::Estimated,
404 );
405 }
406 (
407 cc * cc + cc,
408 None,
409 fallow_output::CoverageTier::None,
410 fallow_output::CoverageSource::Estimated,
411 )
412}
413
414const DIRECT_TEST_COVERAGE_ESTIMATE: f64 = 85.0;
417
418const INDIRECT_TEST_COVERAGE_ESTIMATE: f64 = 40.0;
422const MAX_DIRECT_CALLER_EVIDENCE: usize = 5;
423
424pub(super) struct EstimatedCrapResult {
435 pub max_crap: f64,
436 pub above_threshold: usize,
437 pub per_function: Vec<PerFunctionCrap>,
438}
439
440fn compute_crap_scores_estimated(
441 complexity: &[fallow_types::extract::FunctionComplexity],
442 test_referenced_exports: &rustc_hash::FxHashSet<String>,
443 is_test_reachable: bool,
444 coverage_source: fallow_output::CoverageSource,
445) -> EstimatedCrapResult {
446 if complexity.is_empty() {
447 return EstimatedCrapResult {
448 max_crap: 0.0,
449 above_threshold: 0,
450 per_function: Vec::new(),
451 };
452 }
453 let mut max = 0.0_f64;
454 let mut above = 0usize;
455 let mut per_function = Vec::with_capacity(complexity.len());
456 for f in complexity {
457 let cc = f64::from(f.cyclomatic);
458 let estimated_coverage = if test_referenced_exports.contains(f.name.as_str()) {
459 DIRECT_TEST_COVERAGE_ESTIMATE
460 } else if is_test_reachable {
461 INDIRECT_TEST_COVERAGE_ESTIMATE
462 } else {
463 0.0
464 };
465 let crap = crap_formula(cc, estimated_coverage);
466 let crap_rounded = (crap * 10.0).round() / 10.0;
467 max = max.max(crap);
468 if crap >= CRAP_THRESHOLD {
469 above += 1;
470 }
471 per_function.push(PerFunctionCrap {
472 line: f.line,
473 col: f.col,
474 crap: crap_rounded,
475 coverage_pct: None,
476 coverage_tier: fallow_output::CoverageTier::from_pct(estimated_coverage),
477 coverage_source,
478 });
479 }
480 EstimatedCrapResult {
481 max_crap: (max * 10.0).round() / 10.0,
482 above_threshold: above,
483 per_function,
484 }
485}
486
487#[derive(Debug, Clone)]
501pub(super) struct TemplateInheritContext {
502 pub is_test_reachable: bool,
503 pub test_referenced_exports: rustc_hash::FxHashSet<String>,
504 pub provenance_owner: std::path::PathBuf,
509}
510
511fn build_template_inherit_contexts(
533 graph: &fallow_graph::graph::ModuleGraph,
534 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
535 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
536) -> rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext> {
537 let mut out = rustc_hash::FxHashMap::default();
538 for node in &graph.modules {
539 if let Some(context) =
540 template_inherit_context_for_node(node, graph, module_by_id, file_paths)
541 {
542 out.insert(node.file_id, context);
543 }
544 }
545 out
546}
547
548fn template_inherit_context_for_node(
549 node: &fallow_graph::graph::ModuleNode,
550 graph: &fallow_graph::graph::ModuleGraph,
551 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
552 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
553) -> Option<TemplateInheritContext> {
554 if !is_template_inherit_candidate(node, module_by_id, file_paths) {
555 return None;
556 }
557 let importers = graph.reverse_deps.get(node.file_id.0 as usize)?;
558 template_inherit_context_from_importers(importers, graph, module_by_id, file_paths)
559}
560
561fn is_template_inherit_candidate(
562 node: &fallow_graph::graph::ModuleNode,
563 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
564 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
565) -> bool {
566 let Some(path) = file_paths.get(&node.file_id) else {
567 return false;
568 };
569 if !path
570 .extension()
571 .and_then(|ext| ext.to_str())
572 .is_some_and(|ext| ext.eq_ignore_ascii_case("html"))
573 {
574 return false;
575 }
576 module_by_id.get(&node.file_id).is_some_and(|module| {
577 module
578 .complexity
579 .iter()
580 .any(|finding| finding.name.as_str() == "<template>")
581 })
582}
583
584fn template_inherit_context_from_importers(
585 importers: &[crate::discover::FileId],
586 graph: &fallow_graph::graph::ModuleGraph,
587 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
588 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
589) -> Option<TemplateInheritContext> {
590 let mut any_reachable = false;
591 let mut combined_refs = rustc_hash::FxHashSet::default();
592 let mut provenance: Option<std::path::PathBuf> = None;
593 let mut first_owner: Option<std::path::PathBuf> = None;
594
595 for &importer_id in importers {
596 let Some((owner_node, owner_path)) =
597 template_owner(importer_id, graph, module_by_id, file_paths)
598 else {
599 continue;
600 };
601 if first_owner.is_none() {
602 first_owner = Some((*owner_path).clone());
603 }
604 if owner_node.is_test_reachable() {
605 any_reachable = true;
606 provenance.get_or_insert_with(|| (*owner_path).clone());
607 let refs = build_test_referenced_exports(&owner_node.exports, &graph.modules);
608 combined_refs.extend(refs);
609 }
610 }
611
612 let provenance_owner = provenance.or(first_owner)?;
613 Some(TemplateInheritContext {
614 is_test_reachable: any_reachable,
615 test_referenced_exports: combined_refs,
616 provenance_owner,
617 })
618}
619
620fn template_owner<'a>(
621 importer_id: crate::discover::FileId,
622 graph: &'a fallow_graph::graph::ModuleGraph,
623 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
624 file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
625) -> Option<(&'a fallow_graph::graph::ModuleNode, &'a std::path::PathBuf)> {
626 let owner_node = graph.modules.get(importer_id.0 as usize)?;
627 let owner_path = *file_paths.get(&importer_id)?;
628 if !is_template_owner_path(owner_path) || graph.test_entry_points.contains(&importer_id) {
629 return None;
630 }
631 let owner_has_component = module_by_id
632 .get(&importer_id)
633 .is_some_and(|module| module.has_angular_component_template_url);
634 owner_has_component.then_some((owner_node, owner_path))
635}
636
637fn is_template_owner_path(path: &std::path::Path) -> bool {
638 path.extension()
639 .and_then(|ext| ext.to_str())
640 .is_some_and(|ext| {
641 matches!(
642 ext.to_ascii_lowercase().as_str(),
643 "ts" | "tsx" | "mts" | "cts"
644 )
645 })
646}
647
648fn build_test_referenced_exports(
653 exports: &[fallow_graph::graph::ExportSymbol],
654 graph_modules: &[fallow_graph::graph::ModuleNode],
655) -> rustc_hash::FxHashSet<String> {
656 let mut set = rustc_hash::FxHashSet::default();
657 for export in exports {
658 if export.is_type_only {
659 continue;
660 }
661 let has_test_ref = export.references.iter().any(|reference| {
662 graph_modules
663 .get(reference.from_file.0 as usize)
664 .is_some_and(fallow_graph::graph::ModuleNode::is_test_reachable)
665 });
666 if has_test_ref {
667 set.insert(export.name.to_string());
668 }
669 }
670 set
671}
672
673fn collect_direct_callers(
674 graph: &fallow_graph::graph::ModuleGraph,
675 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
676) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>> {
677 let mut callers_by_target = rustc_hash::FxHashMap::default();
678 for node in &graph.modules {
679 let Some(target_path) = file_paths.get(&node.file_id) else {
680 continue;
681 };
682 let mut callers = graph
683 .direct_importer_summaries(node.file_id)
684 .into_iter()
685 .filter_map(|summary| {
686 file_paths
687 .get(&summary.source)
688 .map(|caller_path| DirectCallerEvidence {
689 path: (*caller_path).clone(),
690 symbols: summary
691 .symbols
692 .into_iter()
693 .map(|symbol| DirectCallerSymbolEvidence {
694 imported: symbol.imported,
695 local: symbol.local,
696 type_only: symbol.type_only,
697 })
698 .collect(),
699 })
700 })
701 .collect::<Vec<_>>();
702 callers.sort_by(|a, b| a.path.cmp(&b.path));
703 callers.truncate(MAX_DIRECT_CALLER_EVIDENCE);
704 if !callers.is_empty() {
705 callers_by_target.insert((*target_path).clone(), callers);
706 }
707 }
708 callers_by_target
709}
710
711#[expect(
714 clippy::suboptimal_flops,
715 reason = "explicit multiplication matches the CRAP formula specification"
716)]
717fn crap_formula(cc: f64, coverage_pct: f64) -> f64 {
718 let uncovered = 1.0 - coverage_pct / 100.0;
719 cc * cc * uncovered * uncovered * uncovered + cc
720}
721
722const ANONYMOUS_FALLBACK_MAX_COLUMN_DRIFT: u32 = 16;
728
729pub struct IstanbulFileCoverage {
732 functions: rustc_hash::FxHashMap<(String, u32, u32), f64>,
742}
743
744impl IstanbulFileCoverage {
745 pub fn lookup(&self, name: &str, line: u32, col: u32) -> Option<f64> {
762 if let Some(&pct) = self.functions.get(&(name.to_string(), line, col)) {
763 return Some(pct);
764 }
765 if let Some(pct) = self
766 .functions
767 .iter()
768 .filter(|((n, l, _), _)| n == name && l.abs_diff(line) <= 2)
769 .min_by_key(|((_, l, c), _)| (l.abs_diff(line), c.abs_diff(col)))
770 .map(|(_, &pct)| pct)
771 {
772 return Some(pct);
773 }
774 let mut nearest_distance: Option<(u32, u32)> = None;
775 let mut nearest_pct: Option<f64> = None;
776 let mut tied = false;
777 for ((n, l, c), &pct) in &self.functions {
778 if !n.starts_with("(anonymous_") {
779 continue;
780 }
781 if l.abs_diff(line) > 2 {
782 continue;
783 }
784 let dist = (l.abs_diff(line), c.abs_diff(col));
785 if dist.0 > 0 && dist.1 > ANONYMOUS_FALLBACK_MAX_COLUMN_DRIFT {
786 continue;
787 }
788 match nearest_distance {
789 None => {
790 nearest_distance = Some(dist);
791 nearest_pct = Some(pct);
792 tied = false;
793 }
794 Some(prev) if dist < prev => {
795 nearest_distance = Some(dist);
796 nearest_pct = Some(pct);
797 tied = false;
798 }
799 Some(prev) if dist == prev => {
800 tied = true;
801 }
802 Some(_) => {}
803 }
804 }
805 if tied { None } else { nearest_pct }
806 }
807}
808
809pub struct IstanbulCoverage {
811 files: rustc_hash::FxHashMap<std::path::PathBuf, IstanbulFileCoverage>,
812}
813
814impl IstanbulCoverage {
815 pub fn get(&self, path: &std::path::Path) -> Option<&IstanbulFileCoverage> {
817 self.files.get(path)
818 }
819}
820
821enum CrapCoverageResolution<'a> {
829 TemplateInherited(&'a TemplateInheritContext),
830 Istanbul {
831 file_coverage: Option<&'a IstanbulFileCoverage>,
832 },
833 StaticEstimated,
834}
835
836fn resolve_crap_coverage<'a>(
837 template_inherit: Option<&'a TemplateInheritContext>,
838 istanbul_coverage: Option<&'a IstanbulCoverage>,
839 path: &std::path::Path,
840) -> CrapCoverageResolution<'a> {
841 if let Some(inherit_ctx) = template_inherit {
842 CrapCoverageResolution::TemplateInherited(inherit_ctx)
843 } else if let Some(istanbul) = istanbul_coverage {
844 let canonical = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
845 CrapCoverageResolution::Istanbul {
846 file_coverage: istanbul.get(&canonical),
847 }
848 } else {
849 CrapCoverageResolution::StaticEstimated
850 }
851}
852
853pub(super) fn auto_detect_coverage(root: &std::path::Path) -> Option<std::path::PathBuf> {
860 let candidates = [
861 root.join("coverage/coverage-final.json"),
862 root.join(".nyc_output/coverage-final.json"),
863 ];
864 candidates.into_iter().find(|p| p.is_file())
865}
866
867pub fn resolve_relative_to_root(
873 path: &std::path::Path,
874 project_root: Option<&std::path::Path>,
875) -> std::path::PathBuf {
876 if fallow_types::path_util::is_absolute_path_any_platform(path) {
877 return path.to_path_buf();
878 }
879 match project_root {
880 Some(root) => root.join(path),
881 None => path.to_path_buf(),
882 }
883}
884
885pub(super) fn load_istanbul_coverage(
897 path: &std::path::Path,
898 coverage_root: Option<&std::path::Path>,
899 project_root: Option<&std::path::Path>,
900) -> Result<IstanbulCoverage, String> {
901 super::validate_coverage_root_absolute(coverage_root)?;
902 let resolved = resolve_relative_to_root(path, project_root);
903 let file_path = if resolved.is_dir() {
904 let candidate = resolved.join("coverage-final.json");
905 if candidate.is_file() {
906 candidate
907 } else {
908 return Err(format!(
909 "no coverage-final.json found in {}",
910 resolved.display()
911 ));
912 }
913 } else {
914 resolved
915 };
916
917 let json = std::fs::read_to_string(&file_path)
918 .map_err(|e| format!("failed to read coverage file {}: {e}", file_path.display()))?;
919
920 let raw: std::collections::BTreeMap<String, oxc_coverage_instrument::FileCoverage> =
921 oxc_coverage_instrument::parse_coverage_map(&json).map_err(|e| {
922 format!(
923 "failed to parse coverage data from {}: {e}",
924 file_path.display()
925 )
926 })?;
927
928 let mut files = rustc_hash::FxHashMap::default();
929 for file_cov in raw.values() {
930 let raw_path = std::path::PathBuf::from(&file_cov.path);
931 let file_path = if let (Some(cov_root), Some(proj_root)) = (coverage_root, project_root) {
932 raw_path
933 .strip_prefix(cov_root)
934 .map(|rel| proj_root.join(rel))
935 .unwrap_or(raw_path)
936 } else {
937 raw_path
938 };
939 let canonical = dunce::canonicalize(&file_path).unwrap_or(file_path);
940
941 let mut functions = rustc_hash::FxHashMap::default();
942 for (fn_id, fn_entry) in &file_cov.fn_map {
943 let coverage_pct = compute_function_statement_coverage(file_cov, fn_id, fn_entry);
944 insert_istanbul_function_coverage(&mut functions, fn_entry, coverage_pct);
945 }
946
947 files.insert(canonical, IstanbulFileCoverage { functions });
948 }
949
950 Ok(IstanbulCoverage { files })
951}
952
953fn insert_istanbul_function_coverage(
954 functions: &mut rustc_hash::FxHashMap<(String, u32, u32), f64>,
955 fn_entry: &oxc_coverage_instrument::FnEntry,
956 coverage_pct: f64,
957) {
958 let name = fn_entry.name.clone();
959 let primary = (
960 name.clone(),
961 effective_istanbul_fn_line(fn_entry),
962 effective_istanbul_fn_col(fn_entry),
963 );
964 functions.insert(primary.clone(), coverage_pct);
965
966 let declaration = (name, fn_entry.decl.start.line, fn_entry.decl.start.column);
967 if declaration != primary {
968 functions.entry(declaration).or_insert(coverage_pct);
969 }
970}
971
972fn effective_istanbul_fn_line(fn_entry: &oxc_coverage_instrument::FnEntry) -> u32 {
973 if fn_entry.line > 0 {
974 fn_entry.line
975 } else {
976 fn_entry.decl.start.line
977 }
978}
979
980fn effective_istanbul_fn_col(fn_entry: &oxc_coverage_instrument::FnEntry) -> u32 {
985 fn_entry.decl.start.column
986}
987
988fn compute_function_statement_coverage(
995 file_cov: &oxc_coverage_instrument::FileCoverage,
996 fn_id: &str,
997 fn_entry: &oxc_coverage_instrument::FnEntry,
998) -> f64 {
999 let fn_start_line = fn_entry.loc.start.line;
1000 let fn_start_col = fn_entry.loc.start.column;
1001 let fn_end_line = fn_entry.loc.end.line;
1002 let fn_end_col = fn_entry.loc.end.column;
1003
1004 let mut total = 0u32;
1005 let mut covered = 0u32;
1006
1007 for (stmt_id, stmt_loc) in &file_cov.statement_map {
1008 let after_start = stmt_loc.start.line > fn_start_line
1009 || (stmt_loc.start.line == fn_start_line && stmt_loc.start.column >= fn_start_col);
1010 let before_end = stmt_loc.end.line < fn_end_line
1011 || (stmt_loc.end.line == fn_end_line && stmt_loc.end.column <= fn_end_col);
1012
1013 if after_start && before_end {
1014 total += 1;
1015 if file_cov.s.get(stmt_id).copied().unwrap_or(0) > 0 {
1016 covered += 1;
1017 }
1018 }
1019 }
1020
1021 if total == 0 {
1022 let hit = file_cov.f.get(fn_id).copied().unwrap_or(0);
1023 if hit > 0 { 100.0 } else { 0.0 }
1024 } else {
1025 f64::from(covered) / f64::from(total) * 100.0
1026 }
1027}
1028
1029pub(super) fn count_unused_exports_by_path(
1034 unused_exports: &[crate::results::UnusedExportFinding],
1035) -> rustc_hash::FxHashMap<&std::path::Path, usize> {
1036 let mut map: rustc_hash::FxHashMap<&std::path::Path, usize> = rustc_hash::FxHashMap::default();
1037 for exp in unused_exports {
1038 *map.entry(exp.export.path.as_path()).or_default() += 1;
1039 }
1040 map
1041}
1042
1043pub(super) fn compute_maintainability_index(
1063 complexity_density: f64,
1064 dead_code_ratio: f64,
1065 fan_out: usize,
1066 lines: u32,
1067) -> f64 {
1068 let dampening = (f64::from(lines) / fallow_output::MI_DENSITY_MIN_LINES).min(1.0);
1069 let fan_out_penalty = ((fan_out as f64).ln_1p() * 4.0).min(15.0);
1070 #[expect(
1071 clippy::suboptimal_flops,
1072 reason = "formula matches documented specification"
1073 )]
1074 let score = 100.0
1075 - (complexity_density * 30.0 * dampening)
1076 - (dead_code_ratio * 20.0)
1077 - fan_out_penalty;
1078 score.clamp(0.0, 100.0)
1079}
1080
1081fn file_score_structural_concern(score: &FileHealthScore) -> f64 {
1082 (100.0 - score.maintainability_index).clamp(0.0, 100.0)
1083}
1084
1085fn file_score_crap_concern(crap_max: f64) -> f64 {
1086 if crap_max <= 0.0 {
1087 0.0
1088 } else if crap_max < 15.0 {
1089 (crap_max / 15.0) * 45.0
1090 } else if crap_max < CRAP_THRESHOLD {
1091 ((crap_max - 15.0) / 15.0).mul_add(30.0, 45.0)
1092 } else if crap_max < 100.0 {
1093 ((crap_max - CRAP_THRESHOLD) / (100.0 - CRAP_THRESHOLD)).mul_add(25.0, 75.0)
1094 } else {
1095 100.0
1096 }
1097}
1098
1099fn file_score_triage_concern(score: &FileHealthScore) -> f64 {
1100 file_score_structural_concern(score).max(file_score_crap_concern(score.crap_max))
1101}
1102
1103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1109pub enum FileScoreConcern {
1110 Structural,
1111 Risk,
1112}
1113
1114impl FileScoreConcern {
1115 pub const fn label(self) -> &'static str {
1117 match self {
1118 Self::Structural => "structure",
1119 Self::Risk => "risk",
1120 }
1121 }
1122}
1123
1124pub fn file_score_concern_axis(score: &FileHealthScore) -> FileScoreConcern {
1129 if score.crap_max <= 0.0 {
1130 FileScoreConcern::Structural
1131 } else if file_score_crap_concern(score.crap_max) >= file_score_structural_concern(score) {
1132 FileScoreConcern::Risk
1133 } else {
1134 FileScoreConcern::Structural
1135 }
1136}
1137
1138fn compare_file_score_triage(a: &FileHealthScore, b: &FileHealthScore) -> std::cmp::Ordering {
1139 file_score_triage_concern(b)
1140 .total_cmp(&file_score_triage_concern(a))
1141 .then_with(|| b.crap_max.total_cmp(&a.crap_max))
1142 .then_with(|| a.maintainability_index.total_cmp(&b.maintainability_index))
1143 .then_with(|| a.path.cmp(&b.path))
1144}
1145
1146pub(super) fn compute_file_scores(
1152 modules: &[crate::source::ModuleInfo],
1153 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
1154 changed_files: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1155 analysis_output: crate::results::DeadCodeAnalysisArtifacts,
1156 istanbul_coverage: Option<&IstanbulCoverage>,
1157 root: &std::path::Path,
1158) -> Result<FileScoreOutput, String> {
1159 let retained_graph = analysis_output.graph.ok_or("graph not available")?;
1160 let graph = retained_graph.as_graph();
1161 let results = &analysis_output.results;
1162
1163 let circular_files = collect_circular_files(results);
1164 let top_complex_fns = collect_top_complex_fns(modules, file_paths);
1165 let cycle_members = collect_cycle_members(results);
1166 let direct_callers = collect_direct_callers(graph, file_paths);
1167 let unused_export_names = collect_unused_export_names(results);
1168
1169 let unused_files: rustc_hash::FxHashSet<&std::path::Path> = results
1170 .unused_files
1171 .iter()
1172 .map(|f| f.file.path.as_path())
1173 .collect();
1174
1175 let unused_exports_by_path = count_unused_exports_by_path(&results.unused_exports);
1176
1177 let FileScoreCoverageSetup {
1178 module_by_id,
1179 coverage,
1180 } = prepare_file_score_coverage_setup(modules, file_paths, results, graph, root);
1181
1182 let template_inherit = build_template_inherit_contexts(graph, &module_by_id, file_paths);
1183
1184 let mut acc = accumulate_file_scores(
1185 unused_export_names,
1186 &FileScoreLoopCtx {
1187 graph,
1188 file_paths,
1189 module_by_id: &module_by_id,
1190 unused_files: &unused_files,
1191 unused_exports_by_path: &unused_exports_by_path,
1192 template_inherit: &template_inherit,
1193 istanbul_coverage,
1194 },
1195 );
1196 acc.scores = finalize_file_score_list(acc.scores, changed_files);
1197
1198 Ok(build_file_score_output(FileScoreOutputParts {
1199 graph,
1200 file_paths,
1201 results,
1202 scores: acc.scores,
1203 coverage,
1204 circular_files,
1205 top_complex_fns,
1206 entry_points: acc.entry_points,
1207 value_export_counts: acc.value_export_counts,
1208 unused_export_names: acc.unused_export_names,
1209 cycle_members,
1210 direct_callers,
1211 istanbul_matched: acc.istanbul_matched,
1212 istanbul_total: acc.istanbul_total,
1213 per_function_crap: acc.per_function_crap,
1214 template_inherit,
1215 }))
1216}
1217
1218struct FileScoreLoopCtx<'a> {
1220 graph: &'a fallow_graph::graph::ModuleGraph,
1221 file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
1222 module_by_id: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
1223 unused_files: &'a rustc_hash::FxHashSet<&'a std::path::Path>,
1224 unused_exports_by_path: &'a rustc_hash::FxHashMap<&'a std::path::Path, usize>,
1225 template_inherit: &'a rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
1226 istanbul_coverage: Option<&'a IstanbulCoverage>,
1227}
1228
1229struct FileScoreAccumulator {
1231 scores: Vec<FileHealthScore>,
1232 entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
1233 value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
1234 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
1235 per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
1236 istanbul_matched: usize,
1237 istanbul_total: usize,
1238}
1239
1240impl FileScoreAccumulator {
1241 fn with_capacity(modules: usize) -> Self {
1243 FileScoreAccumulator {
1244 scores: Vec::with_capacity(modules),
1245 entry_points: rustc_hash::FxHashSet::default(),
1246 value_export_counts: rustc_hash::FxHashMap::default(),
1247 unused_export_names: rustc_hash::FxHashMap::default(),
1248 per_function_crap: rustc_hash::FxHashMap::default(),
1249 istanbul_matched: 0,
1250 istanbul_total: 0,
1251 }
1252 }
1253}
1254
1255fn accumulate_file_scores(
1258 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
1259 ctx: &FileScoreLoopCtx<'_>,
1260) -> FileScoreAccumulator {
1261 let mut acc = FileScoreAccumulator {
1262 unused_export_names,
1263 ..FileScoreAccumulator::with_capacity(ctx.graph.modules.len())
1264 };
1265 for node in &ctx.graph.modules {
1266 let Some(path) = ctx.file_paths.get(&node.file_id) else {
1267 continue;
1268 };
1269 record_entry_point(&mut acc.entry_points, node, path);
1270 let score = compute_one_file_score(&mut acc, ctx, node, path);
1271 acc.scores.push(score);
1272 }
1273 acc
1274}
1275
1276fn finalize_file_score_list(
1279 mut scores: Vec<FileHealthScore>,
1280 changed_files: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1281) -> Vec<FileHealthScore> {
1282 if let Some(changed) = changed_files {
1283 scores.retain(|s| changed.contains(&s.path));
1284 }
1285 scores.retain(|s| s.function_count > 0);
1286 scores.sort_by(compare_file_score_triage);
1287 scores
1288}
1289
1290fn compute_one_file_score(
1292 acc: &mut FileScoreAccumulator,
1293 ctx: &FileScoreLoopCtx<'_>,
1294 node: &fallow_graph::graph::ModuleNode,
1295 path: &std::path::Path,
1296) -> FileHealthScore {
1297 let fan_in = ctx
1298 .graph
1299 .reverse_deps
1300 .get(node.file_id.0 as usize)
1301 .map_or(0, Vec::len);
1302 let fan_out = node.edge_range.len();
1303
1304 let (total_cyclomatic, total_cognitive, function_count, lines) = ctx
1305 .module_by_id
1306 .get(&node.file_id)
1307 .map_or((0, 0, 0, 0), |module| aggregate_complexity(module));
1308
1309 let value_exports = node.exports.iter().filter(|e| !e.is_type_only).count();
1310 let path_owned = path.to_path_buf();
1311 acc.value_export_counts
1312 .insert(path_owned.clone(), value_exports);
1313 record_unused_file_export_names(
1314 path_owned.as_path(),
1315 &node.exports,
1316 ctx.unused_files,
1317 &mut acc.unused_export_names,
1318 );
1319
1320 let (dead_code_ratio_rounded, complexity_density_rounded, maintainability_index_rounded) =
1321 compute_file_score_metrics(node, &path_owned, ctx, total_cyclomatic, lines, fan_out);
1322
1323 let crap = compute_file_score_crap(
1324 node,
1325 ctx.module_by_id.get(&node.file_id).copied(),
1326 ctx.graph,
1327 ctx.template_inherit.get(&node.file_id),
1328 ctx.istanbul_coverage,
1329 &path_owned,
1330 );
1331 acc.istanbul_matched += crap.istanbul_matched;
1332 acc.istanbul_total += crap.istanbul_total;
1333 record_per_function_crap(&mut acc.per_function_crap, &path_owned, crap.per_function);
1334
1335 FileHealthScore {
1336 path: path_owned,
1337 fan_in,
1338 fan_out,
1339 dead_code_ratio: dead_code_ratio_rounded,
1340 complexity_density: complexity_density_rounded,
1341 maintainability_index: maintainability_index_rounded,
1342 total_cyclomatic,
1343 total_cognitive,
1344 function_count,
1345 lines,
1346 crap_max: crap.max,
1347 crap_above_threshold: crap.above_threshold,
1348 }
1349}
1350
1351fn compute_file_score_metrics(
1354 node: &fallow_graph::graph::ModuleNode,
1355 path: &std::path::Path,
1356 ctx: &FileScoreLoopCtx<'_>,
1357 total_cyclomatic: u32,
1358 lines: u32,
1359 fan_out: usize,
1360) -> (f64, f64, f64) {
1361 let dead_code_ratio = compute_dead_code_ratio(
1362 path,
1363 &node.exports,
1364 ctx.unused_files,
1365 ctx.unused_exports_by_path,
1366 );
1367 let complexity_density = compute_complexity_density(total_cyclomatic, lines);
1368
1369 let dead_code_ratio_rounded = (dead_code_ratio * 100.0).round() / 100.0;
1370 let complexity_density_rounded = (complexity_density * 100.0).round() / 100.0;
1371
1372 let maintainability_index = compute_maintainability_index(
1373 complexity_density_rounded,
1374 dead_code_ratio_rounded,
1375 fan_out,
1376 lines,
1377 );
1378 (
1379 dead_code_ratio_rounded,
1380 complexity_density_rounded,
1381 (maintainability_index * 10.0).round() / 10.0,
1382 )
1383}
1384
1385fn build_file_score_output(parts: FileScoreOutputParts<'_>) -> FileScoreOutput {
1386 let total_exports: usize = parts.graph.modules.iter().map(|m| m.exports.len()).sum();
1387 let unused_deps = parts.results.unused_dependencies.len()
1388 + parts.results.unused_dev_dependencies.len()
1389 + parts.results.unused_optional_dependencies.len();
1390 let analysis_snapshot =
1391 build_analysis_counts_snapshot(parts.graph, parts.file_paths, parts.results, unused_deps);
1392 let analysis_counts =
1393 build_file_score_analysis_counts(parts.results, total_exports, unused_deps);
1394 let template_inherit_provenance =
1395 build_template_inherit_provenance(parts.template_inherit, parts.file_paths);
1396
1397 FileScoreOutput {
1398 scores: parts.scores,
1399 coverage: parts.coverage,
1400 circular_files: parts.circular_files,
1401 top_complex_fns: parts.top_complex_fns,
1402 entry_points: parts.entry_points,
1403 value_export_counts: parts.value_export_counts,
1404 unused_export_names: parts.unused_export_names,
1405 cycle_members: parts.cycle_members,
1406 direct_callers: parts.direct_callers,
1407 analysis_counts,
1408 prop_drilling_chains: parts.results.prop_drilling_chains.clone(),
1409 render_fan_in: parts.results.render_fan_in.clone(),
1410 analysis_snapshot,
1411 istanbul_matched: parts.istanbul_matched,
1412 istanbul_total: parts.istanbul_total,
1413 per_function_crap: parts.per_function_crap,
1414 template_inherit_provenance,
1415 }
1416}
1417
1418fn build_file_score_analysis_counts(
1419 results: &crate::results::AnalysisResults,
1420 total_exports: usize,
1421 unused_deps: usize,
1422) -> crate::vital_signs::AnalysisCounts {
1423 crate::vital_signs::AnalysisCounts {
1424 total_exports,
1425 dead_files: results.unused_files.len(),
1426 dead_exports: results.unused_exports.len() + results.unused_types.len(),
1427 unused_deps,
1428 circular_deps: results.circular_dependencies.len(),
1429 total_deps: 0usize,
1430 }
1431}
1432
1433fn build_template_inherit_provenance(
1434 template_inherit: rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
1435 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
1436) -> rustc_hash::FxHashMap<std::path::PathBuf, std::path::PathBuf> {
1437 template_inherit
1438 .into_iter()
1439 .filter_map(|(file_id, ctx)| {
1440 file_paths
1441 .get(&file_id)
1442 .map(|path| ((**path).clone(), ctx.provenance_owner))
1443 })
1444 .collect()
1445}
1446
1447fn record_entry_point(
1448 entry_points: &mut rustc_hash::FxHashSet<std::path::PathBuf>,
1449 node: &fallow_graph::graph::ModuleNode,
1450 path: &std::path::Path,
1451) {
1452 if node.is_entry_point() {
1453 entry_points.insert(path.to_path_buf());
1454 }
1455}
1456
1457fn record_unused_file_export_names(
1458 path: &std::path::Path,
1459 exports: &[fallow_graph::graph::ExportSymbol],
1460 unused_files: &rustc_hash::FxHashSet<&std::path::Path>,
1461 unused_export_names: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
1462) {
1463 if !unused_files.contains(path) || unused_export_names.contains_key(path) {
1464 return;
1465 }
1466
1467 let names: Vec<String> = exports
1468 .iter()
1469 .filter(|export| !export.is_type_only)
1470 .map(|export| export.name.to_string())
1471 .collect();
1472 if !names.is_empty() {
1473 unused_export_names.insert(path.to_path_buf(), names);
1474 }
1475}
1476
1477struct FileScoreCrap {
1478 max: f64,
1479 above_threshold: usize,
1480 per_function: Vec<PerFunctionCrap>,
1481 istanbul_matched: usize,
1482 istanbul_total: usize,
1483}
1484
1485impl FileScoreCrap {
1486 fn empty() -> Self {
1487 Self {
1488 max: 0.0,
1489 above_threshold: 0,
1490 per_function: Vec::new(),
1491 istanbul_matched: 0,
1492 istanbul_total: 0,
1493 }
1494 }
1495
1496 fn estimated(result: EstimatedCrapResult) -> Self {
1497 Self {
1498 max: result.max_crap,
1499 above_threshold: result.above_threshold,
1500 per_function: result.per_function,
1501 istanbul_matched: 0,
1502 istanbul_total: 0,
1503 }
1504 }
1505
1506 fn istanbul(result: IstanbulCrapResult) -> Self {
1507 Self {
1508 max: result.max_crap,
1509 above_threshold: result.above_threshold,
1510 per_function: result.per_function,
1511 istanbul_matched: result.matched,
1512 istanbul_total: result.total,
1513 }
1514 }
1515}
1516
1517fn compute_file_score_crap(
1518 node: &fallow_graph::graph::ModuleNode,
1519 module: Option<&crate::source::ModuleInfo>,
1520 graph: &fallow_graph::graph::ModuleGraph,
1521 template_inherit: Option<&TemplateInheritContext>,
1522 istanbul_coverage: Option<&IstanbulCoverage>,
1523 path: &std::path::Path,
1524) -> FileScoreCrap {
1525 let Some(module) = module else {
1526 return FileScoreCrap::empty();
1527 };
1528
1529 let is_coverage_suppressed = crate::suppress::is_file_suppressed(
1530 &module.suppressions,
1531 fallow_types::suppress::IssueKind::CoverageGaps,
1532 );
1533 let is_test_reachable = node.is_test_reachable() || is_coverage_suppressed;
1534 let resolution = resolve_crap_coverage(template_inherit, istanbul_coverage, path);
1535 match resolution {
1536 CrapCoverageResolution::TemplateInherited(inherit_ctx) => {
1537 compute_template_inherited_crap(module, inherit_ctx)
1538 }
1539 CrapCoverageResolution::Istanbul { file_coverage } => {
1540 compute_istanbul_file_crap(module, file_coverage, is_test_reachable)
1541 }
1542 CrapCoverageResolution::StaticEstimated => {
1543 compute_static_file_crap(module, &node.exports, &graph.modules, is_test_reachable)
1544 }
1545 }
1546}
1547
1548fn compute_template_inherited_crap(
1549 module: &crate::source::ModuleInfo,
1550 inherit_ctx: &TemplateInheritContext,
1551) -> FileScoreCrap {
1552 FileScoreCrap::estimated(compute_crap_scores_estimated(
1553 &module.complexity,
1554 &inherit_ctx.test_referenced_exports,
1555 inherit_ctx.is_test_reachable,
1556 fallow_output::CoverageSource::EstimatedComponentInherited,
1557 ))
1558}
1559
1560fn compute_istanbul_file_crap(
1561 module: &crate::source::ModuleInfo,
1562 file_coverage: Option<&IstanbulFileCoverage>,
1563 is_test_reachable: bool,
1564) -> FileScoreCrap {
1565 FileScoreCrap::istanbul(compute_crap_scores_istanbul(
1566 &module.complexity,
1567 file_coverage,
1568 is_test_reachable,
1569 ))
1570}
1571
1572fn compute_static_file_crap(
1573 module: &crate::source::ModuleInfo,
1574 exports: &[fallow_graph::graph::ExportSymbol],
1575 graph_modules: &[fallow_graph::graph::ModuleNode],
1576 is_test_reachable: bool,
1577) -> FileScoreCrap {
1578 let test_refs = build_test_referenced_exports(exports, graph_modules);
1579 FileScoreCrap::estimated(compute_crap_scores_estimated(
1580 &module.complexity,
1581 &test_refs,
1582 is_test_reachable,
1583 fallow_output::CoverageSource::Estimated,
1584 ))
1585}
1586
1587fn record_per_function_crap(
1588 per_function_crap: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
1589 path: &std::path::Path,
1590 per_function: Vec<PerFunctionCrap>,
1591) {
1592 if !per_function.is_empty() {
1593 per_function_crap.insert(path.to_path_buf(), per_function);
1594 }
1595}
1596
1597struct FileScoreCoverageSetup<'a> {
1598 module_by_id: rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
1599 coverage: CoverageGapData,
1600}
1601
1602fn prepare_file_score_coverage_setup<'a>(
1603 modules: &'a [crate::source::ModuleInfo],
1604 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
1605 results: &crate::results::AnalysisResults,
1606 graph: &fallow_graph::graph::ModuleGraph,
1607 root: &std::path::Path,
1608) -> FileScoreCoverageSetup<'a> {
1609 let module_by_id: rustc_hash::FxHashMap<_, _> =
1610 modules.iter().map(|m| (m.file_id, m)).collect();
1611 let unused_exports: rustc_hash::FxHashSet<(&std::path::Path, String)> = results
1612 .unused_exports
1613 .iter()
1614 .map(|export| {
1615 (
1616 export.export.path.as_path(),
1617 export.export.export_name.clone(),
1618 )
1619 })
1620 .collect();
1621 let coverage = compute_coverage_gaps(graph, file_paths, &module_by_id, &unused_exports, root);
1622 FileScoreCoverageSetup {
1623 module_by_id,
1624 coverage,
1625 }
1626}
1627
1628fn collect_circular_files(
1629 results: &crate::results::AnalysisResults,
1630) -> rustc_hash::FxHashSet<std::path::PathBuf> {
1631 results
1632 .circular_dependencies
1633 .iter()
1634 .flat_map(|c| c.cycle.files.iter().cloned())
1635 .collect()
1636}
1637
1638fn collect_top_complex_fns(
1639 modules: &[crate::source::ModuleInfo],
1640 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
1641) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>> {
1642 let mut top_complex_fns = rustc_hash::FxHashMap::default();
1643 for module in modules {
1644 if module.complexity.is_empty() {
1645 continue;
1646 }
1647 let Some(path) = file_paths.get(&module.file_id) else {
1648 continue;
1649 };
1650 let mut funcs: Vec<(String, u32, u16)> = module
1651 .complexity
1652 .iter()
1653 .map(|f| (f.name.clone(), f.line, f.cognitive))
1654 .collect();
1655 funcs.sort_by_key(|f| std::cmp::Reverse(f.2));
1656 funcs.truncate(3);
1657 if funcs[0].2 > 0 {
1658 top_complex_fns.insert((*path).clone(), funcs);
1659 }
1660 }
1661 top_complex_fns
1662}
1663
1664fn collect_cycle_members(
1665 results: &crate::results::AnalysisResults,
1666) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>> {
1667 let mut cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>> =
1668 rustc_hash::FxHashMap::default();
1669 for cycle in &results.circular_dependencies {
1670 for file in &cycle.cycle.files {
1671 let others: Vec<std::path::PathBuf> = cycle
1672 .cycle
1673 .files
1674 .iter()
1675 .filter(|f| *f != file)
1676 .cloned()
1677 .collect();
1678 cycle_members
1679 .entry(file.clone())
1680 .or_default()
1681 .extend(others);
1682 }
1683 }
1684 for members in cycle_members.values_mut() {
1685 members.sort();
1686 members.dedup();
1687 }
1688 cycle_members
1689}
1690
1691fn collect_unused_export_names(
1692 results: &crate::results::AnalysisResults,
1693) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> {
1694 let mut unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> =
1695 rustc_hash::FxHashMap::default();
1696 for exp in &results.unused_exports {
1697 unused_export_names
1698 .entry(exp.export.path.clone())
1699 .or_default()
1700 .push(exp.export.export_name.clone());
1701 }
1702 unused_export_names
1703}
1704
1705fn build_analysis_counts_snapshot(
1706 graph: &fallow_graph::graph::ModuleGraph,
1707 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
1708 results: &crate::results::AnalysisResults,
1709 unused_deps: usize,
1710) -> AnalysisCountsSnapshot {
1711 let mut module_export_counts = rustc_hash::FxHashMap::with_capacity_and_hasher(
1712 graph.modules.len(),
1713 rustc_hash::FxBuildHasher,
1714 );
1715 for module in &graph.modules {
1716 if let Some(path) = file_paths.get(&module.file_id) {
1717 module_export_counts.insert((*path).clone(), module.exports.len());
1718 }
1719 }
1720
1721 let mut unused_export_paths =
1722 Vec::with_capacity(results.unused_exports.len() + results.unused_types.len());
1723 unused_export_paths.extend(results.unused_exports.iter().map(|e| e.export.path.clone()));
1724 unused_export_paths.extend(results.unused_types.iter().map(|e| e.export.path.clone()));
1725
1726 let mut unused_dep_package_paths = Vec::with_capacity(unused_deps);
1727 unused_dep_package_paths.extend(
1728 results
1729 .unused_dependencies
1730 .iter()
1731 .map(|d| d.dep.path.clone()),
1732 );
1733 unused_dep_package_paths.extend(
1734 results
1735 .unused_dev_dependencies
1736 .iter()
1737 .map(|d| d.dep.path.clone()),
1738 );
1739 unused_dep_package_paths.extend(
1740 results
1741 .unused_optional_dependencies
1742 .iter()
1743 .map(|d| d.dep.path.clone()),
1744 );
1745
1746 AnalysisCountsSnapshot {
1747 unused_file_paths: results
1748 .unused_files
1749 .iter()
1750 .map(|f| f.file.path.clone())
1751 .collect(),
1752 unused_export_paths,
1753 unused_dep_package_paths,
1754 circular_dep_groups: results
1755 .circular_dependencies
1756 .iter()
1757 .map(|c| c.cycle.files.clone())
1758 .collect(),
1759 module_export_counts,
1760 }
1761}
1762
1763#[cfg(test)]
1764mod tests {
1765 use super::*;
1766
1767 #[test]
1768 fn maintainability_perfect_score() {
1769 assert!((compute_maintainability_index(0.0, 0.0, 0, 100) - 100.0).abs() < f64::EPSILON);
1770 }
1771
1772 #[test]
1773 fn crap_resolution_prefers_template_inheritance_over_istanbul() {
1774 let inherit_ctx = TemplateInheritContext {
1775 is_test_reachable: true,
1776 test_referenced_exports: rustc_hash::FxHashSet::default(),
1777 provenance_owner: std::path::PathBuf::from("/project/src/app.component.ts"),
1778 };
1779 let istanbul = IstanbulCoverage {
1780 files: rustc_hash::FxHashMap::default(),
1781 };
1782
1783 let resolution = resolve_crap_coverage(
1784 Some(&inherit_ctx),
1785 Some(&istanbul),
1786 std::path::Path::new("/project/src/app.component.html"),
1787 );
1788
1789 assert!(matches!(
1790 resolution,
1791 CrapCoverageResolution::TemplateInherited(_)
1792 ));
1793 }
1794
1795 #[test]
1796 fn crap_resolution_keeps_istanbul_when_file_is_missing() {
1797 let istanbul = IstanbulCoverage {
1798 files: rustc_hash::FxHashMap::default(),
1799 };
1800
1801 let resolution = resolve_crap_coverage(
1802 None,
1803 Some(&istanbul),
1804 std::path::Path::new("/project/src/missing.ts"),
1805 );
1806
1807 assert!(matches!(
1808 resolution,
1809 CrapCoverageResolution::Istanbul {
1810 file_coverage: None
1811 }
1812 ));
1813 }
1814
1815 #[test]
1816 fn maintainability_clamped_at_zero() {
1817 assert!((compute_maintainability_index(10.0, 1.0, 100, 200) - 0.0).abs() < f64::EPSILON);
1818 }
1819
1820 #[test]
1821 fn maintainability_formula_correct() {
1822 let result = compute_maintainability_index(0.5, 0.3, 10, 100);
1823 let expected = 11.0_f64.ln().mul_add(-4.0, 100.0 - 15.0 - 6.0);
1824 assert!((result - expected).abs() < 0.01);
1825 }
1826
1827 #[test]
1828 fn maintainability_dead_file_penalty() {
1829 let result = compute_maintainability_index(0.0, 1.0, 0, 100);
1830 assert!((result - 80.0).abs() < f64::EPSILON);
1831 }
1832
1833 #[test]
1834 fn maintainability_fan_out_is_logarithmic() {
1835 let result_10 = compute_maintainability_index(0.0, 0.0, 10, 100);
1836 let result_100 = compute_maintainability_index(0.0, 0.0, 100, 100);
1837 let result_200 = compute_maintainability_index(0.0, 0.0, 200, 100);
1838
1839 assert!(result_10 > 90.0); assert!(result_100 > 84.0); assert!((result_100 - result_200).abs() < f64::EPSILON);
1842 }
1843
1844 #[test]
1845 fn maintainability_fan_out_capped_at_15() {
1846 let result = compute_maintainability_index(0.0, 1.0, 1000, 100);
1847 assert!((result - 65.0).abs() < f64::EPSILON);
1848 }
1849
1850 #[test]
1851 fn maintainability_small_file_dampened() {
1852 let small = compute_maintainability_index(0.40, 0.0, 0, 5);
1853 assert!((small - 98.8).abs() < 0.01);
1854 }
1855
1856 #[test]
1857 fn maintainability_large_file_undampened() {
1858 let large = compute_maintainability_index(0.30, 0.0, 0, 192);
1859 assert!((large - 91.0).abs() < 0.01);
1860 }
1861
1862 #[test]
1863 fn maintainability_small_file_ranks_better_than_complex_large_file() {
1864 let trivial = compute_maintainability_index(0.40, 0.0, 0, 5);
1865 let nightmare = compute_maintainability_index(0.30, 0.0, 0, 192);
1866 assert!(
1867 trivial > nightmare,
1868 "trivial file ({trivial}) should rank better than nightmare ({nightmare})"
1869 );
1870 }
1871
1872 #[test]
1873 fn maintainability_at_dampening_boundary() {
1874 let at_boundary = compute_maintainability_index(0.5, 0.0, 0, 50);
1875 let above_boundary = compute_maintainability_index(0.5, 0.0, 0, 51);
1876 assert!((at_boundary - above_boundary).abs() < 0.01);
1877 }
1878
1879 #[test]
1880 fn maintainability_zero_lines_zero_density_penalty() {
1881 let result = compute_maintainability_index(5.0, 0.0, 0, 0);
1882 assert!((result - 100.0).abs() < f64::EPSILON);
1883 }
1884
1885 #[test]
1886 fn complexity_density_zero_lines() {
1887 assert!((compute_complexity_density(10, 0)).abs() < f64::EPSILON);
1888 }
1889
1890 #[test]
1891 fn complexity_density_normal() {
1892 let result = compute_complexity_density(10, 100);
1893 assert!((result - 0.1).abs() < f64::EPSILON);
1894 }
1895
1896 #[test]
1897 fn complexity_density_high() {
1898 let result = compute_complexity_density(50, 10);
1899 assert!((result - 5.0).abs() < f64::EPSILON);
1900 }
1901
1902 #[test]
1903 fn dead_code_ratio_no_exports() {
1904 let unused_files = rustc_hash::FxHashSet::default();
1905 let unused_map = rustc_hash::FxHashMap::default();
1906 let path = std::path::Path::new("/src/foo.ts");
1907 let exports: Vec<fallow_graph::graph::ExportSymbol> = vec![];
1908
1909 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
1910 assert!((ratio).abs() < f64::EPSILON);
1911 }
1912
1913 #[test]
1914 fn dead_code_ratio_all_unused_file() {
1915 let mut unused_files: rustc_hash::FxHashSet<&std::path::Path> =
1916 rustc_hash::FxHashSet::default();
1917 let path = std::path::Path::new("/src/foo.ts");
1918 unused_files.insert(path);
1919 let unused_map = rustc_hash::FxHashMap::default();
1920 let exports: Vec<fallow_graph::graph::ExportSymbol> = vec![];
1921
1922 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
1923 assert!((ratio - 1.0).abs() < f64::EPSILON);
1924 }
1925
1926 #[test]
1927 fn dead_code_ratio_mix() {
1928 let unused_files = rustc_hash::FxHashSet::default();
1929 let path = std::path::Path::new("/src/foo.ts");
1930
1931 let exports = vec![
1932 fallow_graph::graph::ExportSymbol {
1933 name: crate::source::ExportName::Named("a".into()),
1934 is_type_only: false,
1935 is_side_effect_used: false,
1936 visibility: crate::source::VisibilityTag::None,
1937 expected_unused_reason: None,
1938 span: oxc_span::Span::empty(0),
1939 references: vec![],
1940 members: vec![],
1941 },
1942 fallow_graph::graph::ExportSymbol {
1943 name: crate::source::ExportName::Named("b".into()),
1944 is_type_only: false,
1945 is_side_effect_used: false,
1946 visibility: crate::source::VisibilityTag::None,
1947 expected_unused_reason: None,
1948 span: oxc_span::Span::empty(0),
1949 references: vec![],
1950 members: vec![],
1951 },
1952 fallow_graph::graph::ExportSymbol {
1953 name: crate::source::ExportName::Named("c".into()),
1954 is_type_only: false,
1955 is_side_effect_used: false,
1956 visibility: crate::source::VisibilityTag::None,
1957 expected_unused_reason: None,
1958 span: oxc_span::Span::empty(0),
1959 references: vec![],
1960 members: vec![],
1961 },
1962 fallow_graph::graph::ExportSymbol {
1963 name: crate::source::ExportName::Named("MyType".into()),
1964 is_type_only: true,
1965 is_side_effect_used: false,
1966 visibility: crate::source::VisibilityTag::None,
1967 expected_unused_reason: None,
1968 span: oxc_span::Span::empty(0),
1969 references: vec![],
1970 members: vec![],
1971 },
1972 ];
1973
1974 let mut unused_map: rustc_hash::FxHashMap<&std::path::Path, usize> =
1975 rustc_hash::FxHashMap::default();
1976 unused_map.insert(path, 2);
1977
1978 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
1979 assert!((ratio - 2.0 / 3.0).abs() < 1e-10);
1980 }
1981
1982 #[test]
1983 fn dead_code_ratio_all_type_only_exports() {
1984 let unused_files = rustc_hash::FxHashSet::default();
1985 let path = std::path::Path::new("/src/types.ts");
1986
1987 let exports = vec![fallow_graph::graph::ExportSymbol {
1988 name: crate::source::ExportName::Named("Foo".into()),
1989 is_type_only: true,
1990 is_side_effect_used: false,
1991 visibility: crate::source::VisibilityTag::None,
1992 expected_unused_reason: None,
1993 span: oxc_span::Span::empty(0),
1994 references: vec![],
1995 members: vec![],
1996 }];
1997 let unused_map = rustc_hash::FxHashMap::default();
1998
1999 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
2000 assert!((ratio).abs() < f64::EPSILON);
2001 }
2002
2003 #[test]
2004 fn aggregate_complexity_empty_module() {
2005 let module = crate::source::ModuleInfo {
2006 file_id: crate::discover::FileId(0),
2007 exports: vec![],
2008 imports: vec![],
2009 re_exports: vec![],
2010 dynamic_imports: vec![],
2011 dynamic_import_patterns: vec![],
2012 require_calls: vec![],
2013 package_path_references: Box::default(),
2014 member_accesses: vec![],
2015 semantic_facts: Box::default(),
2016 whole_object_uses: Box::default(),
2017 has_cjs_exports: false,
2018 has_angular_component_template_url: false,
2019 content_hash: 0,
2020 suppressions: vec![],
2021 unknown_suppression_kinds: vec![],
2022 unused_import_bindings: vec![],
2023 type_referenced_import_bindings: vec![],
2024 value_referenced_import_bindings: vec![],
2025 line_offsets: vec![],
2026 complexity: vec![],
2027 flag_uses: vec![],
2028 class_heritage: vec![],
2029 exported_factory_returns: Box::default(),
2030 type_member_types: Box::default(),
2031 injection_tokens: vec![],
2032 local_type_declarations: Vec::new(),
2033 public_signature_type_references: Vec::new(),
2034 namespace_object_aliases: Vec::new(),
2035 iconify_prefixes: Vec::new(),
2036 iconify_icon_names: Vec::new(),
2037 auto_import_candidates: Vec::new(),
2038 directives: Vec::new(),
2039 client_only_dynamic_import_spans: Vec::new(),
2040 security_sinks: Vec::new(),
2041 security_sinks_skipped: 0,
2042 security_unresolved_callee_sites: Vec::new(),
2043 tainted_bindings: Vec::new(),
2044 sanitized_sink_args: Vec::new(),
2045 security_control_sites: Vec::new(),
2046 callee_uses: Vec::new(),
2047 misplaced_directives: Vec::new(),
2048 inline_server_action_exports: Vec::new(),
2049 di_key_sites: Vec::new(),
2050 has_dynamic_provide: false,
2051 referenced_import_bindings: Vec::new(),
2052 component_props: Vec::new(),
2053 has_props_attrs_fallthrough: false,
2054 has_define_expose: false,
2055 has_define_model: false,
2056 has_unharvestable_props: false,
2057 component_emits: Vec::new(),
2058 angular_inputs: Vec::new(),
2059 angular_outputs: Vec::new(),
2060 has_unharvestable_emits: false,
2061 has_dynamic_emit: false,
2062 has_emit_whole_object_use: false,
2063 load_return_keys: Vec::new(),
2064 has_unharvestable_load: false,
2065 has_load_data_whole_use: false,
2066 has_page_data_store_whole_use: false,
2067 component_functions: Vec::new(),
2068 react_props: Vec::new(),
2069 hook_uses: Vec::new(),
2070 render_edges: Vec::new(),
2071 svelte_dispatched_events: Vec::new(),
2072 svelte_listened_events: Vec::new(),
2073 angular_component_selectors: Vec::new(),
2074 registered_custom_elements: Vec::new(),
2075 used_custom_element_tags: Vec::new(),
2076 angular_used_selectors: Vec::new(),
2077 angular_entry_component_refs: Vec::new(),
2078 has_dynamic_component_render: false,
2079 has_dynamic_dispatch: false,
2080 };
2081
2082 let (cyc, cog, funcs, lines) = aggregate_complexity(&module);
2083 assert_eq!(cyc, 0);
2084 assert_eq!(cog, 0);
2085 assert_eq!(funcs, 0);
2086 assert_eq!(lines, 0);
2087 }
2088
2089 #[test]
2090 fn aggregate_complexity_single_function() {
2091 let module = crate::source::ModuleInfo {
2092 file_id: crate::discover::FileId(0),
2093 exports: vec![],
2094 imports: vec![],
2095 re_exports: vec![],
2096 dynamic_imports: vec![],
2097 dynamic_import_patterns: vec![],
2098 require_calls: vec![],
2099 package_path_references: Box::default(),
2100 member_accesses: vec![],
2101 semantic_facts: Box::default(),
2102 whole_object_uses: Box::default(),
2103 has_cjs_exports: false,
2104 has_angular_component_template_url: false,
2105 content_hash: 0,
2106 suppressions: vec![],
2107 unknown_suppression_kinds: vec![],
2108 unused_import_bindings: vec![],
2109 type_referenced_import_bindings: vec![],
2110 value_referenced_import_bindings: vec![],
2111 flag_uses: vec![],
2112 class_heritage: vec![],
2113 exported_factory_returns: Box::default(),
2114 type_member_types: Box::default(),
2115 injection_tokens: vec![],
2116 local_type_declarations: Vec::new(),
2117 public_signature_type_references: Vec::new(),
2118 namespace_object_aliases: Vec::new(),
2119 iconify_prefixes: Vec::new(),
2120 iconify_icon_names: Vec::new(),
2121 auto_import_candidates: Vec::new(),
2122 directives: Vec::new(),
2123 client_only_dynamic_import_spans: Vec::new(),
2124 security_sinks: Vec::new(),
2125 security_sinks_skipped: 0,
2126 security_unresolved_callee_sites: Vec::new(),
2127 tainted_bindings: Vec::new(),
2128 sanitized_sink_args: Vec::new(),
2129 security_control_sites: Vec::new(),
2130 callee_uses: Vec::new(),
2131 misplaced_directives: Vec::new(),
2132 inline_server_action_exports: Vec::new(),
2133 di_key_sites: Vec::new(),
2134 has_dynamic_provide: false,
2135 referenced_import_bindings: Vec::new(),
2136 component_props: Vec::new(),
2137 has_props_attrs_fallthrough: false,
2138 has_define_expose: false,
2139 has_define_model: false,
2140 has_unharvestable_props: false,
2141 component_emits: Vec::new(),
2142 angular_inputs: Vec::new(),
2143 angular_outputs: Vec::new(),
2144 has_unharvestable_emits: false,
2145 has_dynamic_emit: false,
2146 has_emit_whole_object_use: false,
2147 load_return_keys: Vec::new(),
2148 has_unharvestable_load: false,
2149 has_load_data_whole_use: false,
2150 has_page_data_store_whole_use: false,
2151 component_functions: Vec::new(),
2152 react_props: Vec::new(),
2153 hook_uses: Vec::new(),
2154 render_edges: Vec::new(),
2155 svelte_dispatched_events: Vec::new(),
2156 svelte_listened_events: Vec::new(),
2157 angular_component_selectors: Vec::new(),
2158 registered_custom_elements: Vec::new(),
2159 used_custom_element_tags: Vec::new(),
2160 angular_used_selectors: Vec::new(),
2161 angular_entry_component_refs: Vec::new(),
2162 has_dynamic_component_render: false,
2163 has_dynamic_dispatch: false,
2164 line_offsets: vec![0, 10, 20, 30, 40], complexity: vec![fallow_types::extract::FunctionComplexity {
2166 name: "doStuff".into(),
2167 line: 1,
2168 col: 0,
2169 cyclomatic: 7,
2170 cognitive: 4,
2171 line_count: 5,
2172 param_count: 0,
2173 react_hook_count: 0,
2174 react_jsx_max_depth: 0,
2175 react_prop_count: 0,
2176 source_hash: None,
2177 contributions: Vec::new(),
2178 }],
2179 };
2180
2181 let (cyc, cog, funcs, lines) = aggregate_complexity(&module);
2182 assert_eq!(cyc, 7);
2183 assert_eq!(cog, 4);
2184 assert_eq!(funcs, 1);
2185 assert_eq!(lines, 5);
2186 }
2187
2188 #[test]
2189 #[expect(
2190 clippy::too_many_lines,
2191 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
2192 )]
2193 fn aggregate_complexity_multiple_functions() {
2194 let module = crate::source::ModuleInfo {
2195 file_id: crate::discover::FileId(0),
2196 exports: vec![],
2197 imports: vec![],
2198 re_exports: vec![],
2199 dynamic_imports: vec![],
2200 dynamic_import_patterns: vec![],
2201 require_calls: vec![],
2202 package_path_references: Box::default(),
2203 member_accesses: vec![],
2204 semantic_facts: Box::default(),
2205 whole_object_uses: Box::default(),
2206 has_cjs_exports: false,
2207 has_angular_component_template_url: false,
2208 content_hash: 0,
2209 suppressions: vec![],
2210 unknown_suppression_kinds: vec![],
2211 unused_import_bindings: vec![],
2212 type_referenced_import_bindings: vec![],
2213 value_referenced_import_bindings: vec![],
2214 flag_uses: vec![],
2215 class_heritage: vec![],
2216 exported_factory_returns: Box::default(),
2217 type_member_types: Box::default(),
2218 injection_tokens: vec![],
2219 local_type_declarations: Vec::new(),
2220 public_signature_type_references: Vec::new(),
2221 namespace_object_aliases: Vec::new(),
2222 iconify_prefixes: Vec::new(),
2223 iconify_icon_names: Vec::new(),
2224 auto_import_candidates: Vec::new(),
2225 directives: Vec::new(),
2226 client_only_dynamic_import_spans: Vec::new(),
2227 security_sinks: Vec::new(),
2228 security_sinks_skipped: 0,
2229 security_unresolved_callee_sites: Vec::new(),
2230 tainted_bindings: Vec::new(),
2231 sanitized_sink_args: Vec::new(),
2232 security_control_sites: Vec::new(),
2233 callee_uses: Vec::new(),
2234 misplaced_directives: Vec::new(),
2235 inline_server_action_exports: Vec::new(),
2236 di_key_sites: Vec::new(),
2237 has_dynamic_provide: false,
2238 referenced_import_bindings: Vec::new(),
2239 component_props: Vec::new(),
2240 has_props_attrs_fallthrough: false,
2241 has_define_expose: false,
2242 has_define_model: false,
2243 has_unharvestable_props: false,
2244 component_emits: Vec::new(),
2245 angular_inputs: Vec::new(),
2246 angular_outputs: Vec::new(),
2247 has_unharvestable_emits: false,
2248 has_dynamic_emit: false,
2249 has_emit_whole_object_use: false,
2250 load_return_keys: Vec::new(),
2251 has_unharvestable_load: false,
2252 has_load_data_whole_use: false,
2253 has_page_data_store_whole_use: false,
2254 component_functions: Vec::new(),
2255 react_props: Vec::new(),
2256 hook_uses: Vec::new(),
2257 render_edges: Vec::new(),
2258 svelte_dispatched_events: Vec::new(),
2259 svelte_listened_events: Vec::new(),
2260 angular_component_selectors: Vec::new(),
2261 registered_custom_elements: Vec::new(),
2262 used_custom_element_tags: Vec::new(),
2263 angular_used_selectors: Vec::new(),
2264 angular_entry_component_refs: Vec::new(),
2265 has_dynamic_component_render: false,
2266 has_dynamic_dispatch: false,
2267 line_offsets: vec![0, 10, 20], complexity: vec![
2269 fallow_types::extract::FunctionComplexity {
2270 name: "a".into(),
2271 line: 1,
2272 col: 0,
2273 cyclomatic: 3,
2274 cognitive: 2,
2275 line_count: 1,
2276 param_count: 0,
2277 react_hook_count: 0,
2278 react_jsx_max_depth: 0,
2279 react_prop_count: 0,
2280 source_hash: None,
2281 contributions: Vec::new(),
2282 },
2283 fallow_types::extract::FunctionComplexity {
2284 name: "b".into(),
2285 line: 2,
2286 col: 0,
2287 cyclomatic: 5,
2288 cognitive: 8,
2289 line_count: 2,
2290 param_count: 0,
2291 react_hook_count: 0,
2292 react_jsx_max_depth: 0,
2293 react_prop_count: 0,
2294 source_hash: None,
2295 contributions: Vec::new(),
2296 },
2297 ],
2298 };
2299
2300 let (cyc, cog, funcs, lines) = aggregate_complexity(&module);
2301 assert_eq!(cyc, 8);
2302 assert_eq!(cog, 10);
2303 assert_eq!(funcs, 2);
2304 assert_eq!(lines, 3);
2305 }
2306
2307 #[test]
2308 fn count_unused_exports_empty() {
2309 let exports: Vec<crate::results::UnusedExportFinding> = vec![];
2310 let map = count_unused_exports_by_path(&exports);
2311 assert!(map.is_empty());
2312 }
2313
2314 #[test]
2315 fn count_unused_exports_groups_by_path() {
2316 let exports = vec![
2317 crate::results::UnusedExportFinding::with_actions(crate::results::UnusedExport {
2318 path: std::path::PathBuf::from("/src/a.ts"),
2319 export_name: "foo".into(),
2320 is_type_only: false,
2321 line: 1,
2322 col: 0,
2323 span_start: 0,
2324 is_re_export: false,
2325 }),
2326 crate::results::UnusedExportFinding::with_actions(crate::results::UnusedExport {
2327 path: std::path::PathBuf::from("/src/a.ts"),
2328 export_name: "bar".into(),
2329 is_type_only: false,
2330 line: 5,
2331 col: 0,
2332 span_start: 40,
2333 is_re_export: false,
2334 }),
2335 crate::results::UnusedExportFinding::with_actions(crate::results::UnusedExport {
2336 path: std::path::PathBuf::from("/src/b.ts"),
2337 export_name: "baz".into(),
2338 is_type_only: false,
2339 line: 1,
2340 col: 0,
2341 span_start: 0,
2342 is_re_export: false,
2343 }),
2344 ];
2345 let map = count_unused_exports_by_path(&exports);
2346 assert_eq!(map.get(std::path::Path::new("/src/a.ts")).copied(), Some(2));
2347 assert_eq!(map.get(std::path::Path::new("/src/b.ts")).copied(), Some(1));
2348 }
2349
2350 #[test]
2351 fn dead_code_ratio_all_value_exports_unused() {
2352 let unused_files = rustc_hash::FxHashSet::default();
2353 let path = std::path::Path::new("/src/foo.ts");
2354
2355 let exports = vec![
2356 fallow_graph::graph::ExportSymbol {
2357 name: crate::source::ExportName::Named("a".into()),
2358 is_type_only: false,
2359 is_side_effect_used: false,
2360 visibility: crate::source::VisibilityTag::None,
2361 expected_unused_reason: None,
2362 span: oxc_span::Span::empty(0),
2363 references: vec![],
2364 members: vec![],
2365 },
2366 fallow_graph::graph::ExportSymbol {
2367 name: crate::source::ExportName::Named("b".into()),
2368 is_type_only: false,
2369 is_side_effect_used: false,
2370 visibility: crate::source::VisibilityTag::None,
2371 expected_unused_reason: None,
2372 span: oxc_span::Span::empty(0),
2373 references: vec![],
2374 members: vec![],
2375 },
2376 ];
2377
2378 let mut unused_map: rustc_hash::FxHashMap<&std::path::Path, usize> =
2379 rustc_hash::FxHashMap::default();
2380 unused_map.insert(path, 2);
2381
2382 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
2383 assert!((ratio - 1.0).abs() < f64::EPSILON);
2384 }
2385
2386 #[test]
2387 fn dead_code_ratio_clamped_when_unused_exceeds_value_exports() {
2388 let unused_files = rustc_hash::FxHashSet::default();
2389 let path = std::path::Path::new("/src/foo.ts");
2390
2391 let exports = vec![fallow_graph::graph::ExportSymbol {
2392 name: crate::source::ExportName::Named("a".into()),
2393 is_type_only: false,
2394 is_side_effect_used: false,
2395 visibility: crate::source::VisibilityTag::None,
2396 expected_unused_reason: None,
2397 span: oxc_span::Span::empty(0),
2398 references: vec![],
2399 members: vec![],
2400 }];
2401
2402 let mut unused_map: rustc_hash::FxHashMap<&std::path::Path, usize> =
2403 rustc_hash::FxHashMap::default();
2404 unused_map.insert(path, 5);
2405
2406 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
2407 assert!((ratio - 1.0).abs() < f64::EPSILON);
2408 }
2409
2410 #[test]
2411 fn dead_code_ratio_no_unused_exports_for_path() {
2412 let unused_files = rustc_hash::FxHashSet::default();
2413 let path = std::path::Path::new("/src/clean.ts");
2414
2415 let exports = vec![fallow_graph::graph::ExportSymbol {
2416 name: crate::source::ExportName::Named("used".into()),
2417 is_type_only: false,
2418 is_side_effect_used: false,
2419 visibility: crate::source::VisibilityTag::None,
2420 expected_unused_reason: None,
2421 span: oxc_span::Span::empty(0),
2422 references: vec![],
2423 members: vec![],
2424 }];
2425
2426 let unused_map = rustc_hash::FxHashMap::default();
2427 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
2428 assert!(ratio.abs() < f64::EPSILON);
2429 }
2430
2431 #[test]
2432 fn complexity_density_zero_cyclomatic_with_lines() {
2433 let result = compute_complexity_density(0, 100);
2434 assert!(result.abs() < f64::EPSILON);
2435 }
2436
2437 #[test]
2438 fn complexity_density_single_line() {
2439 let result = compute_complexity_density(1, 1);
2440 assert!((result - 1.0).abs() < f64::EPSILON);
2441 }
2442
2443 #[test]
2444 fn maintainability_only_complexity_penalty() {
2445 let result = compute_maintainability_index(3.0, 0.0, 0, 100);
2446 assert!((result - 10.0).abs() < f64::EPSILON);
2447 }
2448
2449 #[test]
2450 fn maintainability_only_dead_code_penalty() {
2451 let result = compute_maintainability_index(0.0, 0.5, 0, 100);
2452 assert!((result - 90.0).abs() < f64::EPSILON);
2453 }
2454
2455 #[test]
2456 fn maintainability_fan_out_one() {
2457 let result = compute_maintainability_index(0.0, 0.0, 1, 100);
2458 let expected = 2.0_f64.ln().mul_add(-4.0, 100.0);
2459 assert!((result - expected).abs() < 0.01);
2460 }
2461
2462 #[test]
2463 fn maintainability_all_penalties_maxed() {
2464 let result = compute_maintainability_index(10.0, 1.0, 1000, 200);
2465 assert!(result.abs() < f64::EPSILON);
2466 }
2467
2468 #[test]
2469 fn count_unused_exports_single_file_single_export() {
2470 let exports = vec![crate::results::UnusedExportFinding::with_actions(
2471 crate::results::UnusedExport {
2472 path: std::path::PathBuf::from("/src/only.ts"),
2473 export_name: "lonely".into(),
2474 is_type_only: false,
2475 line: 1,
2476 col: 0,
2477 span_start: 0,
2478 is_re_export: false,
2479 },
2480 )];
2481 let map = count_unused_exports_by_path(&exports);
2482 assert_eq!(map.len(), 1);
2483 assert_eq!(
2484 map.get(std::path::Path::new("/src/only.ts")).copied(),
2485 Some(1)
2486 );
2487 }
2488
2489 fn build_test_graph(
2491 files: &[crate::discover::DiscoveredFile],
2492 entry_point_paths: &[std::path::PathBuf],
2493 resolved_modules: &[fallow_graph::resolve::ResolvedModule],
2494 ) -> fallow_graph::graph::ModuleGraph {
2495 let entry_points: Vec<crate::discover::EntryPoint> = entry_point_paths
2496 .iter()
2497 .map(|p| crate::discover::EntryPoint {
2498 path: p.clone(),
2499 source: crate::discover::EntryPointSource::PackageJsonMain,
2500 })
2501 .collect();
2502 fallow_graph::graph::ModuleGraph::build(resolved_modules, &entry_points, files)
2503 }
2504
2505 fn make_module_info(
2507 file_id: u32,
2508 line_count: usize,
2509 functions: Vec<fallow_types::extract::FunctionComplexity>,
2510 ) -> crate::source::ModuleInfo {
2511 crate::source::ModuleInfo {
2512 file_id: crate::discover::FileId(file_id),
2513 exports: vec![],
2514 imports: vec![],
2515 re_exports: vec![],
2516 dynamic_imports: vec![],
2517 dynamic_import_patterns: vec![],
2518 require_calls: vec![],
2519 package_path_references: Box::default(),
2520 member_accesses: vec![],
2521 semantic_facts: Box::default(),
2522 whole_object_uses: Box::default(),
2523 has_cjs_exports: false,
2524 has_angular_component_template_url: false,
2525 content_hash: 0,
2526 suppressions: vec![],
2527 unknown_suppression_kinds: vec![],
2528 unused_import_bindings: vec![],
2529 type_referenced_import_bindings: vec![],
2530 value_referenced_import_bindings: vec![],
2531 line_offsets: (0..line_count).map(|i| (i * 10) as u32).collect(),
2532 complexity: functions,
2533 flag_uses: vec![],
2534 class_heritage: vec![],
2535 exported_factory_returns: Box::default(),
2536 type_member_types: Box::default(),
2537 injection_tokens: vec![],
2538 local_type_declarations: Vec::new(),
2539 public_signature_type_references: Vec::new(),
2540 namespace_object_aliases: Vec::new(),
2541 iconify_prefixes: Vec::new(),
2542 iconify_icon_names: Vec::new(),
2543 auto_import_candidates: Vec::new(),
2544 directives: Vec::new(),
2545 client_only_dynamic_import_spans: Vec::new(),
2546 security_sinks: Vec::new(),
2547 security_sinks_skipped: 0,
2548 security_unresolved_callee_sites: Vec::new(),
2549 tainted_bindings: Vec::new(),
2550 sanitized_sink_args: Vec::new(),
2551 security_control_sites: Vec::new(),
2552 callee_uses: Vec::new(),
2553 misplaced_directives: Vec::new(),
2554 inline_server_action_exports: Vec::new(),
2555 di_key_sites: Vec::new(),
2556 has_dynamic_provide: false,
2557 referenced_import_bindings: Vec::new(),
2558 component_props: Vec::new(),
2559 has_props_attrs_fallthrough: false,
2560 has_define_expose: false,
2561 has_define_model: false,
2562 has_unharvestable_props: false,
2563 component_emits: Vec::new(),
2564 angular_inputs: Vec::new(),
2565 angular_outputs: Vec::new(),
2566 has_unharvestable_emits: false,
2567 has_dynamic_emit: false,
2568 has_emit_whole_object_use: false,
2569 load_return_keys: Vec::new(),
2570 has_unharvestable_load: false,
2571 has_load_data_whole_use: false,
2572 has_page_data_store_whole_use: false,
2573 component_functions: Vec::new(),
2574 react_props: Vec::new(),
2575 hook_uses: Vec::new(),
2576 render_edges: Vec::new(),
2577 svelte_dispatched_events: Vec::new(),
2578 svelte_listened_events: Vec::new(),
2579 angular_component_selectors: Vec::new(),
2580 registered_custom_elements: Vec::new(),
2581 used_custom_element_tags: Vec::new(),
2582 angular_used_selectors: Vec::new(),
2583 angular_entry_component_refs: Vec::new(),
2584 has_dynamic_component_render: false,
2585 has_dynamic_dispatch: false,
2586 }
2587 }
2588
2589 fn make_file_score(path: &str, maintainability_index: f64, crap_max: f64) -> FileHealthScore {
2590 FileHealthScore {
2591 path: std::path::PathBuf::from(path),
2592 fan_in: 0,
2593 fan_out: 0,
2594 dead_code_ratio: 0.0,
2595 complexity_density: 0.0,
2596 maintainability_index,
2597 total_cyclomatic: 0,
2598 total_cognitive: 0,
2599 function_count: 1,
2600 lines: 1,
2601 crap_max,
2602 crap_above_threshold: usize::from(crap_max >= CRAP_THRESHOLD),
2603 }
2604 }
2605
2606 #[test]
2607 fn file_score_crap_concern_tracks_crap_risk_bands() {
2608 assert!((file_score_crap_concern(0.0) - 0.0).abs() < f64::EPSILON);
2609 assert!((file_score_crap_concern(15.0) - 45.0).abs() < f64::EPSILON);
2610 assert!((file_score_crap_concern(CRAP_THRESHOLD) - 75.0).abs() < f64::EPSILON);
2611 assert!((file_score_crap_concern(100.0) - 100.0).abs() < f64::EPSILON);
2612 assert!((file_score_crap_concern(552.0) - 100.0).abs() < f64::EPSILON);
2613 }
2614
2615 #[test]
2616 fn file_score_concern_axis_labels_dominant_signal() {
2617 let risk_driven = make_file_score("/src/risk.ts", 84.8, 552.0);
2618 assert_eq!(
2619 file_score_concern_axis(&risk_driven),
2620 FileScoreConcern::Risk
2621 );
2622 assert_eq!(file_score_concern_axis(&risk_driven).label(), "risk");
2623
2624 let structure_driven = make_file_score("/src/structure.ts", 30.0, 8.0);
2625 assert_eq!(
2626 file_score_concern_axis(&structure_driven),
2627 FileScoreConcern::Structural
2628 );
2629 assert_eq!(
2630 file_score_concern_axis(&structure_driven).label(),
2631 "structure"
2632 );
2633
2634 let no_risk = make_file_score("/src/clean.ts", 100.0, 0.0);
2635 assert_eq!(
2636 file_score_concern_axis(&no_risk),
2637 FileScoreConcern::Structural
2638 );
2639 }
2640
2641 #[test]
2642 fn file_score_triage_sort_prioritizes_high_crap_over_slightly_lower_mi() {
2643 let low_mi_low_risk = make_file_score("/src/low-mi-low-risk.ts", 81.7, 2.0);
2644 let higher_mi_high_risk = make_file_score("/src/higher-mi-high-risk.ts", 84.8, 552.0);
2645
2646 let mut scores = [low_mi_low_risk, higher_mi_high_risk];
2647 scores.sort_by(compare_file_score_triage);
2648
2649 assert_eq!(
2650 scores[0].path,
2651 std::path::Path::new("/src/higher-mi-high-risk.ts")
2652 );
2653 assert_eq!(
2654 scores[1].path,
2655 std::path::Path::new("/src/low-mi-low-risk.ts")
2656 );
2657 }
2658
2659 #[test]
2660 fn file_score_triage_sort_orders_saturated_crap_by_raw_crap_descending() {
2661 let lower_crap_worse_mi = make_file_score("/src/a.ts", 84.8, 106.0);
2662 let higher_crap_better_mi = make_file_score("/src/b.ts", 96.7, 552.0);
2663
2664 let mut scores = [lower_crap_worse_mi, higher_crap_better_mi];
2665 scores.sort_by(compare_file_score_triage);
2666
2667 assert_eq!(scores[0].path, std::path::Path::new("/src/b.ts"));
2668 assert_eq!(scores[1].path, std::path::Path::new("/src/a.ts"));
2669 }
2670
2671 #[test]
2672 fn file_score_triage_sort_uses_mi_crap_and_path_tie_breakers() {
2673 let mut scores = [
2674 make_file_score("/src/b.ts", 70.0, 1.0),
2675 make_file_score("/src/a.ts", 70.0, 1.0),
2676 make_file_score("/src/higher-crap.ts", 70.0, 2.0),
2677 make_file_score("/src/lower-concern.ts", 80.0, 1.0),
2678 ];
2679
2680 scores.sort_by(compare_file_score_triage);
2681
2682 let paths: Vec<_> = scores.iter().map(|score| score.path.as_path()).collect();
2683 assert_eq!(
2684 paths,
2685 vec![
2686 std::path::Path::new("/src/higher-crap.ts"),
2687 std::path::Path::new("/src/a.ts"),
2688 std::path::Path::new("/src/b.ts"),
2689 std::path::Path::new("/src/lower-concern.ts"),
2690 ]
2691 );
2692 }
2693
2694 #[test]
2695 fn compute_file_scores_empty_graph() {
2696 let files: Vec<crate::discover::DiscoveredFile> = vec![];
2697 let graph = build_test_graph(&files, &[], &[]);
2698 let modules: Vec<crate::source::ModuleInfo> = vec![];
2699 let file_paths = rustc_hash::FxHashMap::default();
2700
2701 let output = crate::results::DeadCodeAnalysisArtifacts {
2702 results: fallow_types::results::AnalysisResults::default(),
2703 timings: None,
2704 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2705 modules: None,
2706 files: None,
2707 script_used_packages: rustc_hash::FxHashSet::default(),
2708 file_hashes: rustc_hash::FxHashMap::default(),
2709 };
2710
2711 let result = compute_file_scores(
2712 &modules,
2713 &file_paths,
2714 None,
2715 output,
2716 None,
2717 std::path::Path::new("/project"),
2718 )
2719 .unwrap();
2720 assert!(result.scores.is_empty());
2721 assert!(result.circular_files.is_empty());
2722 assert!(result.top_complex_fns.is_empty());
2723 assert!(result.entry_points.is_empty());
2724 assert_eq!(result.analysis_counts.total_exports, 0);
2725 assert_eq!(result.analysis_counts.dead_files, 0);
2726 }
2727
2728 #[test]
2729 fn compute_file_scores_no_graph_returns_error() {
2730 let modules: Vec<crate::source::ModuleInfo> = vec![];
2731 let file_paths = rustc_hash::FxHashMap::default();
2732
2733 let output = crate::results::DeadCodeAnalysisArtifacts {
2734 results: fallow_types::results::AnalysisResults::default(),
2735 timings: None,
2736 graph: None,
2737 modules: None,
2738 files: None,
2739 script_used_packages: rustc_hash::FxHashSet::default(),
2740 file_hashes: rustc_hash::FxHashMap::default(),
2741 };
2742
2743 let result = compute_file_scores(
2744 &modules,
2745 &file_paths,
2746 None,
2747 output,
2748 None,
2749 std::path::Path::new("/project"),
2750 );
2751 assert!(result.is_err());
2752 match result {
2753 Err(msg) => assert_eq!(msg, "graph not available"),
2754 Ok(_) => panic!("expected error"),
2755 }
2756 }
2757
2758 #[test]
2759 fn compute_file_scores_single_file_with_function() {
2760 let path_a = std::path::PathBuf::from("/src/a.ts");
2761 let files = vec![crate::discover::DiscoveredFile {
2762 id: crate::discover::FileId(0),
2763 path: path_a.clone(),
2764 size_bytes: 100,
2765 }];
2766
2767 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
2768 file_id: crate::discover::FileId(0),
2769 path: path_a.clone(),
2770 exports: vec![fallow_types::extract::ExportInfo {
2771 name: crate::source::ExportName::Named("foo".into()),
2772 local_name: None,
2773 is_type_only: false,
2774 visibility: crate::source::VisibilityTag::None,
2775 expected_unused_reason: None,
2776 span: oxc_span::Span::empty(0),
2777 members: vec![],
2778 is_side_effect_used: false,
2779 super_class: None,
2780 }],
2781 ..Default::default()
2782 }];
2783
2784 let graph = build_test_graph(&files, std::slice::from_ref(&path_a), &resolved_modules);
2785
2786 let modules = vec![make_module_info(
2787 0,
2788 10,
2789 vec![fallow_types::extract::FunctionComplexity {
2790 name: "foo".into(),
2791 line: 1,
2792 col: 0,
2793 cyclomatic: 5,
2794 cognitive: 3,
2795 line_count: 10,
2796 param_count: 0,
2797 react_hook_count: 0,
2798 react_jsx_max_depth: 0,
2799 react_prop_count: 0,
2800 source_hash: None,
2801 contributions: Vec::new(),
2802 }],
2803 )];
2804
2805 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
2806 rustc_hash::FxHashMap::default();
2807 file_paths.insert(crate::discover::FileId(0), &files[0].path);
2808
2809 let output = crate::results::DeadCodeAnalysisArtifacts {
2810 results: fallow_types::results::AnalysisResults::default(),
2811 timings: None,
2812 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2813 modules: None,
2814 files: None,
2815 script_used_packages: rustc_hash::FxHashSet::default(),
2816 file_hashes: rustc_hash::FxHashMap::default(),
2817 };
2818
2819 let result = compute_file_scores(
2820 &modules,
2821 &file_paths,
2822 None,
2823 output,
2824 None,
2825 std::path::Path::new("/project"),
2826 )
2827 .unwrap();
2828 assert_eq!(result.scores.len(), 1);
2829
2830 let score = &result.scores[0];
2831 assert_eq!(score.path, path_a);
2832 assert_eq!(score.total_cyclomatic, 5);
2833 assert_eq!(score.total_cognitive, 3);
2834 assert_eq!(score.function_count, 1);
2835 assert_eq!(score.lines, 10);
2836 assert!((score.complexity_density - 0.5).abs() < f64::EPSILON);
2837 assert!(score.dead_code_ratio.abs() < f64::EPSILON);
2838 assert!(result.entry_points.contains(&path_a));
2839 }
2840
2841 #[test]
2842 fn compute_file_scores_excludes_barrel_files() {
2843 let path_a = std::path::PathBuf::from("/src/index.ts");
2844 let files = vec![crate::discover::DiscoveredFile {
2845 id: crate::discover::FileId(0),
2846 path: path_a.clone(),
2847 size_bytes: 50,
2848 }];
2849
2850 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
2851 file_id: crate::discover::FileId(0),
2852 path: path_a.clone(),
2853 ..Default::default()
2854 }];
2855
2856 let graph = build_test_graph(&files, std::slice::from_ref(&path_a), &resolved_modules);
2857
2858 let modules = vec![make_module_info(0, 5, vec![])];
2859
2860 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
2861 rustc_hash::FxHashMap::default();
2862 file_paths.insert(crate::discover::FileId(0), &files[0].path);
2863
2864 let output = crate::results::DeadCodeAnalysisArtifacts {
2865 results: fallow_types::results::AnalysisResults::default(),
2866 timings: None,
2867 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2868 modules: None,
2869 files: None,
2870 script_used_packages: rustc_hash::FxHashSet::default(),
2871 file_hashes: rustc_hash::FxHashMap::default(),
2872 };
2873
2874 let result = compute_file_scores(
2875 &modules,
2876 &file_paths,
2877 None,
2878 output,
2879 None,
2880 std::path::Path::new("/project"),
2881 )
2882 .unwrap();
2883 assert!(result.scores.is_empty());
2884 }
2885
2886 #[test]
2887 fn compute_file_scores_changed_since_filter() {
2888 let path_a = std::path::PathBuf::from("/src/a.ts");
2889 let path_b = std::path::PathBuf::from("/src/b.ts");
2890 let files = vec![
2891 crate::discover::DiscoveredFile {
2892 id: crate::discover::FileId(0),
2893 path: path_a.clone(),
2894 size_bytes: 100,
2895 },
2896 crate::discover::DiscoveredFile {
2897 id: crate::discover::FileId(1),
2898 path: path_b.clone(),
2899 size_bytes: 100,
2900 },
2901 ];
2902
2903 let resolved_modules = vec![
2904 fallow_graph::resolve::ResolvedModule {
2905 file_id: crate::discover::FileId(0),
2906 path: path_a,
2907 ..Default::default()
2908 },
2909 fallow_graph::resolve::ResolvedModule {
2910 file_id: crate::discover::FileId(1),
2911 path: path_b.clone(),
2912 ..Default::default()
2913 },
2914 ];
2915
2916 let graph = build_test_graph(&files, &[], &resolved_modules);
2917
2918 let modules = vec![
2919 make_module_info(
2920 0,
2921 10,
2922 vec![fallow_types::extract::FunctionComplexity {
2923 name: "fn_a".into(),
2924 line: 1,
2925 col: 0,
2926 cyclomatic: 2,
2927 cognitive: 1,
2928 line_count: 10,
2929 param_count: 0,
2930 react_hook_count: 0,
2931 react_jsx_max_depth: 0,
2932 react_prop_count: 0,
2933 source_hash: None,
2934 contributions: Vec::new(),
2935 }],
2936 ),
2937 make_module_info(
2938 1,
2939 10,
2940 vec![fallow_types::extract::FunctionComplexity {
2941 name: "fn_b".into(),
2942 line: 1,
2943 col: 0,
2944 cyclomatic: 3,
2945 cognitive: 2,
2946 line_count: 10,
2947 param_count: 0,
2948 react_hook_count: 0,
2949 react_jsx_max_depth: 0,
2950 react_prop_count: 0,
2951 source_hash: None,
2952 contributions: Vec::new(),
2953 }],
2954 ),
2955 ];
2956
2957 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
2958 rustc_hash::FxHashMap::default();
2959 file_paths.insert(crate::discover::FileId(0), &files[0].path);
2960 file_paths.insert(crate::discover::FileId(1), &files[1].path);
2961
2962 let path_b_check = std::path::PathBuf::from("/src/b.ts");
2963 let mut changed = rustc_hash::FxHashSet::default();
2964 changed.insert(path_b);
2965
2966 let output = crate::results::DeadCodeAnalysisArtifacts {
2967 results: fallow_types::results::AnalysisResults::default(),
2968 timings: None,
2969 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2970 modules: None,
2971 files: None,
2972 script_used_packages: rustc_hash::FxHashSet::default(),
2973 file_hashes: rustc_hash::FxHashMap::default(),
2974 };
2975
2976 let result = compute_file_scores(
2977 &modules,
2978 &file_paths,
2979 Some(&changed),
2980 output,
2981 None,
2982 std::path::Path::new("/project"),
2983 )
2984 .unwrap();
2985 assert_eq!(result.scores.len(), 1);
2986 assert_eq!(result.scores[0].path, path_b_check);
2987 }
2988
2989 #[test]
2990 fn compute_file_scores_sorted_by_triage_concern() {
2991 let path_a = std::path::PathBuf::from("/src/a.ts");
2992 let path_b = std::path::PathBuf::from("/src/b.ts");
2993 let files = vec![
2994 crate::discover::DiscoveredFile {
2995 id: crate::discover::FileId(0),
2996 path: path_a.clone(),
2997 size_bytes: 100,
2998 },
2999 crate::discover::DiscoveredFile {
3000 id: crate::discover::FileId(1),
3001 path: path_b.clone(),
3002 size_bytes: 100,
3003 },
3004 ];
3005
3006 let resolved_modules = vec![
3007 fallow_graph::resolve::ResolvedModule {
3008 file_id: crate::discover::FileId(0),
3009 path: path_a.clone(),
3010 ..Default::default()
3011 },
3012 fallow_graph::resolve::ResolvedModule {
3013 file_id: crate::discover::FileId(1),
3014 path: path_b,
3015 ..Default::default()
3016 },
3017 ];
3018
3019 let graph = build_test_graph(&files, &[], &resolved_modules);
3020
3021 let modules = vec![
3022 make_module_info(
3023 0,
3024 10,
3025 vec![fallow_types::extract::FunctionComplexity {
3026 name: "complex_fn".into(),
3027 line: 1,
3028 col: 0,
3029 cyclomatic: 30,
3030 cognitive: 20,
3031 line_count: 10,
3032 param_count: 0,
3033 react_hook_count: 0,
3034 react_jsx_max_depth: 0,
3035 react_prop_count: 0,
3036 source_hash: None,
3037 contributions: Vec::new(),
3038 }],
3039 ),
3040 make_module_info(
3041 1,
3042 100,
3043 vec![fallow_types::extract::FunctionComplexity {
3044 name: "simple_fn".into(),
3045 line: 1,
3046 col: 0,
3047 cyclomatic: 1,
3048 cognitive: 0,
3049 line_count: 100,
3050 param_count: 0,
3051 react_hook_count: 0,
3052 react_jsx_max_depth: 0,
3053 react_prop_count: 0,
3054 source_hash: None,
3055 contributions: Vec::new(),
3056 }],
3057 ),
3058 ];
3059
3060 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3061 rustc_hash::FxHashMap::default();
3062 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3063 file_paths.insert(crate::discover::FileId(1), &files[1].path);
3064
3065 let output = crate::results::DeadCodeAnalysisArtifacts {
3066 results: fallow_types::results::AnalysisResults::default(),
3067 timings: None,
3068 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3069 modules: None,
3070 files: None,
3071 script_used_packages: rustc_hash::FxHashSet::default(),
3072 file_hashes: rustc_hash::FxHashMap::default(),
3073 };
3074
3075 let result = compute_file_scores(
3076 &modules,
3077 &file_paths,
3078 None,
3079 output,
3080 None,
3081 std::path::Path::new("/project"),
3082 )
3083 .unwrap();
3084 assert_eq!(result.scores.len(), 2);
3085 assert!(result.scores[0].maintainability_index <= result.scores[1].maintainability_index);
3086 assert_eq!(result.scores[0].path, path_a);
3087 }
3088
3089 #[test]
3090 fn compute_file_scores_with_unused_file_populates_evidence() {
3091 let path_a = std::path::PathBuf::from("/src/unused.ts");
3092 let files = vec![crate::discover::DiscoveredFile {
3093 id: crate::discover::FileId(0),
3094 path: path_a.clone(),
3095 size_bytes: 100,
3096 }];
3097
3098 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3099 file_id: crate::discover::FileId(0),
3100 path: path_a.clone(),
3101 exports: vec![fallow_types::extract::ExportInfo {
3102 name: crate::source::ExportName::Named("orphan".into()),
3103 local_name: None,
3104 is_type_only: false,
3105 visibility: crate::source::VisibilityTag::None,
3106 expected_unused_reason: None,
3107 span: oxc_span::Span::empty(0),
3108 members: vec![],
3109 is_side_effect_used: false,
3110 super_class: None,
3111 }],
3112 ..Default::default()
3113 }];
3114
3115 let graph = build_test_graph(&files, &[], &resolved_modules);
3116
3117 let modules = vec![make_module_info(
3118 0,
3119 10,
3120 vec![fallow_types::extract::FunctionComplexity {
3121 name: "orphan".into(),
3122 line: 1,
3123 col: 0,
3124 cyclomatic: 1,
3125 cognitive: 0,
3126 line_count: 10,
3127 param_count: 0,
3128 react_hook_count: 0,
3129 react_jsx_max_depth: 0,
3130 react_prop_count: 0,
3131 source_hash: None,
3132 contributions: Vec::new(),
3133 }],
3134 )];
3135
3136 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3137 rustc_hash::FxHashMap::default();
3138 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3139
3140 let mut results = fallow_types::results::AnalysisResults::default();
3141 results.unused_files.push(
3142 fallow_types::output_dead_code::UnusedFileFinding::with_actions(
3143 fallow_types::results::UnusedFile {
3144 path: path_a.clone(),
3145 },
3146 ),
3147 );
3148
3149 let output = crate::results::DeadCodeAnalysisArtifacts {
3150 results,
3151 timings: None,
3152 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3153 modules: None,
3154 files: None,
3155 script_used_packages: rustc_hash::FxHashSet::default(),
3156 file_hashes: rustc_hash::FxHashMap::default(),
3157 };
3158
3159 let result = compute_file_scores(
3160 &modules,
3161 &file_paths,
3162 None,
3163 output,
3164 None,
3165 std::path::Path::new("/project"),
3166 )
3167 .unwrap();
3168 assert_eq!(result.scores.len(), 1);
3169 assert!((result.scores[0].dead_code_ratio - 1.0).abs() < f64::EPSILON);
3170 assert!(result.unused_export_names.contains_key(&path_a));
3171 let names = &result.unused_export_names[&path_a];
3172 assert_eq!(names, &["orphan"]);
3173 assert_eq!(result.analysis_counts.dead_files, 1);
3174 }
3175
3176 #[test]
3177 #[expect(
3178 clippy::too_many_lines,
3179 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3180 )]
3181 fn compute_file_scores_tracks_top_complex_functions() {
3182 let path_a = std::path::PathBuf::from("/src/complex.ts");
3183 let files = vec![crate::discover::DiscoveredFile {
3184 id: crate::discover::FileId(0),
3185 path: path_a.clone(),
3186 size_bytes: 500,
3187 }];
3188
3189 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3190 file_id: crate::discover::FileId(0),
3191 path: path_a.clone(),
3192 ..Default::default()
3193 }];
3194
3195 let graph = build_test_graph(&files, &[], &resolved_modules);
3196
3197 let modules = vec![make_module_info(
3198 0,
3199 50,
3200 vec![
3201 fallow_types::extract::FunctionComplexity {
3202 name: "high".into(),
3203 line: 1,
3204 col: 0,
3205 cyclomatic: 10,
3206 cognitive: 20,
3207 line_count: 10,
3208 param_count: 0,
3209 react_hook_count: 0,
3210 react_jsx_max_depth: 0,
3211 react_prop_count: 0,
3212 source_hash: None,
3213 contributions: Vec::new(),
3214 },
3215 fallow_types::extract::FunctionComplexity {
3216 name: "medium".into(),
3217 line: 11,
3218 col: 0,
3219 cyclomatic: 5,
3220 cognitive: 10,
3221 line_count: 10,
3222 param_count: 0,
3223 react_hook_count: 0,
3224 react_jsx_max_depth: 0,
3225 react_prop_count: 0,
3226 source_hash: None,
3227 contributions: Vec::new(),
3228 },
3229 fallow_types::extract::FunctionComplexity {
3230 name: "low".into(),
3231 line: 21,
3232 col: 0,
3233 cyclomatic: 2,
3234 cognitive: 5,
3235 line_count: 10,
3236 param_count: 0,
3237 react_hook_count: 0,
3238 react_jsx_max_depth: 0,
3239 react_prop_count: 0,
3240 source_hash: None,
3241 contributions: Vec::new(),
3242 },
3243 fallow_types::extract::FunctionComplexity {
3244 name: "trivial".into(),
3245 line: 31,
3246 col: 0,
3247 cyclomatic: 1,
3248 cognitive: 1,
3249 line_count: 10,
3250 param_count: 0,
3251 react_hook_count: 0,
3252 react_jsx_max_depth: 0,
3253 react_prop_count: 0,
3254 source_hash: None,
3255 contributions: Vec::new(),
3256 },
3257 ],
3258 )];
3259
3260 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3261 rustc_hash::FxHashMap::default();
3262 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3263
3264 let output = crate::results::DeadCodeAnalysisArtifacts {
3265 results: fallow_types::results::AnalysisResults::default(),
3266 timings: None,
3267 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3268 modules: None,
3269 files: None,
3270 script_used_packages: rustc_hash::FxHashSet::default(),
3271 file_hashes: rustc_hash::FxHashMap::default(),
3272 };
3273
3274 let result = compute_file_scores(
3275 &modules,
3276 &file_paths,
3277 None,
3278 output,
3279 None,
3280 std::path::Path::new("/project"),
3281 )
3282 .unwrap();
3283 assert!(result.top_complex_fns.contains_key(&path_a));
3284 let top = &result.top_complex_fns[&path_a];
3285 assert_eq!(top.len(), 3);
3286 assert_eq!(top[0].0, "high");
3287 assert_eq!(top[0].2, 20);
3288 assert_eq!(top[1].0, "medium");
3289 assert_eq!(top[1].2, 10);
3290 assert_eq!(top[2].0, "low");
3291 assert_eq!(top[2].2, 5);
3292 }
3293
3294 #[test]
3295 #[expect(
3296 clippy::too_many_lines,
3297 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3298 )]
3299 fn compute_file_scores_with_circular_deps() {
3300 let path_a = std::path::PathBuf::from("/src/a.ts");
3301 let path_b = std::path::PathBuf::from("/src/b.ts");
3302 let files = vec![
3303 crate::discover::DiscoveredFile {
3304 id: crate::discover::FileId(0),
3305 path: path_a.clone(),
3306 size_bytes: 100,
3307 },
3308 crate::discover::DiscoveredFile {
3309 id: crate::discover::FileId(1),
3310 path: path_b.clone(),
3311 size_bytes: 100,
3312 },
3313 ];
3314
3315 let resolved_modules = vec![
3316 fallow_graph::resolve::ResolvedModule {
3317 file_id: crate::discover::FileId(0),
3318 path: path_a.clone(),
3319 ..Default::default()
3320 },
3321 fallow_graph::resolve::ResolvedModule {
3322 file_id: crate::discover::FileId(1),
3323 path: path_b.clone(),
3324 ..Default::default()
3325 },
3326 ];
3327
3328 let graph = build_test_graph(&files, &[], &resolved_modules);
3329
3330 let modules = vec![
3331 make_module_info(
3332 0,
3333 10,
3334 vec![fallow_types::extract::FunctionComplexity {
3335 name: "fn_a".into(),
3336 line: 1,
3337 col: 0,
3338 cyclomatic: 2,
3339 cognitive: 1,
3340 line_count: 10,
3341 param_count: 0,
3342 react_hook_count: 0,
3343 react_jsx_max_depth: 0,
3344 react_prop_count: 0,
3345 source_hash: None,
3346 contributions: Vec::new(),
3347 }],
3348 ),
3349 make_module_info(
3350 1,
3351 10,
3352 vec![fallow_types::extract::FunctionComplexity {
3353 name: "fn_b".into(),
3354 line: 1,
3355 col: 0,
3356 cyclomatic: 3,
3357 cognitive: 2,
3358 line_count: 10,
3359 param_count: 0,
3360 react_hook_count: 0,
3361 react_jsx_max_depth: 0,
3362 react_prop_count: 0,
3363 source_hash: None,
3364 contributions: Vec::new(),
3365 }],
3366 ),
3367 ];
3368
3369 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3370 rustc_hash::FxHashMap::default();
3371 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3372 file_paths.insert(crate::discover::FileId(1), &files[1].path);
3373
3374 let mut results = fallow_types::results::AnalysisResults::default();
3375 results.circular_dependencies.push(
3376 fallow_types::output_dead_code::CircularDependencyFinding::with_actions(
3377 fallow_types::results::CircularDependency {
3378 files: vec![path_a.clone(), path_b.clone()],
3379 length: 2,
3380 line: 1,
3381 col: 0,
3382 edges: Vec::new(),
3383 is_cross_package: false,
3384 },
3385 ),
3386 );
3387
3388 let output = crate::results::DeadCodeAnalysisArtifacts {
3389 results,
3390 timings: None,
3391 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3392 modules: None,
3393 files: None,
3394 script_used_packages: rustc_hash::FxHashSet::default(),
3395 file_hashes: rustc_hash::FxHashMap::default(),
3396 };
3397
3398 let result = compute_file_scores(
3399 &modules,
3400 &file_paths,
3401 None,
3402 output,
3403 None,
3404 std::path::Path::new("/project"),
3405 )
3406 .unwrap();
3407 assert!(result.circular_files.contains(&path_a));
3408 assert!(result.circular_files.contains(&path_b));
3409 assert!(result.cycle_members.contains_key(&path_a));
3410 assert_eq!(result.cycle_members[&path_a], vec![path_b.clone()]);
3411 assert!(result.cycle_members.contains_key(&path_b));
3412 assert_eq!(result.cycle_members[&path_b], vec![path_a]);
3413 assert_eq!(result.analysis_counts.circular_deps, 1);
3414 }
3415
3416 #[test]
3417 #[expect(
3418 clippy::too_many_lines,
3419 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3420 )]
3421 fn compute_file_scores_analysis_counts_unused_exports_and_types() {
3422 let path_a = std::path::PathBuf::from("/src/a.ts");
3423 let files = vec![crate::discover::DiscoveredFile {
3424 id: crate::discover::FileId(0),
3425 path: path_a.clone(),
3426 size_bytes: 100,
3427 }];
3428
3429 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3430 file_id: crate::discover::FileId(0),
3431 path: path_a.clone(),
3432 exports: vec![
3433 fallow_types::extract::ExportInfo {
3434 name: crate::source::ExportName::Named("foo".into()),
3435 local_name: None,
3436 is_type_only: false,
3437 visibility: crate::source::VisibilityTag::None,
3438 expected_unused_reason: None,
3439 span: oxc_span::Span::empty(0),
3440 members: vec![],
3441 is_side_effect_used: false,
3442 super_class: None,
3443 },
3444 fallow_types::extract::ExportInfo {
3445 name: crate::source::ExportName::Named("bar".into()),
3446 local_name: None,
3447 is_type_only: false,
3448 visibility: crate::source::VisibilityTag::None,
3449 expected_unused_reason: None,
3450 span: oxc_span::Span::empty(0),
3451 members: vec![],
3452 is_side_effect_used: false,
3453 super_class: None,
3454 },
3455 ],
3456 ..Default::default()
3457 }];
3458
3459 let graph = build_test_graph(&files, &[], &resolved_modules);
3460
3461 let mut module = make_module_info(
3462 0,
3463 10,
3464 vec![fallow_types::extract::FunctionComplexity {
3465 name: "fn_a".into(),
3466 line: 1,
3467 col: 0,
3468 cyclomatic: 1,
3469 cognitive: 0,
3470 line_count: 10,
3471 param_count: 0,
3472 react_hook_count: 0,
3473 react_jsx_max_depth: 0,
3474 react_prop_count: 0,
3475 source_hash: None,
3476 contributions: Vec::new(),
3477 }],
3478 );
3479 module.exports = vec![
3480 fallow_types::extract::ExportInfo {
3481 name: crate::source::ExportName::Named("foo".into()),
3482 local_name: None,
3483 is_type_only: false,
3484 visibility: crate::source::VisibilityTag::None,
3485 expected_unused_reason: None,
3486 span: oxc_span::Span::empty(0),
3487 members: vec![],
3488 is_side_effect_used: false,
3489 super_class: None,
3490 },
3491 fallow_types::extract::ExportInfo {
3492 name: crate::source::ExportName::Named("bar".into()),
3493 local_name: None,
3494 is_type_only: false,
3495 visibility: crate::source::VisibilityTag::None,
3496 expected_unused_reason: None,
3497 span: oxc_span::Span::empty(0),
3498 members: vec![],
3499 is_side_effect_used: false,
3500 super_class: None,
3501 },
3502 ];
3503 let modules = vec![module];
3504
3505 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3506 rustc_hash::FxHashMap::default();
3507 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3508
3509 let mut results = fallow_types::results::AnalysisResults::default();
3510 results.unused_exports.push(
3511 fallow_types::output_dead_code::UnusedExportFinding::with_actions(
3512 fallow_types::results::UnusedExport {
3513 path: path_a.clone(),
3514 export_name: "foo".into(),
3515 is_type_only: false,
3516 line: 1,
3517 col: 0,
3518 span_start: 0,
3519 is_re_export: false,
3520 },
3521 ),
3522 );
3523 results.unused_types.push(
3524 fallow_types::output_dead_code::UnusedTypeFinding::with_actions(
3525 fallow_types::results::UnusedExport {
3526 path: path_a,
3527 export_name: "MyType".into(),
3528 is_type_only: true,
3529 line: 5,
3530 col: 0,
3531 span_start: 40,
3532 is_re_export: false,
3533 },
3534 ),
3535 );
3536 results.unused_dependencies.push(
3537 fallow_types::output_dead_code::UnusedDependencyFinding::with_actions(
3538 fallow_types::results::UnusedDependency {
3539 package_name: "lodash".into(),
3540 location: fallow_types::results::DependencyLocation::Dependencies,
3541 path: std::path::PathBuf::from("/package.json"),
3542 line: 1,
3543 used_in_workspaces: Vec::new(),
3544 },
3545 ),
3546 );
3547
3548 let output = crate::results::DeadCodeAnalysisArtifacts {
3549 results,
3550 timings: None,
3551 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3552 modules: None,
3553 files: None,
3554 script_used_packages: rustc_hash::FxHashSet::default(),
3555 file_hashes: rustc_hash::FxHashMap::default(),
3556 };
3557
3558 let result = compute_file_scores(
3559 &modules,
3560 &file_paths,
3561 None,
3562 output,
3563 None,
3564 std::path::Path::new("/project"),
3565 )
3566 .unwrap();
3567 assert_eq!(result.analysis_counts.total_exports, 2);
3568 assert_eq!(result.analysis_counts.dead_exports, 2);
3569 assert_eq!(result.analysis_counts.unused_deps, 1);
3570 }
3571
3572 #[test]
3574 #[expect(
3575 clippy::too_many_lines,
3576 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3577 )]
3578 fn total_exports_counts_graph_modules_not_extraction_modules() {
3579 let path_a = std::path::PathBuf::from("/src/a.ts");
3580 let files = vec![crate::discover::DiscoveredFile {
3581 id: crate::discover::FileId(0),
3582 path: path_a.clone(),
3583 size_bytes: 100,
3584 }];
3585
3586 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3587 file_id: crate::discover::FileId(0),
3588 path: path_a.clone(),
3589 exports: vec![
3590 fallow_types::extract::ExportInfo {
3591 name: crate::source::ExportName::Named("foo".into()),
3592 local_name: None,
3593 is_type_only: false,
3594 visibility: crate::source::VisibilityTag::None,
3595 expected_unused_reason: None,
3596 span: oxc_span::Span::empty(0),
3597 members: vec![],
3598 is_side_effect_used: false,
3599 super_class: None,
3600 },
3601 fallow_types::extract::ExportInfo {
3602 name: crate::source::ExportName::Named("bar".into()),
3603 local_name: None,
3604 is_type_only: false,
3605 visibility: crate::source::VisibilityTag::None,
3606 expected_unused_reason: None,
3607 span: oxc_span::Span::empty(0),
3608 members: vec![],
3609 is_side_effect_used: false,
3610 super_class: None,
3611 },
3612 fallow_types::extract::ExportInfo {
3613 name: crate::source::ExportName::Named("baz".into()),
3614 local_name: None,
3615 is_type_only: false,
3616 visibility: crate::source::VisibilityTag::None,
3617 expected_unused_reason: None,
3618 span: oxc_span::Span::new(0, 0),
3619 members: vec![],
3620 is_side_effect_used: false,
3621 super_class: None,
3622 },
3623 ],
3624 ..Default::default()
3625 }];
3626
3627 let graph = build_test_graph(&files, &[], &resolved_modules);
3628
3629 let mut module = make_module_info(
3630 0,
3631 10,
3632 vec![fallow_types::extract::FunctionComplexity {
3633 name: "fn_a".into(),
3634 line: 1,
3635 col: 0,
3636 cyclomatic: 1,
3637 cognitive: 0,
3638 line_count: 10,
3639 param_count: 0,
3640 react_hook_count: 0,
3641 react_jsx_max_depth: 0,
3642 react_prop_count: 0,
3643 source_hash: None,
3644 contributions: Vec::new(),
3645 }],
3646 );
3647 module.exports = vec![
3648 fallow_types::extract::ExportInfo {
3649 name: crate::source::ExportName::Named("foo".into()),
3650 local_name: None,
3651 is_type_only: false,
3652 visibility: crate::source::VisibilityTag::None,
3653 expected_unused_reason: None,
3654 span: oxc_span::Span::empty(0),
3655 members: vec![],
3656 is_side_effect_used: false,
3657 super_class: None,
3658 },
3659 fallow_types::extract::ExportInfo {
3660 name: crate::source::ExportName::Named("bar".into()),
3661 local_name: None,
3662 is_type_only: false,
3663 visibility: crate::source::VisibilityTag::None,
3664 expected_unused_reason: None,
3665 span: oxc_span::Span::empty(0),
3666 members: vec![],
3667 is_side_effect_used: false,
3668 super_class: None,
3669 },
3670 ];
3671 let modules = vec![module];
3672
3673 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3674 rustc_hash::FxHashMap::default();
3675 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3676
3677 let mut results = fallow_types::results::AnalysisResults::default();
3678 for name in ["foo", "bar", "baz"] {
3679 results.unused_exports.push(
3680 fallow_types::output_dead_code::UnusedExportFinding::with_actions(
3681 fallow_types::results::UnusedExport {
3682 path: path_a.clone(),
3683 export_name: name.into(),
3684 is_type_only: false,
3685 line: 1,
3686 col: 0,
3687 span_start: 0,
3688 is_re_export: name == "baz",
3689 },
3690 ),
3691 );
3692 }
3693
3694 let output = crate::results::DeadCodeAnalysisArtifacts {
3695 results,
3696 timings: None,
3697 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3698 modules: None,
3699 files: None,
3700 script_used_packages: rustc_hash::FxHashSet::default(),
3701 file_hashes: rustc_hash::FxHashMap::default(),
3702 };
3703
3704 let result = compute_file_scores(
3705 &modules,
3706 &file_paths,
3707 None,
3708 output,
3709 None,
3710 std::path::Path::new("/project"),
3711 )
3712 .unwrap();
3713 assert_eq!(result.analysis_counts.total_exports, 3);
3714 assert_eq!(result.analysis_counts.dead_exports, 3);
3715 }
3716
3717 #[test]
3718 fn compute_file_scores_module_not_in_file_paths_skipped() {
3719 let path_a = std::path::PathBuf::from("/src/a.ts");
3720 let files = vec![crate::discover::DiscoveredFile {
3721 id: crate::discover::FileId(0),
3722 path: path_a.clone(),
3723 size_bytes: 100,
3724 }];
3725
3726 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3727 file_id: crate::discover::FileId(0),
3728 path: path_a,
3729 ..Default::default()
3730 }];
3731
3732 let graph = build_test_graph(&files, &[], &resolved_modules);
3733
3734 let modules = vec![make_module_info(
3735 0,
3736 10,
3737 vec![fallow_types::extract::FunctionComplexity {
3738 name: "fn_a".into(),
3739 line: 1,
3740 col: 0,
3741 cyclomatic: 2,
3742 cognitive: 1,
3743 line_count: 10,
3744 param_count: 0,
3745 react_hook_count: 0,
3746 react_jsx_max_depth: 0,
3747 react_prop_count: 0,
3748 source_hash: None,
3749 contributions: Vec::new(),
3750 }],
3751 )];
3752
3753 let file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3754 rustc_hash::FxHashMap::default();
3755
3756 let output = crate::results::DeadCodeAnalysisArtifacts {
3757 results: fallow_types::results::AnalysisResults::default(),
3758 timings: None,
3759 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3760 modules: None,
3761 files: None,
3762 script_used_packages: rustc_hash::FxHashSet::default(),
3763 file_hashes: rustc_hash::FxHashMap::default(),
3764 };
3765
3766 let result = compute_file_scores(
3767 &modules,
3768 &file_paths,
3769 None,
3770 output,
3771 None,
3772 std::path::Path::new("/project"),
3773 )
3774 .unwrap();
3775 assert!(result.scores.is_empty());
3776 }
3777
3778 #[test]
3779 fn compute_file_scores_mi_rounded_to_one_decimal() {
3780 let path_a = std::path::PathBuf::from("/src/a.ts");
3781 let files = vec![crate::discover::DiscoveredFile {
3782 id: crate::discover::FileId(0),
3783 path: path_a.clone(),
3784 size_bytes: 100,
3785 }];
3786
3787 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3788 file_id: crate::discover::FileId(0),
3789 path: path_a.clone(),
3790 ..Default::default()
3791 }];
3792
3793 let graph = build_test_graph(&files, std::slice::from_ref(&path_a), &resolved_modules);
3794
3795 let modules = vec![make_module_info(
3796 0,
3797 100,
3798 vec![fallow_types::extract::FunctionComplexity {
3799 name: "fn".into(),
3800 line: 1,
3801 col: 0,
3802 cyclomatic: 7,
3803 cognitive: 3,
3804 line_count: 100,
3805 param_count: 0,
3806 react_hook_count: 0,
3807 react_jsx_max_depth: 0,
3808 react_prop_count: 0,
3809 source_hash: None,
3810 contributions: Vec::new(),
3811 }],
3812 )];
3813
3814 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3815 rustc_hash::FxHashMap::default();
3816 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3817
3818 let output = crate::results::DeadCodeAnalysisArtifacts {
3819 results: fallow_types::results::AnalysisResults::default(),
3820 timings: None,
3821 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3822 modules: None,
3823 files: None,
3824 script_used_packages: rustc_hash::FxHashSet::default(),
3825 file_hashes: rustc_hash::FxHashMap::default(),
3826 };
3827
3828 let result = compute_file_scores(
3829 &modules,
3830 &file_paths,
3831 None,
3832 output,
3833 None,
3834 std::path::Path::new("/project"),
3835 )
3836 .unwrap();
3837 let mi = result.scores[0].maintainability_index;
3838 let rounded = (mi * 10.0).round() / 10.0;
3839 assert!((mi - rounded).abs() < f64::EPSILON);
3840 }
3841
3842 #[test]
3843 fn compute_file_scores_value_export_counts_tracked() {
3844 let path_a = std::path::PathBuf::from("/src/a.ts");
3845 let files = vec![crate::discover::DiscoveredFile {
3846 id: crate::discover::FileId(0),
3847 path: path_a.clone(),
3848 size_bytes: 100,
3849 }];
3850
3851 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3852 file_id: crate::discover::FileId(0),
3853 path: path_a.clone(),
3854 exports: vec![
3855 fallow_types::extract::ExportInfo {
3856 name: crate::source::ExportName::Named("a".into()),
3857 local_name: None,
3858 is_type_only: false,
3859 visibility: crate::source::VisibilityTag::None,
3860 expected_unused_reason: None,
3861 span: oxc_span::Span::empty(0),
3862 members: vec![],
3863 is_side_effect_used: false,
3864 super_class: None,
3865 },
3866 fallow_types::extract::ExportInfo {
3867 name: crate::source::ExportName::Named("b".into()),
3868 local_name: None,
3869 is_type_only: false,
3870 visibility: crate::source::VisibilityTag::None,
3871 expected_unused_reason: None,
3872 span: oxc_span::Span::empty(0),
3873 members: vec![],
3874 is_side_effect_used: false,
3875 super_class: None,
3876 },
3877 fallow_types::extract::ExportInfo {
3878 name: crate::source::ExportName::Named("T".into()),
3879 local_name: None,
3880 is_type_only: true,
3881 visibility: crate::source::VisibilityTag::None,
3882 expected_unused_reason: None,
3883 span: oxc_span::Span::empty(0),
3884 members: vec![],
3885 is_side_effect_used: false,
3886 super_class: None,
3887 },
3888 ],
3889 ..Default::default()
3890 }];
3891
3892 let graph = build_test_graph(&files, &[], &resolved_modules);
3893
3894 let modules = vec![make_module_info(
3895 0,
3896 10,
3897 vec![fallow_types::extract::FunctionComplexity {
3898 name: "fn_a".into(),
3899 line: 1,
3900 col: 0,
3901 cyclomatic: 2,
3902 cognitive: 1,
3903 line_count: 10,
3904 param_count: 0,
3905 react_hook_count: 0,
3906 react_jsx_max_depth: 0,
3907 react_prop_count: 0,
3908 source_hash: None,
3909 contributions: Vec::new(),
3910 }],
3911 )];
3912
3913 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3914 rustc_hash::FxHashMap::default();
3915 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3916
3917 let output = crate::results::DeadCodeAnalysisArtifacts {
3918 results: fallow_types::results::AnalysisResults::default(),
3919 timings: None,
3920 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3921 modules: None,
3922 files: None,
3923 script_used_packages: rustc_hash::FxHashSet::default(),
3924 file_hashes: rustc_hash::FxHashMap::default(),
3925 };
3926
3927 let result = compute_file_scores(
3928 &modules,
3929 &file_paths,
3930 None,
3931 output,
3932 None,
3933 std::path::Path::new("/project"),
3934 )
3935 .unwrap();
3936 assert_eq!(result.value_export_counts[&path_a], 2);
3937 }
3938
3939 #[test]
3940 fn compute_file_scores_top_complex_fns_zero_cognitive_excluded() {
3941 let path_a = std::path::PathBuf::from("/src/simple.ts");
3942 let files = vec![crate::discover::DiscoveredFile {
3943 id: crate::discover::FileId(0),
3944 path: path_a.clone(),
3945 size_bytes: 100,
3946 }];
3947
3948 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3949 file_id: crate::discover::FileId(0),
3950 path: path_a.clone(),
3951 ..Default::default()
3952 }];
3953
3954 let graph = build_test_graph(&files, &[], &resolved_modules);
3955
3956 let modules = vec![make_module_info(
3957 0,
3958 10,
3959 vec![fallow_types::extract::FunctionComplexity {
3960 name: "trivial".into(),
3961 line: 1,
3962 col: 0,
3963 cyclomatic: 1,
3964 cognitive: 0,
3965 line_count: 10,
3966 param_count: 0,
3967 react_hook_count: 0,
3968 react_jsx_max_depth: 0,
3969 react_prop_count: 0,
3970 source_hash: None,
3971 contributions: Vec::new(),
3972 }],
3973 )];
3974
3975 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3976 rustc_hash::FxHashMap::default();
3977 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3978
3979 let output = crate::results::DeadCodeAnalysisArtifacts {
3980 results: fallow_types::results::AnalysisResults::default(),
3981 timings: None,
3982 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3983 modules: None,
3984 files: None,
3985 script_used_packages: rustc_hash::FxHashSet::default(),
3986 file_hashes: rustc_hash::FxHashMap::default(),
3987 };
3988
3989 let result = compute_file_scores(
3990 &modules,
3991 &file_paths,
3992 None,
3993 output,
3994 None,
3995 std::path::Path::new("/project"),
3996 )
3997 .unwrap();
3998 assert!(!result.top_complex_fns.contains_key(&path_a));
3999 }
4000
4001 fn make_fn_complexity(cyclomatic: u16) -> fallow_types::extract::FunctionComplexity {
4002 fallow_types::extract::FunctionComplexity {
4003 name: "test_fn".into(),
4004 line: 1,
4005 col: 0,
4006 cyclomatic,
4007 cognitive: 0,
4008 line_count: 10,
4009 param_count: 0,
4010 react_hook_count: 0,
4011 react_jsx_max_depth: 0,
4012 react_prop_count: 0,
4013 source_hash: None,
4014 contributions: Vec::new(),
4015 }
4016 }
4017
4018 #[test]
4019 fn crap_scores_empty_complexity() {
4020 let (max, above) = compute_crap_scores_binary(&[], true);
4021 assert!((max).abs() < f64::EPSILON);
4022 assert_eq!(above, 0);
4023 }
4024
4025 #[test]
4026 fn crap_scores_test_reachable() {
4027 let funcs = vec![make_fn_complexity(5)];
4028 let (max, above) = compute_crap_scores_binary(&funcs, true);
4029 assert!((max - 5.0).abs() < f64::EPSILON);
4030 assert_eq!(above, 0);
4031 }
4032
4033 #[test]
4034 fn crap_scores_untested_at_threshold() {
4035 let funcs = vec![make_fn_complexity(5)];
4036 let (max, above) = compute_crap_scores_binary(&funcs, false);
4037 assert!((max - 30.0).abs() < f64::EPSILON);
4038 assert_eq!(above, 1);
4039 }
4040
4041 #[test]
4042 fn crap_scores_untested_above_threshold() {
4043 let funcs = vec![make_fn_complexity(6)];
4044 let (max, above) = compute_crap_scores_binary(&funcs, false);
4045 assert!((max - 42.0).abs() < f64::EPSILON);
4046 assert_eq!(above, 1);
4047 }
4048
4049 #[test]
4050 fn crap_scores_untested_below_threshold() {
4051 let funcs = vec![make_fn_complexity(4)];
4052 let (max, above) = compute_crap_scores_binary(&funcs, false);
4053 assert!((max - 20.0).abs() < f64::EPSILON);
4054 assert_eq!(above, 0);
4055 }
4056
4057 #[test]
4058 fn crap_scores_mixed_functions_untested() {
4059 let funcs = vec![
4060 make_fn_complexity(2),
4061 make_fn_complexity(5),
4062 make_fn_complexity(8),
4063 ];
4064 let (max, above) = compute_crap_scores_binary(&funcs, false);
4065 assert!((max - 72.0).abs() < f64::EPSILON);
4066 assert_eq!(above, 2);
4067 }
4068
4069 #[test]
4070 fn crap_formula_full_coverage() {
4071 let result = crap_formula(10.0, 100.0);
4072 assert!((result - 10.0).abs() < f64::EPSILON);
4073 }
4074
4075 #[test]
4076 fn crap_formula_zero_coverage() {
4077 let result = crap_formula(5.0, 0.0);
4078 assert!((result - 30.0).abs() < f64::EPSILON);
4079 }
4080
4081 #[test]
4082 fn crap_formula_partial_coverage() {
4083 let result = crap_formula(10.0, 50.0);
4084 assert!((result - 22.5).abs() < f64::EPSILON);
4085 }
4086
4087 #[test]
4088 fn crap_formula_high_coverage_low_complexity() {
4089 let result = crap_formula(2.0, 90.0);
4090 assert!((result - 2.004).abs() < 0.001);
4091 }
4092
4093 #[test]
4094 fn istanbul_crap_with_coverage_data() {
4095 let funcs = vec![make_fn_complexity(10)];
4096 let mut functions = rustc_hash::FxHashMap::default();
4097 functions.insert(("test_fn".to_string(), 1, 0), 80.0);
4098 let file_cov = IstanbulFileCoverage { functions };
4099 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), false);
4100 assert!((result.max_crap - 10.8).abs() < 0.1);
4101 assert_eq!(result.above_threshold, 0);
4102 }
4103
4104 #[test]
4105 fn istanbul_crap_falls_back_to_binary_when_no_match() {
4106 let funcs = vec![make_fn_complexity(6)];
4107 let file_cov = IstanbulFileCoverage {
4108 functions: rustc_hash::FxHashMap::default(),
4109 };
4110 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), false);
4111 assert!((result.max_crap - 42.0).abs() < f64::EPSILON);
4112 assert_eq!(result.above_threshold, 1);
4113 }
4114
4115 #[test]
4116 fn istanbul_crap_falls_back_to_binary_when_no_file_coverage() {
4117 let funcs = vec![make_fn_complexity(5)];
4118 let result = compute_crap_scores_istanbul(&funcs, None, true);
4119 assert!((result.max_crap - 5.0).abs() < f64::EPSILON);
4120 assert_eq!(result.above_threshold, 0);
4121 }
4122
4123 #[test]
4124 fn istanbul_crap_zero_coverage_matches_binary_untested() {
4125 let funcs = vec![make_fn_complexity(5)];
4126 let mut functions = rustc_hash::FxHashMap::default();
4127 functions.insert(("test_fn".to_string(), 1, 0), 0.0);
4128 let file_cov = IstanbulFileCoverage { functions };
4129 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), false);
4130 assert!((result.max_crap - 30.0).abs() < f64::EPSILON);
4131 assert_eq!(result.above_threshold, 1);
4132 }
4133
4134 #[test]
4135 fn estimated_crap_direct_test_reference() {
4136 let funcs = vec![make_fn_complexity(10)];
4137 let mut refs = rustc_hash::FxHashSet::default();
4138 refs.insert("test_fn".to_string());
4139 let result = compute_crap_scores_estimated(
4140 &funcs,
4141 &refs,
4142 true,
4143 fallow_output::CoverageSource::Estimated,
4144 );
4145 let (max, above) = (result.max_crap, result.above_threshold);
4146 assert!((max - 10.3).abs() < 0.1);
4147 assert_eq!(above, 0);
4148 }
4149
4150 #[test]
4151 fn estimated_crap_indirect_test_reachable() {
4152 let funcs = vec![make_fn_complexity(10)];
4153 let refs = rustc_hash::FxHashSet::default();
4154 let result = compute_crap_scores_estimated(
4155 &funcs,
4156 &refs,
4157 true,
4158 fallow_output::CoverageSource::Estimated,
4159 );
4160 let (max, above) = (result.max_crap, result.above_threshold);
4161 assert!((max - 31.6).abs() < 0.1);
4162 assert_eq!(above, 1);
4163 }
4164
4165 #[test]
4166 fn estimated_crap_untested_file() {
4167 let funcs = vec![make_fn_complexity(5)];
4168 let refs = rustc_hash::FxHashSet::default();
4169 let result = compute_crap_scores_estimated(
4170 &funcs,
4171 &refs,
4172 false,
4173 fallow_output::CoverageSource::Estimated,
4174 );
4175 let (max, above) = (result.max_crap, result.above_threshold);
4176 assert!((max - 30.0).abs() < f64::EPSILON);
4177 assert_eq!(above, 1);
4178 }
4179
4180 #[test]
4181 fn estimated_crap_low_complexity_direct_ref() {
4182 let funcs = vec![make_fn_complexity(2)];
4183 let mut refs = rustc_hash::FxHashSet::default();
4184 refs.insert("test_fn".to_string());
4185 let result = compute_crap_scores_estimated(
4186 &funcs,
4187 &refs,
4188 true,
4189 fallow_output::CoverageSource::Estimated,
4190 );
4191 let (max, above) = (result.max_crap, result.above_threshold);
4192 assert!(max < 3.0);
4193 assert_eq!(above, 0);
4194 }
4195
4196 #[test]
4197 fn estimated_crap_empty() {
4198 let refs = rustc_hash::FxHashSet::default();
4199 let result = compute_crap_scores_estimated(
4200 &[],
4201 &refs,
4202 true,
4203 fallow_output::CoverageSource::Estimated,
4204 );
4205 let (max, above) = (result.max_crap, result.above_threshold);
4206 assert!((max).abs() < f64::EPSILON);
4207 assert_eq!(above, 0);
4208 }
4209
4210 fn make_export(name: &str, is_type_only: bool) -> fallow_graph::graph::ExportSymbol {
4211 fallow_graph::graph::ExportSymbol {
4212 name: fallow_types::extract::ExportName::Named(name.into()),
4213 is_type_only,
4214 is_side_effect_used: false,
4215 visibility: crate::source::VisibilityTag::None,
4216 expected_unused_reason: None,
4217 span: oxc_span::Span::default(),
4218 references: vec![],
4219 members: vec![],
4220 }
4221 }
4222
4223 #[test]
4224 fn dead_code_ratio_type_only_exports_excluded_from_denominator() {
4225 let path = std::path::Path::new("src/types.ts");
4226 let exports = vec![
4227 make_export("MyInterface", true),
4228 make_export("MyType", true),
4229 make_export("myFunction", false),
4230 ];
4231 let unused_files = rustc_hash::FxHashSet::default();
4232 let mut unused_by_path = rustc_hash::FxHashMap::default();
4233 unused_by_path.insert(path, 1_usize); let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_by_path);
4236 assert!((ratio - 1.0).abs() < f64::EPSILON);
4237 }
4238
4239 #[test]
4240 fn dead_code_ratio_only_type_exports_returns_zero() {
4241 let path = std::path::Path::new("src/types.ts");
4242 let exports = vec![
4243 make_export("MyInterface", true),
4244 make_export("MyType", true),
4245 ];
4246 let unused_files = rustc_hash::FxHashSet::default();
4247 let unused_by_path = rustc_hash::FxHashMap::default();
4248
4249 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_by_path);
4250 assert!(ratio.abs() < f64::EPSILON);
4251 }
4252
4253 #[test]
4254 fn dead_code_ratio_mixed_exports_counts_only_values() {
4255 let path = std::path::Path::new("src/component.ts");
4256 let exports = vec![
4257 make_export("Props", true),
4258 make_export("State", true),
4259 make_export("Component", false),
4260 make_export("helper", false),
4261 ];
4262 let unused_files = rustc_hash::FxHashSet::default();
4263 let mut unused_by_path = rustc_hash::FxHashMap::default();
4264 unused_by_path.insert(path, 1_usize);
4265
4266 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_by_path);
4267 assert!((ratio - 0.5).abs() < f64::EPSILON);
4268 }
4269
4270 fn write_single_file_istanbul_fixture(
4271 coverage_path: &std::path::Path,
4272 source_path: &std::path::Path,
4273 fn_map: &serde_json::Value,
4274 function_hits: &serde_json::Value,
4275 ) {
4276 let mut root = serde_json::Map::new();
4277 root.insert(
4278 source_path.to_string_lossy().into_owned(),
4279 serde_json::json!({
4280 "path": source_path.to_string_lossy().into_owned(),
4281 "statementMap": {},
4282 "fnMap": fn_map,
4283 "branchMap": {},
4284 "s": {},
4285 "f": function_hits,
4286 "b": {}
4287 }),
4288 );
4289
4290 std::fs::write(coverage_path, serde_json::to_string(&root).unwrap()).unwrap();
4291 }
4292
4293 #[test]
4294 fn resolve_relative_to_root_joins_relative_with_project_root() {
4295 let resolved = resolve_relative_to_root(
4296 std::path::Path::new("coverage/coverage-final.json"),
4297 Some(std::path::Path::new("/work/my-app")),
4298 );
4299 assert_eq!(
4300 resolved,
4301 std::path::PathBuf::from("/work/my-app/coverage/coverage-final.json")
4302 );
4303 }
4304
4305 #[test]
4306 fn resolve_relative_to_root_returns_absolute_unchanged() {
4307 let resolved = resolve_relative_to_root(
4308 std::path::Path::new("/tmp/coverage-final.json"),
4309 Some(std::path::Path::new("/work/my-app")),
4310 );
4311 assert_eq!(
4312 resolved,
4313 std::path::PathBuf::from("/tmp/coverage-final.json")
4314 );
4315 }
4316
4317 #[test]
4318 fn resolve_relative_to_root_returns_windows_absolute_unchanged_on_any_host() {
4319 let path = std::path::Path::new(r"C:\coverage\coverage-final.json");
4320 let resolved = resolve_relative_to_root(path, Some(std::path::Path::new("/work/my-app")));
4321 assert_eq!(resolved, path);
4322 }
4323
4324 #[cfg(windows)]
4325 #[test]
4326 fn resolve_relative_to_root_returns_posix_rooted_path_unchanged_on_windows() {
4327 let path = std::path::Path::new(r"/ci/workspace/coverage-final.json");
4328 let resolved =
4329 resolve_relative_to_root(path, Some(std::path::Path::new(r"C:\work\my-app")));
4330 assert_eq!(resolved, path);
4331 }
4332
4333 #[test]
4334 fn resolve_relative_to_root_without_project_root_returns_relative_unchanged() {
4335 let resolved =
4336 resolve_relative_to_root(std::path::Path::new("coverage/coverage-final.json"), None);
4337 assert_eq!(
4338 resolved,
4339 std::path::PathBuf::from("coverage/coverage-final.json")
4340 );
4341 }
4342
4343 #[test]
4344 fn load_istanbul_coverage_resolves_relative_path_against_project_root() {
4345 let temp = tempfile::TempDir::new().unwrap();
4346 let source_path = temp.path().join("src/index.ts");
4347 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4348 std::fs::write(&source_path, "export function f(){}").unwrap();
4349
4350 let coverage_path = temp.path().join("coverage/coverage-final.json");
4351 std::fs::create_dir_all(coverage_path.parent().unwrap()).unwrap();
4352 write_single_file_istanbul_fixture(
4353 &coverage_path,
4354 &source_path,
4355 &serde_json::json!({
4356 "0": {
4357 "name": "f",
4358 "decl": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 21 } },
4359 "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 21 } }
4360 }
4361 }),
4362 &serde_json::json!({ "0": 1 }),
4363 );
4364
4365 let coverage = load_istanbul_coverage(
4366 std::path::Path::new("coverage/coverage-final.json"),
4367 None,
4368 Some(temp.path()),
4369 )
4370 .expect("relative path must resolve against project_root");
4371 assert!(
4372 !coverage.files.is_empty(),
4373 "expected coverage to load via project_root resolution, got {} files",
4374 coverage.files.len()
4375 );
4376 }
4377
4378 #[test]
4379 fn load_istanbul_coverage_falls_back_to_decl_line_for_missing_fn_line() {
4380 let temp = tempfile::TempDir::new().unwrap();
4381 let source_path = temp.path().join("src/service.ts");
4382 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4383 std::fs::write(&source_path, "export class DataService {}\n").unwrap();
4384
4385 let coverage_path = temp.path().join("coverage-final.json");
4386 write_single_file_istanbul_fixture(
4387 &coverage_path,
4388 &source_path,
4389 &serde_json::json!({
4390 "0": {
4391 "name": "(anonymous_0)",
4392 "decl": {
4393 "start": { "line": 5, "column": 2 },
4394 "end": { "line": 5, "column": 13 }
4395 },
4396 "loc": {
4397 "start": { "line": 5, "column": 14 },
4398 "end": { "line": 11, "column": 3 }
4399 }
4400 },
4401 "1": {
4402 "name": "(anonymous_1)",
4403 "decl": {
4404 "start": { "line": 20, "column": 14 },
4405 "end": { "line": 20, "column": 25 }
4406 },
4407 "loc": {
4408 "start": { "line": 20, "column": 28 },
4409 "end": { "line": 22, "column": 2 }
4410 }
4411 }
4412 }),
4413 &serde_json::json!({
4414 "0": 1,
4415 "1": 0
4416 }),
4417 );
4418
4419 let coverage = load_istanbul_coverage(&coverage_path, None, None).unwrap();
4420 let canonical_source = dunce::canonicalize(&source_path).unwrap();
4421 let file_coverage = coverage.get(&canonical_source).unwrap();
4422
4423 assert_eq!(file_coverage.lookup("processData", 5, 0), Some(100.0));
4424 assert_eq!(file_coverage.lookup("handleSpecial", 20, 0), Some(0.0));
4425 }
4426
4427 #[test]
4428 fn load_istanbul_coverage_indexes_explicit_and_decl_lines() {
4429 let temp = tempfile::TempDir::new().unwrap();
4430 let source_path = temp.path().join("src/handler.ts");
4431 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4432 std::fs::write(&source_path, "export const handleClick = () => {}\n").unwrap();
4433
4434 let coverage_path = temp.path().join("coverage-final.json");
4435 write_single_file_istanbul_fixture(
4436 &coverage_path,
4437 &source_path,
4438 &serde_json::json!({
4439 "0": {
4440 "name": "handleClick",
4441 "line": 40,
4442 "decl": {
4443 "start": { "line": 22, "column": 13 },
4444 "end": { "line": 22, "column": 24 }
4445 },
4446 "loc": {
4447 "start": { "line": 40, "column": 27 },
4448 "end": { "line": 42, "column": 1 }
4449 }
4450 }
4451 }),
4452 &serde_json::json!({
4453 "0": 1
4454 }),
4455 );
4456
4457 let coverage = load_istanbul_coverage(&coverage_path, None, None).unwrap();
4458 let canonical_source = dunce::canonicalize(&source_path).unwrap();
4459 let file_coverage = coverage.get(&canonical_source).unwrap();
4460
4461 assert_eq!(file_coverage.lookup("handleClick", 40, 0), Some(100.0));
4462 assert_eq!(file_coverage.lookup("handleClick", 22, 13), Some(100.0));
4463 }
4464
4465 #[test]
4466 fn load_istanbul_coverage_matches_multiline_async_arrow_decl_alias() {
4467 let temp = tempfile::TempDir::new().unwrap();
4468 let source_path = temp.path().join("src/actor.ts");
4469 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4470 std::fs::write(
4471 &source_path,
4472 "export const elementsFrom = async (\n locator: AnyLocator,\n options?: { missingAsEmpty?: boolean },\n): Promise<HTMLElement[]> => {\n return [];\n};\n",
4473 )
4474 .unwrap();
4475
4476 let coverage_path = temp.path().join("coverage-final.json");
4477 write_single_file_istanbul_fixture(
4478 &coverage_path,
4479 &source_path,
4480 &serde_json::json!({
4481 "0": {
4482 "name": "(anonymous_0)",
4483 "line": 4,
4484 "decl": {
4485 "start": { "line": 1, "column": 28 },
4486 "end": { "line": 4, "column": 26 }
4487 },
4488 "loc": {
4489 "start": { "line": 4, "column": 27 },
4490 "end": { "line": 6, "column": 1 }
4491 }
4492 }
4493 }),
4494 &serde_json::json!({
4495 "0": 642
4496 }),
4497 );
4498
4499 let coverage = load_istanbul_coverage(&coverage_path, None, None).unwrap();
4500 let canonical_source = dunce::canonicalize(&source_path).unwrap();
4501 let file_coverage = coverage.get(&canonical_source).unwrap();
4502
4503 assert_eq!(file_coverage.lookup("elementsFrom", 1, 28), Some(100.0));
4504 }
4505
4506 #[test]
4507 fn istanbul_lookup_exact_match() {
4508 let mut functions = rustc_hash::FxHashMap::default();
4509 functions.insert(("handleClick".to_string(), 10, 0), 85.0);
4510 let fc = IstanbulFileCoverage { functions };
4511 assert!((fc.lookup("handleClick", 10, 0).unwrap() - 85.0).abs() < f64::EPSILON);
4512 }
4513
4514 #[test]
4515 fn istanbul_lookup_fuzzy_match_within_offset() {
4516 let mut functions = rustc_hash::FxHashMap::default();
4517 functions.insert(("handleClick".to_string(), 10, 0), 72.0);
4518 let fc = IstanbulFileCoverage { functions };
4519 assert!((fc.lookup("handleClick", 11, 0).unwrap() - 72.0).abs() < f64::EPSILON);
4520 assert!((fc.lookup("handleClick", 12, 0).unwrap() - 72.0).abs() < f64::EPSILON);
4521 }
4522
4523 #[test]
4524 fn istanbul_lookup_fuzzy_match_outside_offset() {
4525 let mut functions = rustc_hash::FxHashMap::default();
4526 functions.insert(("handleClick".to_string(), 10, 0), 72.0);
4527 let fc = IstanbulFileCoverage { functions };
4528 assert!(fc.lookup("handleClick", 13, 0).is_none());
4529 }
4530
4531 #[test]
4532 fn istanbul_lookup_name_mismatch() {
4533 let mut functions = rustc_hash::FxHashMap::default();
4534 functions.insert(("handleClick".to_string(), 10, 0), 85.0);
4535 let fc = IstanbulFileCoverage { functions };
4536 assert!(fc.lookup("handleSubmit", 10, 0).is_none());
4537 }
4538
4539 #[test]
4540 fn istanbul_lookup_empty() {
4541 let fc = IstanbulFileCoverage {
4542 functions: rustc_hash::FxHashMap::default(),
4543 };
4544 assert!(fc.lookup("anything", 1, 0).is_none());
4545 }
4546
4547 #[test]
4548 fn istanbul_lookup_fuzzy_picks_closest() {
4549 let mut functions = rustc_hash::FxHashMap::default();
4550 functions.insert(("render".to_string(), 8, 0), 60.0);
4551 functions.insert(("render".to_string(), 12, 0), 90.0);
4552 let fc = IstanbulFileCoverage { functions };
4553 let result = fc.lookup("render", 10, 0);
4554 assert!(result.is_some());
4555 let pct = result.unwrap();
4556 assert!((pct - 60.0).abs() < f64::EPSILON || (pct - 90.0).abs() < f64::EPSILON);
4557 }
4558
4559 #[test]
4560 fn istanbul_lookup_anonymous_fallback_single_candidate() {
4561 let mut functions = rustc_hash::FxHashMap::default();
4562 functions.insert(("(anonymous_0)".to_string(), 28, 0), 75.0);
4563 let fc = IstanbulFileCoverage { functions };
4564 assert!((fc.lookup("myHandler", 28, 0).unwrap() - 75.0).abs() < f64::EPSILON);
4565 assert!((fc.lookup("myHandler", 30, 0).unwrap() - 75.0).abs() < f64::EPSILON);
4566 }
4567
4568 #[test]
4569 fn istanbul_lookup_anonymous_fallback_rejects_nearby_far_column() {
4570 let mut functions = rustc_hash::FxHashMap::default();
4571 functions.insert(("(anonymous_0)".to_string(), 4, 28), 75.0);
4572 let fc = IstanbulFileCoverage { functions };
4573
4574 assert!(fc.lookup("declaredHelper", 3, 0).is_none());
4575 }
4576
4577 #[test]
4578 fn istanbul_lookup_anonymous_fallback_picks_closest_when_lines_differ() {
4579 let mut functions = rustc_hash::FxHashMap::default();
4580 functions.insert(("(anonymous_0)".to_string(), 28, 0), 75.0);
4581 functions.insert(("(anonymous_1)".to_string(), 29, 0), 50.0);
4582 let fc = IstanbulFileCoverage { functions };
4583 assert!((fc.lookup("myHandler", 28, 0).unwrap() - 75.0).abs() < f64::EPSILON);
4584 }
4585
4586 #[test]
4587 fn istanbul_lookup_anonymous_fallback_picks_closest_by_col_on_same_line() {
4588 let mut functions = rustc_hash::FxHashMap::default();
4589 functions.insert(("(anonymous_0)".to_string(), 1, 23), 90.0); functions.insert(("(anonymous_1)".to_string(), 1, 43), 10.0); let fc = IstanbulFileCoverage { functions };
4592 assert!((fc.lookup("<arrow>", 1, 43).unwrap() - 10.0).abs() < f64::EPSILON);
4593 assert!((fc.lookup("<arrow>", 1, 23).unwrap() - 90.0).abs() < f64::EPSILON);
4594 }
4595
4596 #[test]
4597 fn istanbul_lookup_anonymous_fallback_bails_only_on_true_tie() {
4598 let mut functions = rustc_hash::FxHashMap::default();
4599 functions.insert(("(anonymous_0)".to_string(), 27, 0), 75.0);
4600 functions.insert(("(anonymous_1)".to_string(), 29, 0), 50.0);
4601 let fc = IstanbulFileCoverage { functions };
4602 assert!(fc.lookup("myHandler", 28, 0).is_none());
4603 }
4604
4605 #[test]
4606 fn istanbul_lookup_anonymous_fallback_outside_offset() {
4607 let mut functions = rustc_hash::FxHashMap::default();
4608 functions.insert(("(anonymous_0)".to_string(), 28, 0), 75.0);
4609 let fc = IstanbulFileCoverage { functions };
4610 assert!(fc.lookup("myHandler", 31, 0).is_none());
4611 }
4612
4613 #[test]
4614 fn istanbul_lookup_named_match_beats_nearby_anonymous() {
4615 let mut functions = rustc_hash::FxHashMap::default();
4616 functions.insert(("handleClick".to_string(), 10, 0), 90.0);
4617 functions.insert(("(anonymous_7)".to_string(), 11, 0), 10.0);
4618 let fc = IstanbulFileCoverage { functions };
4619 assert!((fc.lookup("handleClick", 10, 0).unwrap() - 90.0).abs() < f64::EPSILON);
4620 }
4621
4622 #[test]
4623 fn build_test_refs_empty() {
4624 let exports: Vec<fallow_graph::graph::ExportSymbol> = vec![];
4625 let modules: Vec<fallow_graph::graph::ModuleNode> = vec![];
4626 let refs = build_test_referenced_exports(&exports, &modules);
4627 assert!(refs.is_empty());
4628 }
4629
4630 #[test]
4631 fn build_test_refs_empty_inputs() {
4632 let exports: Vec<fallow_graph::graph::ExportSymbol> = vec![];
4633 let modules: Vec<fallow_graph::graph::ModuleNode> = vec![];
4634 let refs = build_test_referenced_exports(&exports, &modules);
4635 assert!(refs.is_empty());
4636 }
4637
4638 #[test]
4639 fn istanbul_crap_empty_complexity() {
4640 let result = compute_crap_scores_istanbul(&[], None, false);
4641 assert!((result.max_crap).abs() < f64::EPSILON);
4642 assert_eq!(result.above_threshold, 0);
4643 assert_eq!(result.matched, 0);
4644 assert_eq!(result.total, 0);
4645 }
4646
4647 #[test]
4648 fn istanbul_crap_match_statistics() {
4649 let funcs = vec![make_fn_complexity(5), {
4650 let mut f = make_fn_complexity(3);
4651 f.name = "other_fn".into();
4652 f.line = 10;
4653 f
4654 }];
4655 let mut functions = rustc_hash::FxHashMap::default();
4656 functions.insert(("test_fn".to_string(), 1, 0), 80.0);
4657 let file_cov = IstanbulFileCoverage { functions };
4658 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), true);
4659 assert_eq!(result.matched, 1);
4660 assert_eq!(result.total, 2);
4661 }
4662
4663 #[test]
4664 fn estimated_crap_multiple_functions_mixed_coverage() {
4665 let funcs = vec![
4666 make_fn_complexity(10), {
4668 let mut f = make_fn_complexity(3);
4669 f.name = "helper".into();
4670 f.line = 20;
4671 f
4672 },
4673 ];
4674 let mut refs = rustc_hash::FxHashSet::default();
4675 refs.insert("test_fn".to_string());
4676 let result = compute_crap_scores_estimated(
4677 &funcs,
4678 &refs,
4679 true,
4680 fallow_output::CoverageSource::Estimated,
4681 );
4682 let (max, above) = (result.max_crap, result.above_threshold);
4683 assert!(max > 10.0);
4684 assert_eq!(above, 0);
4685 }
4686
4687 #[test]
4688 fn binary_crap_test_reachable() {
4689 let funcs = vec![make_fn_complexity(10)];
4690 let (max, above) = compute_crap_scores_binary(&funcs, true);
4691 assert!((max - 10.0).abs() < f64::EPSILON);
4692 assert_eq!(above, 0);
4693 }
4694
4695 #[test]
4696 fn binary_crap_not_reachable() {
4697 let funcs = vec![make_fn_complexity(6)];
4698 let (max, above) = compute_crap_scores_binary(&funcs, false);
4699 assert!((max - 42.0).abs() < f64::EPSILON);
4700 assert_eq!(above, 1);
4701 }
4702
4703 #[test]
4704 fn binary_crap_threshold_boundary() {
4705 let funcs = vec![make_fn_complexity(5)];
4706 let (max, above) = compute_crap_scores_binary(&funcs, false);
4707 assert!((max - 30.0).abs() < f64::EPSILON);
4708 assert_eq!(above, 1);
4709 }
4710
4711 #[test]
4712 fn binary_crap_empty() {
4713 let (max, above) = compute_crap_scores_binary(&[], true);
4714 assert!((max).abs() < f64::EPSILON);
4715 assert_eq!(above, 0);
4716 }
4717
4718 #[test]
4719 fn binary_crap_multiple_functions() {
4720 let funcs = vec![make_fn_complexity(3), make_fn_complexity(8)];
4721 let (max, above) = compute_crap_scores_binary(&funcs, false);
4722 assert!((max - 72.0).abs() < f64::EPSILON);
4723 assert_eq!(above, 1);
4724 }
4725}