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 has_route_loader_data_whole_use: false,
2068 component_functions: Vec::new(),
2069 react_props: Vec::new(),
2070 hook_uses: Vec::new(),
2071 render_edges: Vec::new(),
2072 svelte_dispatched_events: Vec::new(),
2073 svelte_listened_events: Vec::new(),
2074 angular_component_selectors: Vec::new(),
2075 registered_custom_elements: Vec::new(),
2076 used_custom_element_tags: Vec::new(),
2077 angular_used_selectors: Vec::new(),
2078 angular_entry_component_refs: Vec::new(),
2079 has_dynamic_component_render: false,
2080 has_dynamic_dispatch: false,
2081 };
2082
2083 let (cyc, cog, funcs, lines) = aggregate_complexity(&module);
2084 assert_eq!(cyc, 0);
2085 assert_eq!(cog, 0);
2086 assert_eq!(funcs, 0);
2087 assert_eq!(lines, 0);
2088 }
2089
2090 #[test]
2091 fn aggregate_complexity_single_function() {
2092 let module = crate::source::ModuleInfo {
2093 file_id: crate::discover::FileId(0),
2094 exports: vec![],
2095 imports: vec![],
2096 re_exports: vec![],
2097 dynamic_imports: vec![],
2098 dynamic_import_patterns: vec![],
2099 require_calls: vec![],
2100 package_path_references: Box::default(),
2101 member_accesses: vec![],
2102 semantic_facts: Box::default(),
2103 whole_object_uses: Box::default(),
2104 has_cjs_exports: false,
2105 has_angular_component_template_url: false,
2106 content_hash: 0,
2107 suppressions: vec![],
2108 unknown_suppression_kinds: vec![],
2109 unused_import_bindings: vec![],
2110 type_referenced_import_bindings: vec![],
2111 value_referenced_import_bindings: vec![],
2112 flag_uses: vec![],
2113 class_heritage: vec![],
2114 exported_factory_returns: Box::default(),
2115 type_member_types: Box::default(),
2116 injection_tokens: vec![],
2117 local_type_declarations: Vec::new(),
2118 public_signature_type_references: Vec::new(),
2119 namespace_object_aliases: Vec::new(),
2120 iconify_prefixes: Vec::new(),
2121 iconify_icon_names: Vec::new(),
2122 auto_import_candidates: Vec::new(),
2123 directives: Vec::new(),
2124 client_only_dynamic_import_spans: Vec::new(),
2125 security_sinks: Vec::new(),
2126 security_sinks_skipped: 0,
2127 security_unresolved_callee_sites: Vec::new(),
2128 tainted_bindings: Vec::new(),
2129 sanitized_sink_args: Vec::new(),
2130 security_control_sites: Vec::new(),
2131 callee_uses: Vec::new(),
2132 misplaced_directives: Vec::new(),
2133 inline_server_action_exports: Vec::new(),
2134 di_key_sites: Vec::new(),
2135 has_dynamic_provide: false,
2136 referenced_import_bindings: Vec::new(),
2137 component_props: Vec::new(),
2138 has_props_attrs_fallthrough: false,
2139 has_define_expose: false,
2140 has_define_model: false,
2141 has_unharvestable_props: false,
2142 component_emits: Vec::new(),
2143 angular_inputs: Vec::new(),
2144 angular_outputs: Vec::new(),
2145 has_unharvestable_emits: false,
2146 has_dynamic_emit: false,
2147 has_emit_whole_object_use: false,
2148 load_return_keys: Vec::new(),
2149 has_unharvestable_load: false,
2150 has_load_data_whole_use: false,
2151 has_page_data_store_whole_use: false,
2152 has_route_loader_data_whole_use: false,
2153 component_functions: Vec::new(),
2154 react_props: Vec::new(),
2155 hook_uses: Vec::new(),
2156 render_edges: Vec::new(),
2157 svelte_dispatched_events: Vec::new(),
2158 svelte_listened_events: Vec::new(),
2159 angular_component_selectors: Vec::new(),
2160 registered_custom_elements: Vec::new(),
2161 used_custom_element_tags: Vec::new(),
2162 angular_used_selectors: Vec::new(),
2163 angular_entry_component_refs: Vec::new(),
2164 has_dynamic_component_render: false,
2165 has_dynamic_dispatch: false,
2166 line_offsets: vec![0, 10, 20, 30, 40], complexity: vec![fallow_types::extract::FunctionComplexity {
2168 name: "doStuff".into(),
2169 line: 1,
2170 col: 0,
2171 cyclomatic: 7,
2172 cognitive: 4,
2173 line_count: 5,
2174 param_count: 0,
2175 react_hook_count: 0,
2176 react_jsx_max_depth: 0,
2177 react_prop_count: 0,
2178 source_hash: None,
2179 contributions: Vec::new(),
2180 }],
2181 };
2182
2183 let (cyc, cog, funcs, lines) = aggregate_complexity(&module);
2184 assert_eq!(cyc, 7);
2185 assert_eq!(cog, 4);
2186 assert_eq!(funcs, 1);
2187 assert_eq!(lines, 5);
2188 }
2189
2190 #[test]
2191 #[expect(
2192 clippy::too_many_lines,
2193 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
2194 )]
2195 fn aggregate_complexity_multiple_functions() {
2196 let module = crate::source::ModuleInfo {
2197 file_id: crate::discover::FileId(0),
2198 exports: vec![],
2199 imports: vec![],
2200 re_exports: vec![],
2201 dynamic_imports: vec![],
2202 dynamic_import_patterns: vec![],
2203 require_calls: vec![],
2204 package_path_references: Box::default(),
2205 member_accesses: vec![],
2206 semantic_facts: Box::default(),
2207 whole_object_uses: Box::default(),
2208 has_cjs_exports: false,
2209 has_angular_component_template_url: false,
2210 content_hash: 0,
2211 suppressions: vec![],
2212 unknown_suppression_kinds: vec![],
2213 unused_import_bindings: vec![],
2214 type_referenced_import_bindings: vec![],
2215 value_referenced_import_bindings: vec![],
2216 flag_uses: vec![],
2217 class_heritage: vec![],
2218 exported_factory_returns: Box::default(),
2219 type_member_types: Box::default(),
2220 injection_tokens: vec![],
2221 local_type_declarations: Vec::new(),
2222 public_signature_type_references: Vec::new(),
2223 namespace_object_aliases: Vec::new(),
2224 iconify_prefixes: Vec::new(),
2225 iconify_icon_names: Vec::new(),
2226 auto_import_candidates: Vec::new(),
2227 directives: Vec::new(),
2228 client_only_dynamic_import_spans: Vec::new(),
2229 security_sinks: Vec::new(),
2230 security_sinks_skipped: 0,
2231 security_unresolved_callee_sites: Vec::new(),
2232 tainted_bindings: Vec::new(),
2233 sanitized_sink_args: Vec::new(),
2234 security_control_sites: Vec::new(),
2235 callee_uses: Vec::new(),
2236 misplaced_directives: Vec::new(),
2237 inline_server_action_exports: Vec::new(),
2238 di_key_sites: Vec::new(),
2239 has_dynamic_provide: false,
2240 referenced_import_bindings: Vec::new(),
2241 component_props: Vec::new(),
2242 has_props_attrs_fallthrough: false,
2243 has_define_expose: false,
2244 has_define_model: false,
2245 has_unharvestable_props: false,
2246 component_emits: Vec::new(),
2247 angular_inputs: Vec::new(),
2248 angular_outputs: Vec::new(),
2249 has_unharvestable_emits: false,
2250 has_dynamic_emit: false,
2251 has_emit_whole_object_use: false,
2252 load_return_keys: Vec::new(),
2253 has_unharvestable_load: false,
2254 has_load_data_whole_use: false,
2255 has_page_data_store_whole_use: false,
2256 has_route_loader_data_whole_use: false,
2257 component_functions: Vec::new(),
2258 react_props: Vec::new(),
2259 hook_uses: Vec::new(),
2260 render_edges: Vec::new(),
2261 svelte_dispatched_events: Vec::new(),
2262 svelte_listened_events: Vec::new(),
2263 angular_component_selectors: Vec::new(),
2264 registered_custom_elements: Vec::new(),
2265 used_custom_element_tags: Vec::new(),
2266 angular_used_selectors: Vec::new(),
2267 angular_entry_component_refs: Vec::new(),
2268 has_dynamic_component_render: false,
2269 has_dynamic_dispatch: false,
2270 line_offsets: vec![0, 10, 20], complexity: vec![
2272 fallow_types::extract::FunctionComplexity {
2273 name: "a".into(),
2274 line: 1,
2275 col: 0,
2276 cyclomatic: 3,
2277 cognitive: 2,
2278 line_count: 1,
2279 param_count: 0,
2280 react_hook_count: 0,
2281 react_jsx_max_depth: 0,
2282 react_prop_count: 0,
2283 source_hash: None,
2284 contributions: Vec::new(),
2285 },
2286 fallow_types::extract::FunctionComplexity {
2287 name: "b".into(),
2288 line: 2,
2289 col: 0,
2290 cyclomatic: 5,
2291 cognitive: 8,
2292 line_count: 2,
2293 param_count: 0,
2294 react_hook_count: 0,
2295 react_jsx_max_depth: 0,
2296 react_prop_count: 0,
2297 source_hash: None,
2298 contributions: Vec::new(),
2299 },
2300 ],
2301 };
2302
2303 let (cyc, cog, funcs, lines) = aggregate_complexity(&module);
2304 assert_eq!(cyc, 8);
2305 assert_eq!(cog, 10);
2306 assert_eq!(funcs, 2);
2307 assert_eq!(lines, 3);
2308 }
2309
2310 #[test]
2311 fn count_unused_exports_empty() {
2312 let exports: Vec<crate::results::UnusedExportFinding> = vec![];
2313 let map = count_unused_exports_by_path(&exports);
2314 assert!(map.is_empty());
2315 }
2316
2317 #[test]
2318 fn count_unused_exports_groups_by_path() {
2319 let exports = vec![
2320 crate::results::UnusedExportFinding::with_actions(crate::results::UnusedExport {
2321 path: std::path::PathBuf::from("/src/a.ts"),
2322 export_name: "foo".into(),
2323 is_type_only: false,
2324 line: 1,
2325 col: 0,
2326 span_start: 0,
2327 is_re_export: false,
2328 }),
2329 crate::results::UnusedExportFinding::with_actions(crate::results::UnusedExport {
2330 path: std::path::PathBuf::from("/src/a.ts"),
2331 export_name: "bar".into(),
2332 is_type_only: false,
2333 line: 5,
2334 col: 0,
2335 span_start: 40,
2336 is_re_export: false,
2337 }),
2338 crate::results::UnusedExportFinding::with_actions(crate::results::UnusedExport {
2339 path: std::path::PathBuf::from("/src/b.ts"),
2340 export_name: "baz".into(),
2341 is_type_only: false,
2342 line: 1,
2343 col: 0,
2344 span_start: 0,
2345 is_re_export: false,
2346 }),
2347 ];
2348 let map = count_unused_exports_by_path(&exports);
2349 assert_eq!(map.get(std::path::Path::new("/src/a.ts")).copied(), Some(2));
2350 assert_eq!(map.get(std::path::Path::new("/src/b.ts")).copied(), Some(1));
2351 }
2352
2353 #[test]
2354 fn dead_code_ratio_all_value_exports_unused() {
2355 let unused_files = rustc_hash::FxHashSet::default();
2356 let path = std::path::Path::new("/src/foo.ts");
2357
2358 let exports = vec![
2359 fallow_graph::graph::ExportSymbol {
2360 name: crate::source::ExportName::Named("a".into()),
2361 is_type_only: false,
2362 is_side_effect_used: false,
2363 visibility: crate::source::VisibilityTag::None,
2364 expected_unused_reason: None,
2365 span: oxc_span::Span::empty(0),
2366 references: vec![],
2367 members: vec![],
2368 },
2369 fallow_graph::graph::ExportSymbol {
2370 name: crate::source::ExportName::Named("b".into()),
2371 is_type_only: false,
2372 is_side_effect_used: false,
2373 visibility: crate::source::VisibilityTag::None,
2374 expected_unused_reason: None,
2375 span: oxc_span::Span::empty(0),
2376 references: vec![],
2377 members: vec![],
2378 },
2379 ];
2380
2381 let mut unused_map: rustc_hash::FxHashMap<&std::path::Path, usize> =
2382 rustc_hash::FxHashMap::default();
2383 unused_map.insert(path, 2);
2384
2385 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
2386 assert!((ratio - 1.0).abs() < f64::EPSILON);
2387 }
2388
2389 #[test]
2390 fn dead_code_ratio_clamped_when_unused_exceeds_value_exports() {
2391 let unused_files = rustc_hash::FxHashSet::default();
2392 let path = std::path::Path::new("/src/foo.ts");
2393
2394 let exports = vec![fallow_graph::graph::ExportSymbol {
2395 name: crate::source::ExportName::Named("a".into()),
2396 is_type_only: false,
2397 is_side_effect_used: false,
2398 visibility: crate::source::VisibilityTag::None,
2399 expected_unused_reason: None,
2400 span: oxc_span::Span::empty(0),
2401 references: vec![],
2402 members: vec![],
2403 }];
2404
2405 let mut unused_map: rustc_hash::FxHashMap<&std::path::Path, usize> =
2406 rustc_hash::FxHashMap::default();
2407 unused_map.insert(path, 5);
2408
2409 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
2410 assert!((ratio - 1.0).abs() < f64::EPSILON);
2411 }
2412
2413 #[test]
2414 fn dead_code_ratio_no_unused_exports_for_path() {
2415 let unused_files = rustc_hash::FxHashSet::default();
2416 let path = std::path::Path::new("/src/clean.ts");
2417
2418 let exports = vec![fallow_graph::graph::ExportSymbol {
2419 name: crate::source::ExportName::Named("used".into()),
2420 is_type_only: false,
2421 is_side_effect_used: false,
2422 visibility: crate::source::VisibilityTag::None,
2423 expected_unused_reason: None,
2424 span: oxc_span::Span::empty(0),
2425 references: vec![],
2426 members: vec![],
2427 }];
2428
2429 let unused_map = rustc_hash::FxHashMap::default();
2430 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_map);
2431 assert!(ratio.abs() < f64::EPSILON);
2432 }
2433
2434 #[test]
2435 fn complexity_density_zero_cyclomatic_with_lines() {
2436 let result = compute_complexity_density(0, 100);
2437 assert!(result.abs() < f64::EPSILON);
2438 }
2439
2440 #[test]
2441 fn complexity_density_single_line() {
2442 let result = compute_complexity_density(1, 1);
2443 assert!((result - 1.0).abs() < f64::EPSILON);
2444 }
2445
2446 #[test]
2447 fn maintainability_only_complexity_penalty() {
2448 let result = compute_maintainability_index(3.0, 0.0, 0, 100);
2449 assert!((result - 10.0).abs() < f64::EPSILON);
2450 }
2451
2452 #[test]
2453 fn maintainability_only_dead_code_penalty() {
2454 let result = compute_maintainability_index(0.0, 0.5, 0, 100);
2455 assert!((result - 90.0).abs() < f64::EPSILON);
2456 }
2457
2458 #[test]
2459 fn maintainability_fan_out_one() {
2460 let result = compute_maintainability_index(0.0, 0.0, 1, 100);
2461 let expected = 2.0_f64.ln().mul_add(-4.0, 100.0);
2462 assert!((result - expected).abs() < 0.01);
2463 }
2464
2465 #[test]
2466 fn maintainability_all_penalties_maxed() {
2467 let result = compute_maintainability_index(10.0, 1.0, 1000, 200);
2468 assert!(result.abs() < f64::EPSILON);
2469 }
2470
2471 #[test]
2472 fn count_unused_exports_single_file_single_export() {
2473 let exports = vec![crate::results::UnusedExportFinding::with_actions(
2474 crate::results::UnusedExport {
2475 path: std::path::PathBuf::from("/src/only.ts"),
2476 export_name: "lonely".into(),
2477 is_type_only: false,
2478 line: 1,
2479 col: 0,
2480 span_start: 0,
2481 is_re_export: false,
2482 },
2483 )];
2484 let map = count_unused_exports_by_path(&exports);
2485 assert_eq!(map.len(), 1);
2486 assert_eq!(
2487 map.get(std::path::Path::new("/src/only.ts")).copied(),
2488 Some(1)
2489 );
2490 }
2491
2492 fn build_test_graph(
2494 files: &[crate::discover::DiscoveredFile],
2495 entry_point_paths: &[std::path::PathBuf],
2496 resolved_modules: &[fallow_graph::resolve::ResolvedModule],
2497 ) -> fallow_graph::graph::ModuleGraph {
2498 let entry_points: Vec<crate::discover::EntryPoint> = entry_point_paths
2499 .iter()
2500 .map(|p| crate::discover::EntryPoint {
2501 path: p.clone(),
2502 source: crate::discover::EntryPointSource::PackageJsonMain,
2503 })
2504 .collect();
2505 fallow_graph::graph::ModuleGraph::build(resolved_modules, &entry_points, files)
2506 }
2507
2508 fn make_module_info(
2510 file_id: u32,
2511 line_count: usize,
2512 functions: Vec<fallow_types::extract::FunctionComplexity>,
2513 ) -> crate::source::ModuleInfo {
2514 crate::source::ModuleInfo {
2515 file_id: crate::discover::FileId(file_id),
2516 exports: vec![],
2517 imports: vec![],
2518 re_exports: vec![],
2519 dynamic_imports: vec![],
2520 dynamic_import_patterns: vec![],
2521 require_calls: vec![],
2522 package_path_references: Box::default(),
2523 member_accesses: vec![],
2524 semantic_facts: Box::default(),
2525 whole_object_uses: Box::default(),
2526 has_cjs_exports: false,
2527 has_angular_component_template_url: false,
2528 content_hash: 0,
2529 suppressions: vec![],
2530 unknown_suppression_kinds: vec![],
2531 unused_import_bindings: vec![],
2532 type_referenced_import_bindings: vec![],
2533 value_referenced_import_bindings: vec![],
2534 line_offsets: (0..line_count).map(|i| (i * 10) as u32).collect(),
2535 complexity: functions,
2536 flag_uses: vec![],
2537 class_heritage: vec![],
2538 exported_factory_returns: Box::default(),
2539 type_member_types: Box::default(),
2540 injection_tokens: vec![],
2541 local_type_declarations: Vec::new(),
2542 public_signature_type_references: Vec::new(),
2543 namespace_object_aliases: Vec::new(),
2544 iconify_prefixes: Vec::new(),
2545 iconify_icon_names: Vec::new(),
2546 auto_import_candidates: Vec::new(),
2547 directives: Vec::new(),
2548 client_only_dynamic_import_spans: Vec::new(),
2549 security_sinks: Vec::new(),
2550 security_sinks_skipped: 0,
2551 security_unresolved_callee_sites: Vec::new(),
2552 tainted_bindings: Vec::new(),
2553 sanitized_sink_args: Vec::new(),
2554 security_control_sites: Vec::new(),
2555 callee_uses: Vec::new(),
2556 misplaced_directives: Vec::new(),
2557 inline_server_action_exports: Vec::new(),
2558 di_key_sites: Vec::new(),
2559 has_dynamic_provide: false,
2560 referenced_import_bindings: Vec::new(),
2561 component_props: Vec::new(),
2562 has_props_attrs_fallthrough: false,
2563 has_define_expose: false,
2564 has_define_model: false,
2565 has_unharvestable_props: false,
2566 component_emits: Vec::new(),
2567 angular_inputs: Vec::new(),
2568 angular_outputs: Vec::new(),
2569 has_unharvestable_emits: false,
2570 has_dynamic_emit: false,
2571 has_emit_whole_object_use: false,
2572 load_return_keys: Vec::new(),
2573 has_unharvestable_load: false,
2574 has_load_data_whole_use: false,
2575 has_page_data_store_whole_use: false,
2576 has_route_loader_data_whole_use: false,
2577 component_functions: Vec::new(),
2578 react_props: Vec::new(),
2579 hook_uses: Vec::new(),
2580 render_edges: Vec::new(),
2581 svelte_dispatched_events: Vec::new(),
2582 svelte_listened_events: Vec::new(),
2583 angular_component_selectors: Vec::new(),
2584 registered_custom_elements: Vec::new(),
2585 used_custom_element_tags: Vec::new(),
2586 angular_used_selectors: Vec::new(),
2587 angular_entry_component_refs: Vec::new(),
2588 has_dynamic_component_render: false,
2589 has_dynamic_dispatch: false,
2590 }
2591 }
2592
2593 fn make_file_score(path: &str, maintainability_index: f64, crap_max: f64) -> FileHealthScore {
2594 FileHealthScore {
2595 path: std::path::PathBuf::from(path),
2596 fan_in: 0,
2597 fan_out: 0,
2598 dead_code_ratio: 0.0,
2599 complexity_density: 0.0,
2600 maintainability_index,
2601 total_cyclomatic: 0,
2602 total_cognitive: 0,
2603 function_count: 1,
2604 lines: 1,
2605 crap_max,
2606 crap_above_threshold: usize::from(crap_max >= CRAP_THRESHOLD),
2607 }
2608 }
2609
2610 #[test]
2611 fn file_score_crap_concern_tracks_crap_risk_bands() {
2612 assert!((file_score_crap_concern(0.0) - 0.0).abs() < f64::EPSILON);
2613 assert!((file_score_crap_concern(15.0) - 45.0).abs() < f64::EPSILON);
2614 assert!((file_score_crap_concern(CRAP_THRESHOLD) - 75.0).abs() < f64::EPSILON);
2615 assert!((file_score_crap_concern(100.0) - 100.0).abs() < f64::EPSILON);
2616 assert!((file_score_crap_concern(552.0) - 100.0).abs() < f64::EPSILON);
2617 }
2618
2619 #[test]
2620 fn file_score_concern_axis_labels_dominant_signal() {
2621 let risk_driven = make_file_score("/src/risk.ts", 84.8, 552.0);
2622 assert_eq!(
2623 file_score_concern_axis(&risk_driven),
2624 FileScoreConcern::Risk
2625 );
2626 assert_eq!(file_score_concern_axis(&risk_driven).label(), "risk");
2627
2628 let structure_driven = make_file_score("/src/structure.ts", 30.0, 8.0);
2629 assert_eq!(
2630 file_score_concern_axis(&structure_driven),
2631 FileScoreConcern::Structural
2632 );
2633 assert_eq!(
2634 file_score_concern_axis(&structure_driven).label(),
2635 "structure"
2636 );
2637
2638 let no_risk = make_file_score("/src/clean.ts", 100.0, 0.0);
2639 assert_eq!(
2640 file_score_concern_axis(&no_risk),
2641 FileScoreConcern::Structural
2642 );
2643 }
2644
2645 #[test]
2646 fn file_score_triage_sort_prioritizes_high_crap_over_slightly_lower_mi() {
2647 let low_mi_low_risk = make_file_score("/src/low-mi-low-risk.ts", 81.7, 2.0);
2648 let higher_mi_high_risk = make_file_score("/src/higher-mi-high-risk.ts", 84.8, 552.0);
2649
2650 let mut scores = [low_mi_low_risk, higher_mi_high_risk];
2651 scores.sort_by(compare_file_score_triage);
2652
2653 assert_eq!(
2654 scores[0].path,
2655 std::path::Path::new("/src/higher-mi-high-risk.ts")
2656 );
2657 assert_eq!(
2658 scores[1].path,
2659 std::path::Path::new("/src/low-mi-low-risk.ts")
2660 );
2661 }
2662
2663 #[test]
2664 fn file_score_triage_sort_orders_saturated_crap_by_raw_crap_descending() {
2665 let lower_crap_worse_mi = make_file_score("/src/a.ts", 84.8, 106.0);
2666 let higher_crap_better_mi = make_file_score("/src/b.ts", 96.7, 552.0);
2667
2668 let mut scores = [lower_crap_worse_mi, higher_crap_better_mi];
2669 scores.sort_by(compare_file_score_triage);
2670
2671 assert_eq!(scores[0].path, std::path::Path::new("/src/b.ts"));
2672 assert_eq!(scores[1].path, std::path::Path::new("/src/a.ts"));
2673 }
2674
2675 #[test]
2676 fn file_score_triage_sort_uses_mi_crap_and_path_tie_breakers() {
2677 let mut scores = [
2678 make_file_score("/src/b.ts", 70.0, 1.0),
2679 make_file_score("/src/a.ts", 70.0, 1.0),
2680 make_file_score("/src/higher-crap.ts", 70.0, 2.0),
2681 make_file_score("/src/lower-concern.ts", 80.0, 1.0),
2682 ];
2683
2684 scores.sort_by(compare_file_score_triage);
2685
2686 let paths: Vec<_> = scores.iter().map(|score| score.path.as_path()).collect();
2687 assert_eq!(
2688 paths,
2689 vec![
2690 std::path::Path::new("/src/higher-crap.ts"),
2691 std::path::Path::new("/src/a.ts"),
2692 std::path::Path::new("/src/b.ts"),
2693 std::path::Path::new("/src/lower-concern.ts"),
2694 ]
2695 );
2696 }
2697
2698 #[test]
2699 fn compute_file_scores_empty_graph() {
2700 let files: Vec<crate::discover::DiscoveredFile> = vec![];
2701 let graph = build_test_graph(&files, &[], &[]);
2702 let modules: Vec<crate::source::ModuleInfo> = vec![];
2703 let file_paths = rustc_hash::FxHashMap::default();
2704
2705 let output = crate::results::DeadCodeAnalysisArtifacts {
2706 results: fallow_types::results::AnalysisResults::default(),
2707 timings: None,
2708 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2709 modules: None,
2710 files: None,
2711 script_used_packages: rustc_hash::FxHashSet::default(),
2712 file_hashes: rustc_hash::FxHashMap::default(),
2713 };
2714
2715 let result = compute_file_scores(
2716 &modules,
2717 &file_paths,
2718 None,
2719 output,
2720 None,
2721 std::path::Path::new("/project"),
2722 )
2723 .unwrap();
2724 assert!(result.scores.is_empty());
2725 assert!(result.circular_files.is_empty());
2726 assert!(result.top_complex_fns.is_empty());
2727 assert!(result.entry_points.is_empty());
2728 assert_eq!(result.analysis_counts.total_exports, 0);
2729 assert_eq!(result.analysis_counts.dead_files, 0);
2730 }
2731
2732 #[test]
2733 fn compute_file_scores_no_graph_returns_error() {
2734 let modules: Vec<crate::source::ModuleInfo> = vec![];
2735 let file_paths = rustc_hash::FxHashMap::default();
2736
2737 let output = crate::results::DeadCodeAnalysisArtifacts {
2738 results: fallow_types::results::AnalysisResults::default(),
2739 timings: None,
2740 graph: None,
2741 modules: None,
2742 files: None,
2743 script_used_packages: rustc_hash::FxHashSet::default(),
2744 file_hashes: rustc_hash::FxHashMap::default(),
2745 };
2746
2747 let result = compute_file_scores(
2748 &modules,
2749 &file_paths,
2750 None,
2751 output,
2752 None,
2753 std::path::Path::new("/project"),
2754 );
2755 assert!(result.is_err());
2756 match result {
2757 Err(msg) => assert_eq!(msg, "graph not available"),
2758 Ok(_) => panic!("expected error"),
2759 }
2760 }
2761
2762 #[test]
2763 fn compute_file_scores_single_file_with_function() {
2764 let path_a = std::path::PathBuf::from("/src/a.ts");
2765 let files = vec![crate::discover::DiscoveredFile {
2766 id: crate::discover::FileId(0),
2767 path: path_a.clone(),
2768 size_bytes: 100,
2769 }];
2770
2771 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
2772 file_id: crate::discover::FileId(0),
2773 path: path_a.clone(),
2774 exports: vec![fallow_types::extract::ExportInfo {
2775 name: crate::source::ExportName::Named("foo".into()),
2776 local_name: None,
2777 is_type_only: false,
2778 visibility: crate::source::VisibilityTag::None,
2779 expected_unused_reason: None,
2780 span: oxc_span::Span::empty(0),
2781 members: vec![],
2782 is_side_effect_used: false,
2783 super_class: None,
2784 }],
2785 ..Default::default()
2786 }];
2787
2788 let graph = build_test_graph(&files, std::slice::from_ref(&path_a), &resolved_modules);
2789
2790 let modules = vec![make_module_info(
2791 0,
2792 10,
2793 vec![fallow_types::extract::FunctionComplexity {
2794 name: "foo".into(),
2795 line: 1,
2796 col: 0,
2797 cyclomatic: 5,
2798 cognitive: 3,
2799 line_count: 10,
2800 param_count: 0,
2801 react_hook_count: 0,
2802 react_jsx_max_depth: 0,
2803 react_prop_count: 0,
2804 source_hash: None,
2805 contributions: Vec::new(),
2806 }],
2807 )];
2808
2809 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
2810 rustc_hash::FxHashMap::default();
2811 file_paths.insert(crate::discover::FileId(0), &files[0].path);
2812
2813 let output = crate::results::DeadCodeAnalysisArtifacts {
2814 results: fallow_types::results::AnalysisResults::default(),
2815 timings: None,
2816 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2817 modules: None,
2818 files: None,
2819 script_used_packages: rustc_hash::FxHashSet::default(),
2820 file_hashes: rustc_hash::FxHashMap::default(),
2821 };
2822
2823 let result = compute_file_scores(
2824 &modules,
2825 &file_paths,
2826 None,
2827 output,
2828 None,
2829 std::path::Path::new("/project"),
2830 )
2831 .unwrap();
2832 assert_eq!(result.scores.len(), 1);
2833
2834 let score = &result.scores[0];
2835 assert_eq!(score.path, path_a);
2836 assert_eq!(score.total_cyclomatic, 5);
2837 assert_eq!(score.total_cognitive, 3);
2838 assert_eq!(score.function_count, 1);
2839 assert_eq!(score.lines, 10);
2840 assert!((score.complexity_density - 0.5).abs() < f64::EPSILON);
2841 assert!(score.dead_code_ratio.abs() < f64::EPSILON);
2842 assert!(result.entry_points.contains(&path_a));
2843 }
2844
2845 #[test]
2846 fn compute_file_scores_excludes_barrel_files() {
2847 let path_a = std::path::PathBuf::from("/src/index.ts");
2848 let files = vec![crate::discover::DiscoveredFile {
2849 id: crate::discover::FileId(0),
2850 path: path_a.clone(),
2851 size_bytes: 50,
2852 }];
2853
2854 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
2855 file_id: crate::discover::FileId(0),
2856 path: path_a.clone(),
2857 ..Default::default()
2858 }];
2859
2860 let graph = build_test_graph(&files, std::slice::from_ref(&path_a), &resolved_modules);
2861
2862 let modules = vec![make_module_info(0, 5, vec![])];
2863
2864 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
2865 rustc_hash::FxHashMap::default();
2866 file_paths.insert(crate::discover::FileId(0), &files[0].path);
2867
2868 let output = crate::results::DeadCodeAnalysisArtifacts {
2869 results: fallow_types::results::AnalysisResults::default(),
2870 timings: None,
2871 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2872 modules: None,
2873 files: None,
2874 script_used_packages: rustc_hash::FxHashSet::default(),
2875 file_hashes: rustc_hash::FxHashMap::default(),
2876 };
2877
2878 let result = compute_file_scores(
2879 &modules,
2880 &file_paths,
2881 None,
2882 output,
2883 None,
2884 std::path::Path::new("/project"),
2885 )
2886 .unwrap();
2887 assert!(result.scores.is_empty());
2888 }
2889
2890 #[test]
2891 fn compute_file_scores_changed_since_filter() {
2892 let path_a = std::path::PathBuf::from("/src/a.ts");
2893 let path_b = std::path::PathBuf::from("/src/b.ts");
2894 let files = vec![
2895 crate::discover::DiscoveredFile {
2896 id: crate::discover::FileId(0),
2897 path: path_a.clone(),
2898 size_bytes: 100,
2899 },
2900 crate::discover::DiscoveredFile {
2901 id: crate::discover::FileId(1),
2902 path: path_b.clone(),
2903 size_bytes: 100,
2904 },
2905 ];
2906
2907 let resolved_modules = vec![
2908 fallow_graph::resolve::ResolvedModule {
2909 file_id: crate::discover::FileId(0),
2910 path: path_a,
2911 ..Default::default()
2912 },
2913 fallow_graph::resolve::ResolvedModule {
2914 file_id: crate::discover::FileId(1),
2915 path: path_b.clone(),
2916 ..Default::default()
2917 },
2918 ];
2919
2920 let graph = build_test_graph(&files, &[], &resolved_modules);
2921
2922 let modules = vec![
2923 make_module_info(
2924 0,
2925 10,
2926 vec![fallow_types::extract::FunctionComplexity {
2927 name: "fn_a".into(),
2928 line: 1,
2929 col: 0,
2930 cyclomatic: 2,
2931 cognitive: 1,
2932 line_count: 10,
2933 param_count: 0,
2934 react_hook_count: 0,
2935 react_jsx_max_depth: 0,
2936 react_prop_count: 0,
2937 source_hash: None,
2938 contributions: Vec::new(),
2939 }],
2940 ),
2941 make_module_info(
2942 1,
2943 10,
2944 vec![fallow_types::extract::FunctionComplexity {
2945 name: "fn_b".into(),
2946 line: 1,
2947 col: 0,
2948 cyclomatic: 3,
2949 cognitive: 2,
2950 line_count: 10,
2951 param_count: 0,
2952 react_hook_count: 0,
2953 react_jsx_max_depth: 0,
2954 react_prop_count: 0,
2955 source_hash: None,
2956 contributions: Vec::new(),
2957 }],
2958 ),
2959 ];
2960
2961 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
2962 rustc_hash::FxHashMap::default();
2963 file_paths.insert(crate::discover::FileId(0), &files[0].path);
2964 file_paths.insert(crate::discover::FileId(1), &files[1].path);
2965
2966 let path_b_check = std::path::PathBuf::from("/src/b.ts");
2967 let mut changed = rustc_hash::FxHashSet::default();
2968 changed.insert(path_b);
2969
2970 let output = crate::results::DeadCodeAnalysisArtifacts {
2971 results: fallow_types::results::AnalysisResults::default(),
2972 timings: None,
2973 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
2974 modules: None,
2975 files: None,
2976 script_used_packages: rustc_hash::FxHashSet::default(),
2977 file_hashes: rustc_hash::FxHashMap::default(),
2978 };
2979
2980 let result = compute_file_scores(
2981 &modules,
2982 &file_paths,
2983 Some(&changed),
2984 output,
2985 None,
2986 std::path::Path::new("/project"),
2987 )
2988 .unwrap();
2989 assert_eq!(result.scores.len(), 1);
2990 assert_eq!(result.scores[0].path, path_b_check);
2991 }
2992
2993 #[test]
2994 fn compute_file_scores_sorted_by_triage_concern() {
2995 let path_a = std::path::PathBuf::from("/src/a.ts");
2996 let path_b = std::path::PathBuf::from("/src/b.ts");
2997 let files = vec![
2998 crate::discover::DiscoveredFile {
2999 id: crate::discover::FileId(0),
3000 path: path_a.clone(),
3001 size_bytes: 100,
3002 },
3003 crate::discover::DiscoveredFile {
3004 id: crate::discover::FileId(1),
3005 path: path_b.clone(),
3006 size_bytes: 100,
3007 },
3008 ];
3009
3010 let resolved_modules = vec![
3011 fallow_graph::resolve::ResolvedModule {
3012 file_id: crate::discover::FileId(0),
3013 path: path_a.clone(),
3014 ..Default::default()
3015 },
3016 fallow_graph::resolve::ResolvedModule {
3017 file_id: crate::discover::FileId(1),
3018 path: path_b,
3019 ..Default::default()
3020 },
3021 ];
3022
3023 let graph = build_test_graph(&files, &[], &resolved_modules);
3024
3025 let modules = vec![
3026 make_module_info(
3027 0,
3028 10,
3029 vec![fallow_types::extract::FunctionComplexity {
3030 name: "complex_fn".into(),
3031 line: 1,
3032 col: 0,
3033 cyclomatic: 30,
3034 cognitive: 20,
3035 line_count: 10,
3036 param_count: 0,
3037 react_hook_count: 0,
3038 react_jsx_max_depth: 0,
3039 react_prop_count: 0,
3040 source_hash: None,
3041 contributions: Vec::new(),
3042 }],
3043 ),
3044 make_module_info(
3045 1,
3046 100,
3047 vec![fallow_types::extract::FunctionComplexity {
3048 name: "simple_fn".into(),
3049 line: 1,
3050 col: 0,
3051 cyclomatic: 1,
3052 cognitive: 0,
3053 line_count: 100,
3054 param_count: 0,
3055 react_hook_count: 0,
3056 react_jsx_max_depth: 0,
3057 react_prop_count: 0,
3058 source_hash: None,
3059 contributions: Vec::new(),
3060 }],
3061 ),
3062 ];
3063
3064 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3065 rustc_hash::FxHashMap::default();
3066 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3067 file_paths.insert(crate::discover::FileId(1), &files[1].path);
3068
3069 let output = crate::results::DeadCodeAnalysisArtifacts {
3070 results: fallow_types::results::AnalysisResults::default(),
3071 timings: None,
3072 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3073 modules: None,
3074 files: None,
3075 script_used_packages: rustc_hash::FxHashSet::default(),
3076 file_hashes: rustc_hash::FxHashMap::default(),
3077 };
3078
3079 let result = compute_file_scores(
3080 &modules,
3081 &file_paths,
3082 None,
3083 output,
3084 None,
3085 std::path::Path::new("/project"),
3086 )
3087 .unwrap();
3088 assert_eq!(result.scores.len(), 2);
3089 assert!(result.scores[0].maintainability_index <= result.scores[1].maintainability_index);
3090 assert_eq!(result.scores[0].path, path_a);
3091 }
3092
3093 #[test]
3094 fn compute_file_scores_with_unused_file_populates_evidence() {
3095 let path_a = std::path::PathBuf::from("/src/unused.ts");
3096 let files = vec![crate::discover::DiscoveredFile {
3097 id: crate::discover::FileId(0),
3098 path: path_a.clone(),
3099 size_bytes: 100,
3100 }];
3101
3102 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3103 file_id: crate::discover::FileId(0),
3104 path: path_a.clone(),
3105 exports: vec![fallow_types::extract::ExportInfo {
3106 name: crate::source::ExportName::Named("orphan".into()),
3107 local_name: None,
3108 is_type_only: false,
3109 visibility: crate::source::VisibilityTag::None,
3110 expected_unused_reason: None,
3111 span: oxc_span::Span::empty(0),
3112 members: vec![],
3113 is_side_effect_used: false,
3114 super_class: None,
3115 }],
3116 ..Default::default()
3117 }];
3118
3119 let graph = build_test_graph(&files, &[], &resolved_modules);
3120
3121 let modules = vec![make_module_info(
3122 0,
3123 10,
3124 vec![fallow_types::extract::FunctionComplexity {
3125 name: "orphan".into(),
3126 line: 1,
3127 col: 0,
3128 cyclomatic: 1,
3129 cognitive: 0,
3130 line_count: 10,
3131 param_count: 0,
3132 react_hook_count: 0,
3133 react_jsx_max_depth: 0,
3134 react_prop_count: 0,
3135 source_hash: None,
3136 contributions: Vec::new(),
3137 }],
3138 )];
3139
3140 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3141 rustc_hash::FxHashMap::default();
3142 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3143
3144 let mut results = fallow_types::results::AnalysisResults::default();
3145 results.unused_files.push(
3146 fallow_types::output_dead_code::UnusedFileFinding::with_actions(
3147 fallow_types::results::UnusedFile {
3148 path: path_a.clone(),
3149 },
3150 ),
3151 );
3152
3153 let output = crate::results::DeadCodeAnalysisArtifacts {
3154 results,
3155 timings: None,
3156 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3157 modules: None,
3158 files: None,
3159 script_used_packages: rustc_hash::FxHashSet::default(),
3160 file_hashes: rustc_hash::FxHashMap::default(),
3161 };
3162
3163 let result = compute_file_scores(
3164 &modules,
3165 &file_paths,
3166 None,
3167 output,
3168 None,
3169 std::path::Path::new("/project"),
3170 )
3171 .unwrap();
3172 assert_eq!(result.scores.len(), 1);
3173 assert!((result.scores[0].dead_code_ratio - 1.0).abs() < f64::EPSILON);
3174 assert!(result.unused_export_names.contains_key(&path_a));
3175 let names = &result.unused_export_names[&path_a];
3176 assert_eq!(names, &["orphan"]);
3177 assert_eq!(result.analysis_counts.dead_files, 1);
3178 }
3179
3180 #[test]
3181 #[expect(
3182 clippy::too_many_lines,
3183 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3184 )]
3185 fn compute_file_scores_tracks_top_complex_functions() {
3186 let path_a = std::path::PathBuf::from("/src/complex.ts");
3187 let files = vec![crate::discover::DiscoveredFile {
3188 id: crate::discover::FileId(0),
3189 path: path_a.clone(),
3190 size_bytes: 500,
3191 }];
3192
3193 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3194 file_id: crate::discover::FileId(0),
3195 path: path_a.clone(),
3196 ..Default::default()
3197 }];
3198
3199 let graph = build_test_graph(&files, &[], &resolved_modules);
3200
3201 let modules = vec![make_module_info(
3202 0,
3203 50,
3204 vec![
3205 fallow_types::extract::FunctionComplexity {
3206 name: "high".into(),
3207 line: 1,
3208 col: 0,
3209 cyclomatic: 10,
3210 cognitive: 20,
3211 line_count: 10,
3212 param_count: 0,
3213 react_hook_count: 0,
3214 react_jsx_max_depth: 0,
3215 react_prop_count: 0,
3216 source_hash: None,
3217 contributions: Vec::new(),
3218 },
3219 fallow_types::extract::FunctionComplexity {
3220 name: "medium".into(),
3221 line: 11,
3222 col: 0,
3223 cyclomatic: 5,
3224 cognitive: 10,
3225 line_count: 10,
3226 param_count: 0,
3227 react_hook_count: 0,
3228 react_jsx_max_depth: 0,
3229 react_prop_count: 0,
3230 source_hash: None,
3231 contributions: Vec::new(),
3232 },
3233 fallow_types::extract::FunctionComplexity {
3234 name: "low".into(),
3235 line: 21,
3236 col: 0,
3237 cyclomatic: 2,
3238 cognitive: 5,
3239 line_count: 10,
3240 param_count: 0,
3241 react_hook_count: 0,
3242 react_jsx_max_depth: 0,
3243 react_prop_count: 0,
3244 source_hash: None,
3245 contributions: Vec::new(),
3246 },
3247 fallow_types::extract::FunctionComplexity {
3248 name: "trivial".into(),
3249 line: 31,
3250 col: 0,
3251 cyclomatic: 1,
3252 cognitive: 1,
3253 line_count: 10,
3254 param_count: 0,
3255 react_hook_count: 0,
3256 react_jsx_max_depth: 0,
3257 react_prop_count: 0,
3258 source_hash: None,
3259 contributions: Vec::new(),
3260 },
3261 ],
3262 )];
3263
3264 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3265 rustc_hash::FxHashMap::default();
3266 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3267
3268 let output = crate::results::DeadCodeAnalysisArtifacts {
3269 results: fallow_types::results::AnalysisResults::default(),
3270 timings: None,
3271 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3272 modules: None,
3273 files: None,
3274 script_used_packages: rustc_hash::FxHashSet::default(),
3275 file_hashes: rustc_hash::FxHashMap::default(),
3276 };
3277
3278 let result = compute_file_scores(
3279 &modules,
3280 &file_paths,
3281 None,
3282 output,
3283 None,
3284 std::path::Path::new("/project"),
3285 )
3286 .unwrap();
3287 assert!(result.top_complex_fns.contains_key(&path_a));
3288 let top = &result.top_complex_fns[&path_a];
3289 assert_eq!(top.len(), 3);
3290 assert_eq!(top[0].0, "high");
3291 assert_eq!(top[0].2, 20);
3292 assert_eq!(top[1].0, "medium");
3293 assert_eq!(top[1].2, 10);
3294 assert_eq!(top[2].0, "low");
3295 assert_eq!(top[2].2, 5);
3296 }
3297
3298 #[test]
3299 #[expect(
3300 clippy::too_many_lines,
3301 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3302 )]
3303 fn compute_file_scores_with_circular_deps() {
3304 let path_a = std::path::PathBuf::from("/src/a.ts");
3305 let path_b = std::path::PathBuf::from("/src/b.ts");
3306 let files = vec![
3307 crate::discover::DiscoveredFile {
3308 id: crate::discover::FileId(0),
3309 path: path_a.clone(),
3310 size_bytes: 100,
3311 },
3312 crate::discover::DiscoveredFile {
3313 id: crate::discover::FileId(1),
3314 path: path_b.clone(),
3315 size_bytes: 100,
3316 },
3317 ];
3318
3319 let resolved_modules = vec![
3320 fallow_graph::resolve::ResolvedModule {
3321 file_id: crate::discover::FileId(0),
3322 path: path_a.clone(),
3323 ..Default::default()
3324 },
3325 fallow_graph::resolve::ResolvedModule {
3326 file_id: crate::discover::FileId(1),
3327 path: path_b.clone(),
3328 ..Default::default()
3329 },
3330 ];
3331
3332 let graph = build_test_graph(&files, &[], &resolved_modules);
3333
3334 let modules = vec![
3335 make_module_info(
3336 0,
3337 10,
3338 vec![fallow_types::extract::FunctionComplexity {
3339 name: "fn_a".into(),
3340 line: 1,
3341 col: 0,
3342 cyclomatic: 2,
3343 cognitive: 1,
3344 line_count: 10,
3345 param_count: 0,
3346 react_hook_count: 0,
3347 react_jsx_max_depth: 0,
3348 react_prop_count: 0,
3349 source_hash: None,
3350 contributions: Vec::new(),
3351 }],
3352 ),
3353 make_module_info(
3354 1,
3355 10,
3356 vec![fallow_types::extract::FunctionComplexity {
3357 name: "fn_b".into(),
3358 line: 1,
3359 col: 0,
3360 cyclomatic: 3,
3361 cognitive: 2,
3362 line_count: 10,
3363 param_count: 0,
3364 react_hook_count: 0,
3365 react_jsx_max_depth: 0,
3366 react_prop_count: 0,
3367 source_hash: None,
3368 contributions: Vec::new(),
3369 }],
3370 ),
3371 ];
3372
3373 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3374 rustc_hash::FxHashMap::default();
3375 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3376 file_paths.insert(crate::discover::FileId(1), &files[1].path);
3377
3378 let mut results = fallow_types::results::AnalysisResults::default();
3379 results.circular_dependencies.push(
3380 fallow_types::output_dead_code::CircularDependencyFinding::with_actions(
3381 fallow_types::results::CircularDependency {
3382 files: vec![path_a.clone(), path_b.clone()],
3383 length: 2,
3384 line: 1,
3385 col: 0,
3386 edges: Vec::new(),
3387 is_cross_package: false,
3388 },
3389 ),
3390 );
3391
3392 let output = crate::results::DeadCodeAnalysisArtifacts {
3393 results,
3394 timings: None,
3395 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3396 modules: None,
3397 files: None,
3398 script_used_packages: rustc_hash::FxHashSet::default(),
3399 file_hashes: rustc_hash::FxHashMap::default(),
3400 };
3401
3402 let result = compute_file_scores(
3403 &modules,
3404 &file_paths,
3405 None,
3406 output,
3407 None,
3408 std::path::Path::new("/project"),
3409 )
3410 .unwrap();
3411 assert!(result.circular_files.contains(&path_a));
3412 assert!(result.circular_files.contains(&path_b));
3413 assert!(result.cycle_members.contains_key(&path_a));
3414 assert_eq!(result.cycle_members[&path_a], vec![path_b.clone()]);
3415 assert!(result.cycle_members.contains_key(&path_b));
3416 assert_eq!(result.cycle_members[&path_b], vec![path_a]);
3417 assert_eq!(result.analysis_counts.circular_deps, 1);
3418 }
3419
3420 #[test]
3421 #[expect(
3422 clippy::too_many_lines,
3423 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3424 )]
3425 fn compute_file_scores_analysis_counts_unused_exports_and_types() {
3426 let path_a = std::path::PathBuf::from("/src/a.ts");
3427 let files = vec![crate::discover::DiscoveredFile {
3428 id: crate::discover::FileId(0),
3429 path: path_a.clone(),
3430 size_bytes: 100,
3431 }];
3432
3433 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3434 file_id: crate::discover::FileId(0),
3435 path: path_a.clone(),
3436 exports: vec![
3437 fallow_types::extract::ExportInfo {
3438 name: crate::source::ExportName::Named("foo".into()),
3439 local_name: None,
3440 is_type_only: false,
3441 visibility: crate::source::VisibilityTag::None,
3442 expected_unused_reason: None,
3443 span: oxc_span::Span::empty(0),
3444 members: vec![],
3445 is_side_effect_used: false,
3446 super_class: None,
3447 },
3448 fallow_types::extract::ExportInfo {
3449 name: crate::source::ExportName::Named("bar".into()),
3450 local_name: None,
3451 is_type_only: false,
3452 visibility: crate::source::VisibilityTag::None,
3453 expected_unused_reason: None,
3454 span: oxc_span::Span::empty(0),
3455 members: vec![],
3456 is_side_effect_used: false,
3457 super_class: None,
3458 },
3459 ],
3460 ..Default::default()
3461 }];
3462
3463 let graph = build_test_graph(&files, &[], &resolved_modules);
3464
3465 let mut module = make_module_info(
3466 0,
3467 10,
3468 vec![fallow_types::extract::FunctionComplexity {
3469 name: "fn_a".into(),
3470 line: 1,
3471 col: 0,
3472 cyclomatic: 1,
3473 cognitive: 0,
3474 line_count: 10,
3475 param_count: 0,
3476 react_hook_count: 0,
3477 react_jsx_max_depth: 0,
3478 react_prop_count: 0,
3479 source_hash: None,
3480 contributions: Vec::new(),
3481 }],
3482 );
3483 module.exports = vec![
3484 fallow_types::extract::ExportInfo {
3485 name: crate::source::ExportName::Named("foo".into()),
3486 local_name: None,
3487 is_type_only: false,
3488 visibility: crate::source::VisibilityTag::None,
3489 expected_unused_reason: None,
3490 span: oxc_span::Span::empty(0),
3491 members: vec![],
3492 is_side_effect_used: false,
3493 super_class: None,
3494 },
3495 fallow_types::extract::ExportInfo {
3496 name: crate::source::ExportName::Named("bar".into()),
3497 local_name: None,
3498 is_type_only: false,
3499 visibility: crate::source::VisibilityTag::None,
3500 expected_unused_reason: None,
3501 span: oxc_span::Span::empty(0),
3502 members: vec![],
3503 is_side_effect_used: false,
3504 super_class: None,
3505 },
3506 ];
3507 let modules = vec![module];
3508
3509 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3510 rustc_hash::FxHashMap::default();
3511 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3512
3513 let mut results = fallow_types::results::AnalysisResults::default();
3514 results.unused_exports.push(
3515 fallow_types::output_dead_code::UnusedExportFinding::with_actions(
3516 fallow_types::results::UnusedExport {
3517 path: path_a.clone(),
3518 export_name: "foo".into(),
3519 is_type_only: false,
3520 line: 1,
3521 col: 0,
3522 span_start: 0,
3523 is_re_export: false,
3524 },
3525 ),
3526 );
3527 results.unused_types.push(
3528 fallow_types::output_dead_code::UnusedTypeFinding::with_actions(
3529 fallow_types::results::UnusedExport {
3530 path: path_a,
3531 export_name: "MyType".into(),
3532 is_type_only: true,
3533 line: 5,
3534 col: 0,
3535 span_start: 40,
3536 is_re_export: false,
3537 },
3538 ),
3539 );
3540 results.unused_dependencies.push(
3541 fallow_types::output_dead_code::UnusedDependencyFinding::with_actions(
3542 fallow_types::results::UnusedDependency {
3543 package_name: "lodash".into(),
3544 location: fallow_types::results::DependencyLocation::Dependencies,
3545 path: std::path::PathBuf::from("/package.json"),
3546 line: 1,
3547 used_in_workspaces: Vec::new(),
3548 },
3549 ),
3550 );
3551
3552 let output = crate::results::DeadCodeAnalysisArtifacts {
3553 results,
3554 timings: None,
3555 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3556 modules: None,
3557 files: None,
3558 script_used_packages: rustc_hash::FxHashSet::default(),
3559 file_hashes: rustc_hash::FxHashMap::default(),
3560 };
3561
3562 let result = compute_file_scores(
3563 &modules,
3564 &file_paths,
3565 None,
3566 output,
3567 None,
3568 std::path::Path::new("/project"),
3569 )
3570 .unwrap();
3571 assert_eq!(result.analysis_counts.total_exports, 2);
3572 assert_eq!(result.analysis_counts.dead_exports, 2);
3573 assert_eq!(result.analysis_counts.unused_deps, 1);
3574 }
3575
3576 #[test]
3578 #[expect(
3579 clippy::too_many_lines,
3580 reason = "test fixture; linear setup/assert, length is not a maintainability concern"
3581 )]
3582 fn total_exports_counts_graph_modules_not_extraction_modules() {
3583 let path_a = std::path::PathBuf::from("/src/a.ts");
3584 let files = vec![crate::discover::DiscoveredFile {
3585 id: crate::discover::FileId(0),
3586 path: path_a.clone(),
3587 size_bytes: 100,
3588 }];
3589
3590 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3591 file_id: crate::discover::FileId(0),
3592 path: path_a.clone(),
3593 exports: vec![
3594 fallow_types::extract::ExportInfo {
3595 name: crate::source::ExportName::Named("foo".into()),
3596 local_name: None,
3597 is_type_only: false,
3598 visibility: crate::source::VisibilityTag::None,
3599 expected_unused_reason: None,
3600 span: oxc_span::Span::empty(0),
3601 members: vec![],
3602 is_side_effect_used: false,
3603 super_class: None,
3604 },
3605 fallow_types::extract::ExportInfo {
3606 name: crate::source::ExportName::Named("bar".into()),
3607 local_name: None,
3608 is_type_only: false,
3609 visibility: crate::source::VisibilityTag::None,
3610 expected_unused_reason: None,
3611 span: oxc_span::Span::empty(0),
3612 members: vec![],
3613 is_side_effect_used: false,
3614 super_class: None,
3615 },
3616 fallow_types::extract::ExportInfo {
3617 name: crate::source::ExportName::Named("baz".into()),
3618 local_name: None,
3619 is_type_only: false,
3620 visibility: crate::source::VisibilityTag::None,
3621 expected_unused_reason: None,
3622 span: oxc_span::Span::new(0, 0),
3623 members: vec![],
3624 is_side_effect_used: false,
3625 super_class: None,
3626 },
3627 ],
3628 ..Default::default()
3629 }];
3630
3631 let graph = build_test_graph(&files, &[], &resolved_modules);
3632
3633 let mut module = make_module_info(
3634 0,
3635 10,
3636 vec![fallow_types::extract::FunctionComplexity {
3637 name: "fn_a".into(),
3638 line: 1,
3639 col: 0,
3640 cyclomatic: 1,
3641 cognitive: 0,
3642 line_count: 10,
3643 param_count: 0,
3644 react_hook_count: 0,
3645 react_jsx_max_depth: 0,
3646 react_prop_count: 0,
3647 source_hash: None,
3648 contributions: Vec::new(),
3649 }],
3650 );
3651 module.exports = vec![
3652 fallow_types::extract::ExportInfo {
3653 name: crate::source::ExportName::Named("foo".into()),
3654 local_name: None,
3655 is_type_only: false,
3656 visibility: crate::source::VisibilityTag::None,
3657 expected_unused_reason: None,
3658 span: oxc_span::Span::empty(0),
3659 members: vec![],
3660 is_side_effect_used: false,
3661 super_class: None,
3662 },
3663 fallow_types::extract::ExportInfo {
3664 name: crate::source::ExportName::Named("bar".into()),
3665 local_name: None,
3666 is_type_only: false,
3667 visibility: crate::source::VisibilityTag::None,
3668 expected_unused_reason: None,
3669 span: oxc_span::Span::empty(0),
3670 members: vec![],
3671 is_side_effect_used: false,
3672 super_class: None,
3673 },
3674 ];
3675 let modules = vec![module];
3676
3677 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3678 rustc_hash::FxHashMap::default();
3679 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3680
3681 let mut results = fallow_types::results::AnalysisResults::default();
3682 for name in ["foo", "bar", "baz"] {
3683 results.unused_exports.push(
3684 fallow_types::output_dead_code::UnusedExportFinding::with_actions(
3685 fallow_types::results::UnusedExport {
3686 path: path_a.clone(),
3687 export_name: name.into(),
3688 is_type_only: false,
3689 line: 1,
3690 col: 0,
3691 span_start: 0,
3692 is_re_export: name == "baz",
3693 },
3694 ),
3695 );
3696 }
3697
3698 let output = crate::results::DeadCodeAnalysisArtifacts {
3699 results,
3700 timings: None,
3701 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3702 modules: None,
3703 files: None,
3704 script_used_packages: rustc_hash::FxHashSet::default(),
3705 file_hashes: rustc_hash::FxHashMap::default(),
3706 };
3707
3708 let result = compute_file_scores(
3709 &modules,
3710 &file_paths,
3711 None,
3712 output,
3713 None,
3714 std::path::Path::new("/project"),
3715 )
3716 .unwrap();
3717 assert_eq!(result.analysis_counts.total_exports, 3);
3718 assert_eq!(result.analysis_counts.dead_exports, 3);
3719 }
3720
3721 #[test]
3722 fn compute_file_scores_module_not_in_file_paths_skipped() {
3723 let path_a = std::path::PathBuf::from("/src/a.ts");
3724 let files = vec![crate::discover::DiscoveredFile {
3725 id: crate::discover::FileId(0),
3726 path: path_a.clone(),
3727 size_bytes: 100,
3728 }];
3729
3730 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3731 file_id: crate::discover::FileId(0),
3732 path: path_a,
3733 ..Default::default()
3734 }];
3735
3736 let graph = build_test_graph(&files, &[], &resolved_modules);
3737
3738 let modules = vec![make_module_info(
3739 0,
3740 10,
3741 vec![fallow_types::extract::FunctionComplexity {
3742 name: "fn_a".into(),
3743 line: 1,
3744 col: 0,
3745 cyclomatic: 2,
3746 cognitive: 1,
3747 line_count: 10,
3748 param_count: 0,
3749 react_hook_count: 0,
3750 react_jsx_max_depth: 0,
3751 react_prop_count: 0,
3752 source_hash: None,
3753 contributions: Vec::new(),
3754 }],
3755 )];
3756
3757 let file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3758 rustc_hash::FxHashMap::default();
3759
3760 let output = crate::results::DeadCodeAnalysisArtifacts {
3761 results: fallow_types::results::AnalysisResults::default(),
3762 timings: None,
3763 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3764 modules: None,
3765 files: None,
3766 script_used_packages: rustc_hash::FxHashSet::default(),
3767 file_hashes: rustc_hash::FxHashMap::default(),
3768 };
3769
3770 let result = compute_file_scores(
3771 &modules,
3772 &file_paths,
3773 None,
3774 output,
3775 None,
3776 std::path::Path::new("/project"),
3777 )
3778 .unwrap();
3779 assert!(result.scores.is_empty());
3780 }
3781
3782 #[test]
3783 fn compute_file_scores_mi_rounded_to_one_decimal() {
3784 let path_a = std::path::PathBuf::from("/src/a.ts");
3785 let files = vec![crate::discover::DiscoveredFile {
3786 id: crate::discover::FileId(0),
3787 path: path_a.clone(),
3788 size_bytes: 100,
3789 }];
3790
3791 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3792 file_id: crate::discover::FileId(0),
3793 path: path_a.clone(),
3794 ..Default::default()
3795 }];
3796
3797 let graph = build_test_graph(&files, std::slice::from_ref(&path_a), &resolved_modules);
3798
3799 let modules = vec![make_module_info(
3800 0,
3801 100,
3802 vec![fallow_types::extract::FunctionComplexity {
3803 name: "fn".into(),
3804 line: 1,
3805 col: 0,
3806 cyclomatic: 7,
3807 cognitive: 3,
3808 line_count: 100,
3809 param_count: 0,
3810 react_hook_count: 0,
3811 react_jsx_max_depth: 0,
3812 react_prop_count: 0,
3813 source_hash: None,
3814 contributions: Vec::new(),
3815 }],
3816 )];
3817
3818 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3819 rustc_hash::FxHashMap::default();
3820 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3821
3822 let output = crate::results::DeadCodeAnalysisArtifacts {
3823 results: fallow_types::results::AnalysisResults::default(),
3824 timings: None,
3825 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3826 modules: None,
3827 files: None,
3828 script_used_packages: rustc_hash::FxHashSet::default(),
3829 file_hashes: rustc_hash::FxHashMap::default(),
3830 };
3831
3832 let result = compute_file_scores(
3833 &modules,
3834 &file_paths,
3835 None,
3836 output,
3837 None,
3838 std::path::Path::new("/project"),
3839 )
3840 .unwrap();
3841 let mi = result.scores[0].maintainability_index;
3842 let rounded = (mi * 10.0).round() / 10.0;
3843 assert!((mi - rounded).abs() < f64::EPSILON);
3844 }
3845
3846 #[test]
3847 fn compute_file_scores_value_export_counts_tracked() {
3848 let path_a = std::path::PathBuf::from("/src/a.ts");
3849 let files = vec![crate::discover::DiscoveredFile {
3850 id: crate::discover::FileId(0),
3851 path: path_a.clone(),
3852 size_bytes: 100,
3853 }];
3854
3855 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3856 file_id: crate::discover::FileId(0),
3857 path: path_a.clone(),
3858 exports: vec![
3859 fallow_types::extract::ExportInfo {
3860 name: crate::source::ExportName::Named("a".into()),
3861 local_name: None,
3862 is_type_only: false,
3863 visibility: crate::source::VisibilityTag::None,
3864 expected_unused_reason: None,
3865 span: oxc_span::Span::empty(0),
3866 members: vec![],
3867 is_side_effect_used: false,
3868 super_class: None,
3869 },
3870 fallow_types::extract::ExportInfo {
3871 name: crate::source::ExportName::Named("b".into()),
3872 local_name: None,
3873 is_type_only: false,
3874 visibility: crate::source::VisibilityTag::None,
3875 expected_unused_reason: None,
3876 span: oxc_span::Span::empty(0),
3877 members: vec![],
3878 is_side_effect_used: false,
3879 super_class: None,
3880 },
3881 fallow_types::extract::ExportInfo {
3882 name: crate::source::ExportName::Named("T".into()),
3883 local_name: None,
3884 is_type_only: true,
3885 visibility: crate::source::VisibilityTag::None,
3886 expected_unused_reason: None,
3887 span: oxc_span::Span::empty(0),
3888 members: vec![],
3889 is_side_effect_used: false,
3890 super_class: None,
3891 },
3892 ],
3893 ..Default::default()
3894 }];
3895
3896 let graph = build_test_graph(&files, &[], &resolved_modules);
3897
3898 let modules = vec![make_module_info(
3899 0,
3900 10,
3901 vec![fallow_types::extract::FunctionComplexity {
3902 name: "fn_a".into(),
3903 line: 1,
3904 col: 0,
3905 cyclomatic: 2,
3906 cognitive: 1,
3907 line_count: 10,
3908 param_count: 0,
3909 react_hook_count: 0,
3910 react_jsx_max_depth: 0,
3911 react_prop_count: 0,
3912 source_hash: None,
3913 contributions: Vec::new(),
3914 }],
3915 )];
3916
3917 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3918 rustc_hash::FxHashMap::default();
3919 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3920
3921 let output = crate::results::DeadCodeAnalysisArtifacts {
3922 results: fallow_types::results::AnalysisResults::default(),
3923 timings: None,
3924 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3925 modules: None,
3926 files: None,
3927 script_used_packages: rustc_hash::FxHashSet::default(),
3928 file_hashes: rustc_hash::FxHashMap::default(),
3929 };
3930
3931 let result = compute_file_scores(
3932 &modules,
3933 &file_paths,
3934 None,
3935 output,
3936 None,
3937 std::path::Path::new("/project"),
3938 )
3939 .unwrap();
3940 assert_eq!(result.value_export_counts[&path_a], 2);
3941 }
3942
3943 #[test]
3944 fn compute_file_scores_top_complex_fns_zero_cognitive_excluded() {
3945 let path_a = std::path::PathBuf::from("/src/simple.ts");
3946 let files = vec![crate::discover::DiscoveredFile {
3947 id: crate::discover::FileId(0),
3948 path: path_a.clone(),
3949 size_bytes: 100,
3950 }];
3951
3952 let resolved_modules = vec![fallow_graph::resolve::ResolvedModule {
3953 file_id: crate::discover::FileId(0),
3954 path: path_a.clone(),
3955 ..Default::default()
3956 }];
3957
3958 let graph = build_test_graph(&files, &[], &resolved_modules);
3959
3960 let modules = vec![make_module_info(
3961 0,
3962 10,
3963 vec![fallow_types::extract::FunctionComplexity {
3964 name: "trivial".into(),
3965 line: 1,
3966 col: 0,
3967 cyclomatic: 1,
3968 cognitive: 0,
3969 line_count: 10,
3970 param_count: 0,
3971 react_hook_count: 0,
3972 react_jsx_max_depth: 0,
3973 react_prop_count: 0,
3974 source_hash: None,
3975 contributions: Vec::new(),
3976 }],
3977 )];
3978
3979 let mut file_paths: rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf> =
3980 rustc_hash::FxHashMap::default();
3981 file_paths.insert(crate::discover::FileId(0), &files[0].path);
3982
3983 let output = crate::results::DeadCodeAnalysisArtifacts {
3984 results: fallow_types::results::AnalysisResults::default(),
3985 timings: None,
3986 graph: Some(crate::module_graph::RetainedModuleGraph::from(graph)),
3987 modules: None,
3988 files: None,
3989 script_used_packages: rustc_hash::FxHashSet::default(),
3990 file_hashes: rustc_hash::FxHashMap::default(),
3991 };
3992
3993 let result = compute_file_scores(
3994 &modules,
3995 &file_paths,
3996 None,
3997 output,
3998 None,
3999 std::path::Path::new("/project"),
4000 )
4001 .unwrap();
4002 assert!(!result.top_complex_fns.contains_key(&path_a));
4003 }
4004
4005 fn make_fn_complexity(cyclomatic: u16) -> fallow_types::extract::FunctionComplexity {
4006 fallow_types::extract::FunctionComplexity {
4007 name: "test_fn".into(),
4008 line: 1,
4009 col: 0,
4010 cyclomatic,
4011 cognitive: 0,
4012 line_count: 10,
4013 param_count: 0,
4014 react_hook_count: 0,
4015 react_jsx_max_depth: 0,
4016 react_prop_count: 0,
4017 source_hash: None,
4018 contributions: Vec::new(),
4019 }
4020 }
4021
4022 #[test]
4023 fn crap_scores_empty_complexity() {
4024 let (max, above) = compute_crap_scores_binary(&[], true);
4025 assert!((max).abs() < f64::EPSILON);
4026 assert_eq!(above, 0);
4027 }
4028
4029 #[test]
4030 fn crap_scores_test_reachable() {
4031 let funcs = vec![make_fn_complexity(5)];
4032 let (max, above) = compute_crap_scores_binary(&funcs, true);
4033 assert!((max - 5.0).abs() < f64::EPSILON);
4034 assert_eq!(above, 0);
4035 }
4036
4037 #[test]
4038 fn crap_scores_untested_at_threshold() {
4039 let funcs = vec![make_fn_complexity(5)];
4040 let (max, above) = compute_crap_scores_binary(&funcs, false);
4041 assert!((max - 30.0).abs() < f64::EPSILON);
4042 assert_eq!(above, 1);
4043 }
4044
4045 #[test]
4046 fn crap_scores_untested_above_threshold() {
4047 let funcs = vec![make_fn_complexity(6)];
4048 let (max, above) = compute_crap_scores_binary(&funcs, false);
4049 assert!((max - 42.0).abs() < f64::EPSILON);
4050 assert_eq!(above, 1);
4051 }
4052
4053 #[test]
4054 fn crap_scores_untested_below_threshold() {
4055 let funcs = vec![make_fn_complexity(4)];
4056 let (max, above) = compute_crap_scores_binary(&funcs, false);
4057 assert!((max - 20.0).abs() < f64::EPSILON);
4058 assert_eq!(above, 0);
4059 }
4060
4061 #[test]
4062 fn crap_scores_mixed_functions_untested() {
4063 let funcs = vec![
4064 make_fn_complexity(2),
4065 make_fn_complexity(5),
4066 make_fn_complexity(8),
4067 ];
4068 let (max, above) = compute_crap_scores_binary(&funcs, false);
4069 assert!((max - 72.0).abs() < f64::EPSILON);
4070 assert_eq!(above, 2);
4071 }
4072
4073 #[test]
4074 fn crap_formula_full_coverage() {
4075 let result = crap_formula(10.0, 100.0);
4076 assert!((result - 10.0).abs() < f64::EPSILON);
4077 }
4078
4079 #[test]
4080 fn crap_formula_zero_coverage() {
4081 let result = crap_formula(5.0, 0.0);
4082 assert!((result - 30.0).abs() < f64::EPSILON);
4083 }
4084
4085 #[test]
4086 fn crap_formula_partial_coverage() {
4087 let result = crap_formula(10.0, 50.0);
4088 assert!((result - 22.5).abs() < f64::EPSILON);
4089 }
4090
4091 #[test]
4092 fn crap_formula_high_coverage_low_complexity() {
4093 let result = crap_formula(2.0, 90.0);
4094 assert!((result - 2.004).abs() < 0.001);
4095 }
4096
4097 #[test]
4098 fn istanbul_crap_with_coverage_data() {
4099 let funcs = vec![make_fn_complexity(10)];
4100 let mut functions = rustc_hash::FxHashMap::default();
4101 functions.insert(("test_fn".to_string(), 1, 0), 80.0);
4102 let file_cov = IstanbulFileCoverage { functions };
4103 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), false);
4104 assert!((result.max_crap - 10.8).abs() < 0.1);
4105 assert_eq!(result.above_threshold, 0);
4106 }
4107
4108 #[test]
4109 fn istanbul_crap_falls_back_to_binary_when_no_match() {
4110 let funcs = vec![make_fn_complexity(6)];
4111 let file_cov = IstanbulFileCoverage {
4112 functions: rustc_hash::FxHashMap::default(),
4113 };
4114 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), false);
4115 assert!((result.max_crap - 42.0).abs() < f64::EPSILON);
4116 assert_eq!(result.above_threshold, 1);
4117 }
4118
4119 #[test]
4120 fn istanbul_crap_falls_back_to_binary_when_no_file_coverage() {
4121 let funcs = vec![make_fn_complexity(5)];
4122 let result = compute_crap_scores_istanbul(&funcs, None, true);
4123 assert!((result.max_crap - 5.0).abs() < f64::EPSILON);
4124 assert_eq!(result.above_threshold, 0);
4125 }
4126
4127 #[test]
4128 fn istanbul_crap_zero_coverage_matches_binary_untested() {
4129 let funcs = vec![make_fn_complexity(5)];
4130 let mut functions = rustc_hash::FxHashMap::default();
4131 functions.insert(("test_fn".to_string(), 1, 0), 0.0);
4132 let file_cov = IstanbulFileCoverage { functions };
4133 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), false);
4134 assert!((result.max_crap - 30.0).abs() < f64::EPSILON);
4135 assert_eq!(result.above_threshold, 1);
4136 }
4137
4138 #[test]
4139 fn estimated_crap_direct_test_reference() {
4140 let funcs = vec![make_fn_complexity(10)];
4141 let mut refs = rustc_hash::FxHashSet::default();
4142 refs.insert("test_fn".to_string());
4143 let result = compute_crap_scores_estimated(
4144 &funcs,
4145 &refs,
4146 true,
4147 fallow_output::CoverageSource::Estimated,
4148 );
4149 let (max, above) = (result.max_crap, result.above_threshold);
4150 assert!((max - 10.3).abs() < 0.1);
4151 assert_eq!(above, 0);
4152 }
4153
4154 #[test]
4155 fn estimated_crap_indirect_test_reachable() {
4156 let funcs = vec![make_fn_complexity(10)];
4157 let refs = rustc_hash::FxHashSet::default();
4158 let result = compute_crap_scores_estimated(
4159 &funcs,
4160 &refs,
4161 true,
4162 fallow_output::CoverageSource::Estimated,
4163 );
4164 let (max, above) = (result.max_crap, result.above_threshold);
4165 assert!((max - 31.6).abs() < 0.1);
4166 assert_eq!(above, 1);
4167 }
4168
4169 #[test]
4170 fn estimated_crap_untested_file() {
4171 let funcs = vec![make_fn_complexity(5)];
4172 let refs = rustc_hash::FxHashSet::default();
4173 let result = compute_crap_scores_estimated(
4174 &funcs,
4175 &refs,
4176 false,
4177 fallow_output::CoverageSource::Estimated,
4178 );
4179 let (max, above) = (result.max_crap, result.above_threshold);
4180 assert!((max - 30.0).abs() < f64::EPSILON);
4181 assert_eq!(above, 1);
4182 }
4183
4184 #[test]
4185 fn estimated_crap_low_complexity_direct_ref() {
4186 let funcs = vec![make_fn_complexity(2)];
4187 let mut refs = rustc_hash::FxHashSet::default();
4188 refs.insert("test_fn".to_string());
4189 let result = compute_crap_scores_estimated(
4190 &funcs,
4191 &refs,
4192 true,
4193 fallow_output::CoverageSource::Estimated,
4194 );
4195 let (max, above) = (result.max_crap, result.above_threshold);
4196 assert!(max < 3.0);
4197 assert_eq!(above, 0);
4198 }
4199
4200 #[test]
4201 fn estimated_crap_empty() {
4202 let refs = rustc_hash::FxHashSet::default();
4203 let result = compute_crap_scores_estimated(
4204 &[],
4205 &refs,
4206 true,
4207 fallow_output::CoverageSource::Estimated,
4208 );
4209 let (max, above) = (result.max_crap, result.above_threshold);
4210 assert!((max).abs() < f64::EPSILON);
4211 assert_eq!(above, 0);
4212 }
4213
4214 fn make_export(name: &str, is_type_only: bool) -> fallow_graph::graph::ExportSymbol {
4215 fallow_graph::graph::ExportSymbol {
4216 name: fallow_types::extract::ExportName::Named(name.into()),
4217 is_type_only,
4218 is_side_effect_used: false,
4219 visibility: crate::source::VisibilityTag::None,
4220 expected_unused_reason: None,
4221 span: oxc_span::Span::default(),
4222 references: vec![],
4223 members: vec![],
4224 }
4225 }
4226
4227 #[test]
4228 fn dead_code_ratio_type_only_exports_excluded_from_denominator() {
4229 let path = std::path::Path::new("src/types.ts");
4230 let exports = vec![
4231 make_export("MyInterface", true),
4232 make_export("MyType", true),
4233 make_export("myFunction", false),
4234 ];
4235 let unused_files = rustc_hash::FxHashSet::default();
4236 let mut unused_by_path = rustc_hash::FxHashMap::default();
4237 unused_by_path.insert(path, 1_usize); let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_by_path);
4240 assert!((ratio - 1.0).abs() < f64::EPSILON);
4241 }
4242
4243 #[test]
4244 fn dead_code_ratio_only_type_exports_returns_zero() {
4245 let path = std::path::Path::new("src/types.ts");
4246 let exports = vec![
4247 make_export("MyInterface", true),
4248 make_export("MyType", true),
4249 ];
4250 let unused_files = rustc_hash::FxHashSet::default();
4251 let unused_by_path = rustc_hash::FxHashMap::default();
4252
4253 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_by_path);
4254 assert!(ratio.abs() < f64::EPSILON);
4255 }
4256
4257 #[test]
4258 fn dead_code_ratio_mixed_exports_counts_only_values() {
4259 let path = std::path::Path::new("src/component.ts");
4260 let exports = vec![
4261 make_export("Props", true),
4262 make_export("State", true),
4263 make_export("Component", false),
4264 make_export("helper", false),
4265 ];
4266 let unused_files = rustc_hash::FxHashSet::default();
4267 let mut unused_by_path = rustc_hash::FxHashMap::default();
4268 unused_by_path.insert(path, 1_usize);
4269
4270 let ratio = compute_dead_code_ratio(path, &exports, &unused_files, &unused_by_path);
4271 assert!((ratio - 0.5).abs() < f64::EPSILON);
4272 }
4273
4274 fn write_single_file_istanbul_fixture(
4275 coverage_path: &std::path::Path,
4276 source_path: &std::path::Path,
4277 fn_map: &serde_json::Value,
4278 function_hits: &serde_json::Value,
4279 ) {
4280 let mut root = serde_json::Map::new();
4281 root.insert(
4282 source_path.to_string_lossy().into_owned(),
4283 serde_json::json!({
4284 "path": source_path.to_string_lossy().into_owned(),
4285 "statementMap": {},
4286 "fnMap": fn_map,
4287 "branchMap": {},
4288 "s": {},
4289 "f": function_hits,
4290 "b": {}
4291 }),
4292 );
4293
4294 std::fs::write(coverage_path, serde_json::to_string(&root).unwrap()).unwrap();
4295 }
4296
4297 #[test]
4298 fn resolve_relative_to_root_joins_relative_with_project_root() {
4299 let resolved = resolve_relative_to_root(
4300 std::path::Path::new("coverage/coverage-final.json"),
4301 Some(std::path::Path::new("/work/my-app")),
4302 );
4303 assert_eq!(
4304 resolved,
4305 std::path::PathBuf::from("/work/my-app/coverage/coverage-final.json")
4306 );
4307 }
4308
4309 #[test]
4310 fn resolve_relative_to_root_returns_absolute_unchanged() {
4311 let resolved = resolve_relative_to_root(
4312 std::path::Path::new("/tmp/coverage-final.json"),
4313 Some(std::path::Path::new("/work/my-app")),
4314 );
4315 assert_eq!(
4316 resolved,
4317 std::path::PathBuf::from("/tmp/coverage-final.json")
4318 );
4319 }
4320
4321 #[test]
4322 fn resolve_relative_to_root_returns_windows_absolute_unchanged_on_any_host() {
4323 let path = std::path::Path::new(r"C:\coverage\coverage-final.json");
4324 let resolved = resolve_relative_to_root(path, Some(std::path::Path::new("/work/my-app")));
4325 assert_eq!(resolved, path);
4326 }
4327
4328 #[cfg(windows)]
4329 #[test]
4330 fn resolve_relative_to_root_returns_posix_rooted_path_unchanged_on_windows() {
4331 let path = std::path::Path::new(r"/ci/workspace/coverage-final.json");
4332 let resolved =
4333 resolve_relative_to_root(path, Some(std::path::Path::new(r"C:\work\my-app")));
4334 assert_eq!(resolved, path);
4335 }
4336
4337 #[test]
4338 fn resolve_relative_to_root_without_project_root_returns_relative_unchanged() {
4339 let resolved =
4340 resolve_relative_to_root(std::path::Path::new("coverage/coverage-final.json"), None);
4341 assert_eq!(
4342 resolved,
4343 std::path::PathBuf::from("coverage/coverage-final.json")
4344 );
4345 }
4346
4347 #[test]
4348 fn load_istanbul_coverage_resolves_relative_path_against_project_root() {
4349 let temp = tempfile::TempDir::new().unwrap();
4350 let source_path = temp.path().join("src/index.ts");
4351 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4352 std::fs::write(&source_path, "export function f(){}").unwrap();
4353
4354 let coverage_path = temp.path().join("coverage/coverage-final.json");
4355 std::fs::create_dir_all(coverage_path.parent().unwrap()).unwrap();
4356 write_single_file_istanbul_fixture(
4357 &coverage_path,
4358 &source_path,
4359 &serde_json::json!({
4360 "0": {
4361 "name": "f",
4362 "decl": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 21 } },
4363 "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 21 } }
4364 }
4365 }),
4366 &serde_json::json!({ "0": 1 }),
4367 );
4368
4369 let coverage = load_istanbul_coverage(
4370 std::path::Path::new("coverage/coverage-final.json"),
4371 None,
4372 Some(temp.path()),
4373 )
4374 .expect("relative path must resolve against project_root");
4375 assert!(
4376 !coverage.files.is_empty(),
4377 "expected coverage to load via project_root resolution, got {} files",
4378 coverage.files.len()
4379 );
4380 }
4381
4382 #[test]
4383 fn load_istanbul_coverage_falls_back_to_decl_line_for_missing_fn_line() {
4384 let temp = tempfile::TempDir::new().unwrap();
4385 let source_path = temp.path().join("src/service.ts");
4386 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4387 std::fs::write(&source_path, "export class DataService {}\n").unwrap();
4388
4389 let coverage_path = temp.path().join("coverage-final.json");
4390 write_single_file_istanbul_fixture(
4391 &coverage_path,
4392 &source_path,
4393 &serde_json::json!({
4394 "0": {
4395 "name": "(anonymous_0)",
4396 "decl": {
4397 "start": { "line": 5, "column": 2 },
4398 "end": { "line": 5, "column": 13 }
4399 },
4400 "loc": {
4401 "start": { "line": 5, "column": 14 },
4402 "end": { "line": 11, "column": 3 }
4403 }
4404 },
4405 "1": {
4406 "name": "(anonymous_1)",
4407 "decl": {
4408 "start": { "line": 20, "column": 14 },
4409 "end": { "line": 20, "column": 25 }
4410 },
4411 "loc": {
4412 "start": { "line": 20, "column": 28 },
4413 "end": { "line": 22, "column": 2 }
4414 }
4415 }
4416 }),
4417 &serde_json::json!({
4418 "0": 1,
4419 "1": 0
4420 }),
4421 );
4422
4423 let coverage = load_istanbul_coverage(&coverage_path, None, None).unwrap();
4424 let canonical_source = dunce::canonicalize(&source_path).unwrap();
4425 let file_coverage = coverage.get(&canonical_source).unwrap();
4426
4427 assert_eq!(file_coverage.lookup("processData", 5, 0), Some(100.0));
4428 assert_eq!(file_coverage.lookup("handleSpecial", 20, 0), Some(0.0));
4429 }
4430
4431 #[test]
4432 fn load_istanbul_coverage_indexes_explicit_and_decl_lines() {
4433 let temp = tempfile::TempDir::new().unwrap();
4434 let source_path = temp.path().join("src/handler.ts");
4435 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4436 std::fs::write(&source_path, "export const handleClick = () => {}\n").unwrap();
4437
4438 let coverage_path = temp.path().join("coverage-final.json");
4439 write_single_file_istanbul_fixture(
4440 &coverage_path,
4441 &source_path,
4442 &serde_json::json!({
4443 "0": {
4444 "name": "handleClick",
4445 "line": 40,
4446 "decl": {
4447 "start": { "line": 22, "column": 13 },
4448 "end": { "line": 22, "column": 24 }
4449 },
4450 "loc": {
4451 "start": { "line": 40, "column": 27 },
4452 "end": { "line": 42, "column": 1 }
4453 }
4454 }
4455 }),
4456 &serde_json::json!({
4457 "0": 1
4458 }),
4459 );
4460
4461 let coverage = load_istanbul_coverage(&coverage_path, None, None).unwrap();
4462 let canonical_source = dunce::canonicalize(&source_path).unwrap();
4463 let file_coverage = coverage.get(&canonical_source).unwrap();
4464
4465 assert_eq!(file_coverage.lookup("handleClick", 40, 0), Some(100.0));
4466 assert_eq!(file_coverage.lookup("handleClick", 22, 13), Some(100.0));
4467 }
4468
4469 #[test]
4470 fn load_istanbul_coverage_matches_multiline_async_arrow_decl_alias() {
4471 let temp = tempfile::TempDir::new().unwrap();
4472 let source_path = temp.path().join("src/actor.ts");
4473 std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
4474 std::fs::write(
4475 &source_path,
4476 "export const elementsFrom = async (\n locator: AnyLocator,\n options?: { missingAsEmpty?: boolean },\n): Promise<HTMLElement[]> => {\n return [];\n};\n",
4477 )
4478 .unwrap();
4479
4480 let coverage_path = temp.path().join("coverage-final.json");
4481 write_single_file_istanbul_fixture(
4482 &coverage_path,
4483 &source_path,
4484 &serde_json::json!({
4485 "0": {
4486 "name": "(anonymous_0)",
4487 "line": 4,
4488 "decl": {
4489 "start": { "line": 1, "column": 28 },
4490 "end": { "line": 4, "column": 26 }
4491 },
4492 "loc": {
4493 "start": { "line": 4, "column": 27 },
4494 "end": { "line": 6, "column": 1 }
4495 }
4496 }
4497 }),
4498 &serde_json::json!({
4499 "0": 642
4500 }),
4501 );
4502
4503 let coverage = load_istanbul_coverage(&coverage_path, None, None).unwrap();
4504 let canonical_source = dunce::canonicalize(&source_path).unwrap();
4505 let file_coverage = coverage.get(&canonical_source).unwrap();
4506
4507 assert_eq!(file_coverage.lookup("elementsFrom", 1, 28), Some(100.0));
4508 }
4509
4510 #[test]
4511 fn istanbul_lookup_exact_match() {
4512 let mut functions = rustc_hash::FxHashMap::default();
4513 functions.insert(("handleClick".to_string(), 10, 0), 85.0);
4514 let fc = IstanbulFileCoverage { functions };
4515 assert!((fc.lookup("handleClick", 10, 0).unwrap() - 85.0).abs() < f64::EPSILON);
4516 }
4517
4518 #[test]
4519 fn istanbul_lookup_fuzzy_match_within_offset() {
4520 let mut functions = rustc_hash::FxHashMap::default();
4521 functions.insert(("handleClick".to_string(), 10, 0), 72.0);
4522 let fc = IstanbulFileCoverage { functions };
4523 assert!((fc.lookup("handleClick", 11, 0).unwrap() - 72.0).abs() < f64::EPSILON);
4524 assert!((fc.lookup("handleClick", 12, 0).unwrap() - 72.0).abs() < f64::EPSILON);
4525 }
4526
4527 #[test]
4528 fn istanbul_lookup_fuzzy_match_outside_offset() {
4529 let mut functions = rustc_hash::FxHashMap::default();
4530 functions.insert(("handleClick".to_string(), 10, 0), 72.0);
4531 let fc = IstanbulFileCoverage { functions };
4532 assert!(fc.lookup("handleClick", 13, 0).is_none());
4533 }
4534
4535 #[test]
4536 fn istanbul_lookup_name_mismatch() {
4537 let mut functions = rustc_hash::FxHashMap::default();
4538 functions.insert(("handleClick".to_string(), 10, 0), 85.0);
4539 let fc = IstanbulFileCoverage { functions };
4540 assert!(fc.lookup("handleSubmit", 10, 0).is_none());
4541 }
4542
4543 #[test]
4544 fn istanbul_lookup_empty() {
4545 let fc = IstanbulFileCoverage {
4546 functions: rustc_hash::FxHashMap::default(),
4547 };
4548 assert!(fc.lookup("anything", 1, 0).is_none());
4549 }
4550
4551 #[test]
4552 fn istanbul_lookup_fuzzy_picks_closest() {
4553 let mut functions = rustc_hash::FxHashMap::default();
4554 functions.insert(("render".to_string(), 8, 0), 60.0);
4555 functions.insert(("render".to_string(), 12, 0), 90.0);
4556 let fc = IstanbulFileCoverage { functions };
4557 let result = fc.lookup("render", 10, 0);
4558 assert!(result.is_some());
4559 let pct = result.unwrap();
4560 assert!((pct - 60.0).abs() < f64::EPSILON || (pct - 90.0).abs() < f64::EPSILON);
4561 }
4562
4563 #[test]
4564 fn istanbul_lookup_anonymous_fallback_single_candidate() {
4565 let mut functions = rustc_hash::FxHashMap::default();
4566 functions.insert(("(anonymous_0)".to_string(), 28, 0), 75.0);
4567 let fc = IstanbulFileCoverage { functions };
4568 assert!((fc.lookup("myHandler", 28, 0).unwrap() - 75.0).abs() < f64::EPSILON);
4569 assert!((fc.lookup("myHandler", 30, 0).unwrap() - 75.0).abs() < f64::EPSILON);
4570 }
4571
4572 #[test]
4573 fn istanbul_lookup_anonymous_fallback_rejects_nearby_far_column() {
4574 let mut functions = rustc_hash::FxHashMap::default();
4575 functions.insert(("(anonymous_0)".to_string(), 4, 28), 75.0);
4576 let fc = IstanbulFileCoverage { functions };
4577
4578 assert!(fc.lookup("declaredHelper", 3, 0).is_none());
4579 }
4580
4581 #[test]
4582 fn istanbul_lookup_anonymous_fallback_picks_closest_when_lines_differ() {
4583 let mut functions = rustc_hash::FxHashMap::default();
4584 functions.insert(("(anonymous_0)".to_string(), 28, 0), 75.0);
4585 functions.insert(("(anonymous_1)".to_string(), 29, 0), 50.0);
4586 let fc = IstanbulFileCoverage { functions };
4587 assert!((fc.lookup("myHandler", 28, 0).unwrap() - 75.0).abs() < f64::EPSILON);
4588 }
4589
4590 #[test]
4591 fn istanbul_lookup_anonymous_fallback_picks_closest_by_col_on_same_line() {
4592 let mut functions = rustc_hash::FxHashMap::default();
4593 functions.insert(("(anonymous_0)".to_string(), 1, 23), 90.0); functions.insert(("(anonymous_1)".to_string(), 1, 43), 10.0); let fc = IstanbulFileCoverage { functions };
4596 assert!((fc.lookup("<arrow>", 1, 43).unwrap() - 10.0).abs() < f64::EPSILON);
4597 assert!((fc.lookup("<arrow>", 1, 23).unwrap() - 90.0).abs() < f64::EPSILON);
4598 }
4599
4600 #[test]
4601 fn istanbul_lookup_anonymous_fallback_bails_only_on_true_tie() {
4602 let mut functions = rustc_hash::FxHashMap::default();
4603 functions.insert(("(anonymous_0)".to_string(), 27, 0), 75.0);
4604 functions.insert(("(anonymous_1)".to_string(), 29, 0), 50.0);
4605 let fc = IstanbulFileCoverage { functions };
4606 assert!(fc.lookup("myHandler", 28, 0).is_none());
4607 }
4608
4609 #[test]
4610 fn istanbul_lookup_anonymous_fallback_outside_offset() {
4611 let mut functions = rustc_hash::FxHashMap::default();
4612 functions.insert(("(anonymous_0)".to_string(), 28, 0), 75.0);
4613 let fc = IstanbulFileCoverage { functions };
4614 assert!(fc.lookup("myHandler", 31, 0).is_none());
4615 }
4616
4617 #[test]
4618 fn istanbul_lookup_named_match_beats_nearby_anonymous() {
4619 let mut functions = rustc_hash::FxHashMap::default();
4620 functions.insert(("handleClick".to_string(), 10, 0), 90.0);
4621 functions.insert(("(anonymous_7)".to_string(), 11, 0), 10.0);
4622 let fc = IstanbulFileCoverage { functions };
4623 assert!((fc.lookup("handleClick", 10, 0).unwrap() - 90.0).abs() < f64::EPSILON);
4624 }
4625
4626 #[test]
4627 fn build_test_refs_empty() {
4628 let exports: Vec<fallow_graph::graph::ExportSymbol> = vec![];
4629 let modules: Vec<fallow_graph::graph::ModuleNode> = vec![];
4630 let refs = build_test_referenced_exports(&exports, &modules);
4631 assert!(refs.is_empty());
4632 }
4633
4634 #[test]
4635 fn build_test_refs_empty_inputs() {
4636 let exports: Vec<fallow_graph::graph::ExportSymbol> = vec![];
4637 let modules: Vec<fallow_graph::graph::ModuleNode> = vec![];
4638 let refs = build_test_referenced_exports(&exports, &modules);
4639 assert!(refs.is_empty());
4640 }
4641
4642 #[test]
4643 fn istanbul_crap_empty_complexity() {
4644 let result = compute_crap_scores_istanbul(&[], None, false);
4645 assert!((result.max_crap).abs() < f64::EPSILON);
4646 assert_eq!(result.above_threshold, 0);
4647 assert_eq!(result.matched, 0);
4648 assert_eq!(result.total, 0);
4649 }
4650
4651 #[test]
4652 fn istanbul_crap_match_statistics() {
4653 let funcs = vec![make_fn_complexity(5), {
4654 let mut f = make_fn_complexity(3);
4655 f.name = "other_fn".into();
4656 f.line = 10;
4657 f
4658 }];
4659 let mut functions = rustc_hash::FxHashMap::default();
4660 functions.insert(("test_fn".to_string(), 1, 0), 80.0);
4661 let file_cov = IstanbulFileCoverage { functions };
4662 let result = compute_crap_scores_istanbul(&funcs, Some(&file_cov), true);
4663 assert_eq!(result.matched, 1);
4664 assert_eq!(result.total, 2);
4665 }
4666
4667 #[test]
4668 fn estimated_crap_multiple_functions_mixed_coverage() {
4669 let funcs = vec![
4670 make_fn_complexity(10), {
4672 let mut f = make_fn_complexity(3);
4673 f.name = "helper".into();
4674 f.line = 20;
4675 f
4676 },
4677 ];
4678 let mut refs = rustc_hash::FxHashSet::default();
4679 refs.insert("test_fn".to_string());
4680 let result = compute_crap_scores_estimated(
4681 &funcs,
4682 &refs,
4683 true,
4684 fallow_output::CoverageSource::Estimated,
4685 );
4686 let (max, above) = (result.max_crap, result.above_threshold);
4687 assert!(max > 10.0);
4688 assert_eq!(above, 0);
4689 }
4690
4691 #[test]
4692 fn binary_crap_test_reachable() {
4693 let funcs = vec![make_fn_complexity(10)];
4694 let (max, above) = compute_crap_scores_binary(&funcs, true);
4695 assert!((max - 10.0).abs() < f64::EPSILON);
4696 assert_eq!(above, 0);
4697 }
4698
4699 #[test]
4700 fn binary_crap_not_reachable() {
4701 let funcs = vec![make_fn_complexity(6)];
4702 let (max, above) = compute_crap_scores_binary(&funcs, false);
4703 assert!((max - 42.0).abs() < f64::EPSILON);
4704 assert_eq!(above, 1);
4705 }
4706
4707 #[test]
4708 fn binary_crap_threshold_boundary() {
4709 let funcs = vec![make_fn_complexity(5)];
4710 let (max, above) = compute_crap_scores_binary(&funcs, false);
4711 assert!((max - 30.0).abs() < f64::EPSILON);
4712 assert_eq!(above, 1);
4713 }
4714
4715 #[test]
4716 fn binary_crap_empty() {
4717 let (max, above) = compute_crap_scores_binary(&[], true);
4718 assert!((max).abs() < f64::EPSILON);
4719 assert_eq!(above, 0);
4720 }
4721
4722 #[test]
4723 fn binary_crap_multiple_functions() {
4724 let funcs = vec![make_fn_complexity(3), make_fn_complexity(8)];
4725 let (max, above) = compute_crap_scores_binary(&funcs, false);
4726 assert!((max - 72.0).abs() < f64::EPSILON);
4727 assert_eq!(above, 1);
4728 }
4729}