1use fallow_output::{DirectCallerEvidence, DirectCallerSymbolEvidence, FileHealthScore};
2
3use crate::module_graph::StaticTestCoverage;
4
5use super::coverage_gaps::compute_coverage_gaps;
6pub(super) use super::coverage_gaps::{CoverageGapData, build_coverage_summary};
7use super::test_reach::build_test_referenced_exports;
8use super::threshold_overrides::ThresholdOverrideResolver;
9
10const MAX_FUNCTION_EVIDENCE: usize = 3;
11
12pub struct FileScoreOutput {
14 pub(crate) scores: Vec<FileHealthScore>,
15 pub(crate) coverage: CoverageGapData,
17 pub(crate) circular_files: rustc_hash::FxHashSet<std::path::PathBuf>,
19 pub(crate) top_complex_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
21 pub(crate) crap_target_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
23 pub(crate) entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
25 pub(crate) value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
27 pub(crate) unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
29 pub(crate) cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>>,
31 pub(crate) direct_callers: rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>>,
33 pub(crate) analysis_counts: crate::vital_signs::AnalysisCounts,
35 pub(crate) prop_drilling_chains: Vec<fallow_types::output_dead_code::PropDrillingChainFinding>,
40 pub(crate) render_fan_in: Option<fallow_types::results::RenderFanInMetric>,
46 pub(crate) analysis_snapshot: AnalysisCountsSnapshot,
50 pub(crate) istanbul_matched: usize,
52 pub(crate) istanbul_total: usize,
53 pub(crate) istanbul_files_joined: usize,
57 pub(crate) istanbul_files_total: usize,
59 pub(crate) coverage_input_format: Option<fallow_output::CoverageInputFormat>,
61 pub(crate) per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
65 pub(crate) template_inherit_provenance:
72 rustc_hash::FxHashMap<std::path::PathBuf, std::path::PathBuf>,
73 pub(crate) static_links: Option<crate::change_coupling::StaticLinkIndex>,
77}
78
79struct FileScoreOutputParts<'a> {
80 graph: &'a fallow_graph::graph::ModuleGraph,
81 with_static_links: bool,
82 file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
83 results: &'a crate::results::AnalysisResults,
84 scores: Vec<FileHealthScore>,
85 coverage: CoverageGapData,
86 circular_files: rustc_hash::FxHashSet<std::path::PathBuf>,
87 top_complex_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
88 crap_target_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
89 entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
90 value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
91 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
92 cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>>,
93 direct_callers: rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>>,
94 istanbul_matched: usize,
95 istanbul_total: usize,
96 istanbul_files_joined: usize,
97 istanbul_files_total: usize,
98 coverage_input_format: Option<fallow_output::CoverageInputFormat>,
99 per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
100 template_inherit: rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
101}
102
103#[derive(Clone, Default)]
109pub struct AnalysisCountsSnapshot {
110 unused_file_paths: Vec<std::path::PathBuf>,
112 unused_export_paths: Vec<std::path::PathBuf>,
115 unused_dep_package_paths: Vec<std::path::PathBuf>,
119 circular_dep_groups: Vec<Vec<std::path::PathBuf>>,
122 module_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
125}
126
127impl AnalysisCountsSnapshot {
128 pub(crate) fn counts_for(
144 &self,
145 subset: &crate::health::SubsetFilter<'_>,
146 defaults: &crate::vital_signs::AnalysisCounts,
147 ) -> crate::vital_signs::AnalysisCounts {
148 if subset.is_full() {
149 return *defaults;
150 }
151 let dead_files = self
152 .unused_file_paths
153 .iter()
154 .filter(|p| subset.matches(p))
155 .count();
156 let dead_exports = self
157 .unused_export_paths
158 .iter()
159 .filter(|p| subset.matches(p))
160 .count();
161 let unused_deps = self
162 .unused_dep_package_paths
163 .iter()
164 .filter(|dep_path| dep_in_subset(subset, dep_path))
165 .count();
166 let circular_deps = self
167 .circular_dep_groups
168 .iter()
169 .filter(|cycle| cycle.iter().any(|p| subset.matches(p)))
170 .count();
171 let total_exports = self
172 .module_export_counts
173 .iter()
174 .filter(|(p, _)| subset.matches(p))
175 .map(|(_, n)| *n)
176 .sum();
177 crate::vital_signs::AnalysisCounts {
178 total_exports,
179 dead_files,
180 dead_exports,
181 unused_deps,
182 circular_deps,
183 total_deps: defaults.total_deps,
184 }
185 }
186}
187
188fn dep_in_subset(subset: &crate::health::SubsetFilter<'_>, dep_path: &std::path::Path) -> bool {
195 match subset {
196 crate::health::SubsetFilter::Full => true,
197 crate::health::SubsetFilter::Paths(set) => {
198 let Some(workspace_root) = dep_path.parent() else {
199 return false;
200 };
201 set.iter().any(|p| p.starts_with(workspace_root))
202 }
203 }
204}
205
206#[expect(
216 clippy::cast_possible_truncation,
217 reason = "line count is bounded by source file size"
218)]
219fn aggregate_complexity(module: &crate::source::ModuleInfo) -> (u32, u32, usize, u32) {
220 let cyc: u32 = module
221 .complexity
222 .iter()
223 .map(|f| u32::from(f.cyclomatic))
224 .sum();
225 let cog: u32 = module
226 .complexity
227 .iter()
228 .map(|f| u32::from(f.cognitive))
229 .sum();
230 let funcs = module.complexity.len();
231 let lines = module.line_offsets.len() as u32;
232 (cyc, cog, funcs, lines)
233}
234
235fn compute_dead_code_ratio(
243 path: &std::path::Path,
244 exports: &[fallow_graph::graph::ExportSymbol],
245 unused_files: &rustc_hash::FxHashSet<&std::path::Path>,
246 unused_exports_by_path: &rustc_hash::FxHashMap<&std::path::Path, usize>,
247) -> f64 {
248 if unused_files.contains(path) {
249 return 1.0;
250 }
251 let value_exports = exports.iter().filter(|e| !e.is_type_only).count();
252 if value_exports == 0 {
253 return 0.0;
254 }
255 let unused = unused_exports_by_path.get(path).copied().unwrap_or(0);
256 (unused as f64 / value_exports as f64).min(1.0)
257}
258
259fn compute_complexity_density(total_cyclomatic: u32, lines: u32) -> f64 {
263 if lines > 0 {
264 f64::from(total_cyclomatic) / f64::from(lines)
265 } else {
266 0.0
267 }
268}
269
270pub(super) const CRAP_THRESHOLD: f64 = 30.0;
273
274#[derive(Clone, Copy)]
277pub(super) struct CrapScoreThresholds<'a> {
278 pub(super) resolver: &'a ThresholdOverrideResolver,
279 pub(super) enforce_crap: bool,
280}
281
282pub(super) struct CrapCeilingLookup<'a> {
289 resolver: &'a ThresholdOverrideResolver,
290 relative: &'a std::path::Path,
291 enforce_crap: bool,
292 suppressions: &'a [crate::suppress::Suppression],
293}
294
295#[derive(Debug, Default)]
302struct CrapThresholdSignals {
303 above: usize,
305 exempted: usize,
309 min_ceiling: Option<f64>,
311 suppressed: usize,
312 unsuppressed_max: f64,
313 unsuppressed_min_ceiling: Option<f64>,
314 eligible_functions: Vec<(String, u32, u16)>,
316}
317
318impl<'a> CrapCeilingLookup<'a> {
319 pub(super) fn new(
320 thresholds: CrapScoreThresholds<'a>,
321 relative: &'a std::path::Path,
322 suppressions: &'a [crate::suppress::Suppression],
323 ) -> Self {
324 Self {
325 resolver: thresholds.resolver,
326 relative,
327 enforce_crap: thresholds.enforce_crap,
328 suppressions,
329 }
330 }
331
332 fn observe(
335 &self,
336 function: &fallow_types::extract::FunctionComplexity,
337 crap_rounded: f64,
338 signals: &mut CrapThresholdSignals,
339 ) {
340 let ceiling = self
341 .resolver
342 .effective_max_crap(self.relative, &function.name);
343 signals.min_ceiling = Some(signals.min_ceiling.map_or(ceiling, |m| m.min(ceiling)));
344 if (!self.enforce_crap || crap_rounded < ceiling) && crap_rounded >= CRAP_THRESHOLD {
345 signals.exempted += 1;
346 }
347 if crate::suppress::is_suppressed(
348 self.suppressions,
349 function.line,
350 crate::suppress::IssueKind::Complexity,
351 ) {
352 signals.suppressed += 1;
353 return;
354 }
355 signals.unsuppressed_max = signals.unsuppressed_max.max(crap_rounded);
356 signals.unsuppressed_min_ceiling = Some(
357 signals
358 .unsuppressed_min_ceiling
359 .map_or(ceiling, |minimum| minimum.min(ceiling)),
360 );
361 if self.enforce_crap && crap_rounded >= ceiling {
362 signals.above += 1;
363 signals.eligible_functions.push((
364 function.name.clone(),
365 function.line,
366 function.cognitive,
367 ));
368 }
369 }
370}
371
372#[derive(Debug, Clone, Copy)]
374pub struct PerFunctionCrap {
375 pub(crate) line: u32,
377 pub(crate) col: u32,
383 pub(crate) crap: f64,
385 pub(crate) coverage_pct: Option<f64>,
388 pub(crate) coverage_tier: fallow_output::CoverageTier,
392 pub(crate) coverage_source: fallow_output::CoverageSource,
399}
400
401#[derive(Debug)]
403struct IstanbulCrapResult {
404 pub max_crap: f64,
405 pub signals: CrapThresholdSignals,
407 pub matched: usize,
409 pub total: usize,
411 pub per_function: Vec<PerFunctionCrap>,
413}
414
415fn compute_crap_scores_istanbul(
426 complexity: &[fallow_types::extract::FunctionComplexity],
427 file_coverage: Option<&IstanbulFileCoverage>,
428 is_test_reachable: bool,
429 ceilings: &CrapCeilingLookup<'_>,
430) -> IstanbulCrapResult {
431 if complexity.is_empty() {
432 return IstanbulCrapResult {
433 max_crap: 0.0,
434 signals: CrapThresholdSignals::default(),
435 matched: 0,
436 total: 0,
437 per_function: Vec::new(),
438 };
439 }
440 let mut max = 0.0_f64;
441 let mut signals = CrapThresholdSignals::default();
442 let mut matched = 0usize;
443 let mut total = 0usize;
444 let mut per_function = Vec::with_capacity(complexity.len());
445 for f in complexity {
446 if fallow_types::extract::is_synthetic_template_unit(&f.name)
455 || fallow_types::extract::is_synthetic_module_unit(&f.name)
456 {
457 continue;
458 }
459 total += 1;
460 let cc = f64::from(ceilings.resolver.gate_cyclomatic(f));
461 let (crap, coverage_pct, tier, source) =
462 crap_for_function(f, cc, file_coverage, is_test_reachable, &mut matched);
463 let crap_rounded = (crap * 10.0).round() / 10.0;
464 max = max.max(crap);
465 ceilings.observe(f, crap_rounded, &mut signals);
466 per_function.push(PerFunctionCrap {
467 line: f.line,
468 col: f.col,
469 crap: crap_rounded,
470 coverage_pct,
471 coverage_tier: tier,
472 coverage_source: source,
473 });
474 }
475 IstanbulCrapResult {
476 max_crap: (max * 10.0).round() / 10.0,
477 signals,
478 matched,
479 total,
480 per_function,
481 }
482}
483
484#[expect(
488 clippy::suboptimal_flops,
489 reason = "cc * cc + cc matches the CRAP formula specification"
490)]
491fn crap_for_function(
492 f: &fallow_types::extract::FunctionComplexity,
493 cc: f64,
494 file_coverage: Option<&IstanbulFileCoverage>,
495 is_test_reachable: bool,
496 matched: &mut usize,
497) -> (
498 f64,
499 Option<f64>,
500 fallow_output::CoverageTier,
501 fallow_output::CoverageSource,
502) {
503 let lookup = file_coverage.and_then(|fc| fc.lookup_function(f));
504 if let Some(cov_pct) = lookup {
505 *matched += 1;
506 return (
507 crap_formula(cc, cov_pct),
508 Some(cov_pct),
509 fallow_output::CoverageTier::from_pct(cov_pct),
510 fallow_output::CoverageSource::Istanbul,
511 );
512 }
513 if is_test_reachable {
517 return (
518 crap_formula(cc, INDIRECT_TEST_COVERAGE_ESTIMATE),
519 None,
520 fallow_output::CoverageTier::from_pct(INDIRECT_TEST_COVERAGE_ESTIMATE),
521 fallow_output::CoverageSource::Estimated,
522 );
523 }
524 (
525 cc * cc + cc,
526 None,
527 fallow_output::CoverageTier::None,
528 fallow_output::CoverageSource::Estimated,
529 )
530}
531
532const DIRECT_TEST_COVERAGE_ESTIMATE: f64 = 85.0;
535
536const INDIRECT_TEST_COVERAGE_ESTIMATE: f64 = 40.0;
540const MAX_DIRECT_CALLER_EVIDENCE: usize = 5;
541
542#[derive(Debug)]
552struct EstimatedCrapResult {
553 pub max_crap: f64,
554 pub signals: CrapThresholdSignals,
556 pub per_function: Vec<PerFunctionCrap>,
557}
558
559fn compute_crap_scores_estimated(
560 complexity: &[fallow_types::extract::FunctionComplexity],
561 test_referenced_exports: &rustc_hash::FxHashSet<String>,
562 is_test_reachable: bool,
563 coverage_source: fallow_output::CoverageSource,
564 ceilings: &CrapCeilingLookup<'_>,
565) -> EstimatedCrapResult {
566 if complexity.is_empty() {
567 return EstimatedCrapResult {
568 max_crap: 0.0,
569 signals: CrapThresholdSignals::default(),
570 per_function: Vec::new(),
571 };
572 }
573 let mut max = 0.0_f64;
574 let mut signals = CrapThresholdSignals::default();
575 let mut per_function = Vec::with_capacity(complexity.len());
576 for f in complexity {
577 if fallow_types::extract::is_synthetic_template_unit(&f.name)
582 || fallow_types::extract::is_synthetic_module_unit(&f.name)
583 {
584 continue;
585 }
586 let cc = f64::from(ceilings.resolver.gate_cyclomatic(f));
587 let estimated_coverage = if test_referenced_exports.contains(f.identity_name()) {
591 DIRECT_TEST_COVERAGE_ESTIMATE
592 } else if is_test_reachable {
593 INDIRECT_TEST_COVERAGE_ESTIMATE
594 } else {
595 0.0
596 };
597 let crap = crap_formula(cc, estimated_coverage);
598 let crap_rounded = (crap * 10.0).round() / 10.0;
599 max = max.max(crap);
600 ceilings.observe(f, crap_rounded, &mut signals);
601 per_function.push(PerFunctionCrap {
602 line: f.line,
603 col: f.col,
604 crap: crap_rounded,
605 coverage_pct: None,
606 coverage_tier: fallow_output::CoverageTier::from_pct(estimated_coverage),
607 coverage_source,
608 });
609 }
610 EstimatedCrapResult {
611 max_crap: (max * 10.0).round() / 10.0,
612 signals,
613 per_function,
614 }
615}
616
617#[derive(Debug, Clone)]
631pub(super) struct TemplateInheritContext {
632 pub is_test_reachable: bool,
633 pub test_referenced_exports: rustc_hash::FxHashSet<String>,
634 pub provenance_owner: std::path::PathBuf,
639}
640
641fn build_template_inherit_contexts(
663 graph: &fallow_graph::graph::ModuleGraph,
664 test_coverage: StaticTestCoverage<'_>,
665 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
666 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
667) -> rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext> {
668 let mut out = rustc_hash::FxHashMap::default();
669 for node in &graph.modules {
670 if let Some(context) =
671 template_inherit_context_for_node(node, graph, test_coverage, module_by_id, file_paths)
672 {
673 out.insert(node.file_id, context);
674 }
675 }
676 out
677}
678
679fn template_inherit_context_for_node(
680 node: &fallow_graph::graph::ModuleNode,
681 graph: &fallow_graph::graph::ModuleGraph,
682 test_coverage: StaticTestCoverage<'_>,
683 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
684 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
685) -> Option<TemplateInheritContext> {
686 if !is_template_inherit_candidate(node, module_by_id, file_paths) {
687 return None;
688 }
689 let importers = graph.reverse_deps.get(node.file_id.0 as usize)?;
690 template_inherit_context_from_importers(
691 importers,
692 graph,
693 test_coverage,
694 module_by_id,
695 file_paths,
696 )
697}
698
699fn is_template_inherit_candidate(
700 node: &fallow_graph::graph::ModuleNode,
701 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
702 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
703) -> bool {
704 let Some(path) = file_paths.get(&node.file_id) else {
705 return false;
706 };
707 if !path
708 .extension()
709 .and_then(|ext| ext.to_str())
710 .is_some_and(|ext| ext.eq_ignore_ascii_case("html"))
711 {
712 return false;
713 }
714 module_by_id.get(&node.file_id).is_some_and(|module| {
715 module
716 .complexity
717 .iter()
718 .any(|finding| finding.name.as_str() == "<template>")
719 })
720}
721
722fn template_inherit_context_from_importers(
723 importers: &[crate::discover::FileId],
724 graph: &fallow_graph::graph::ModuleGraph,
725 test_coverage: StaticTestCoverage<'_>,
726 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
727 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
728) -> Option<TemplateInheritContext> {
729 let mut any_reachable = false;
730 let mut combined_refs = rustc_hash::FxHashSet::default();
731 let mut provenance: Option<std::path::PathBuf> = None;
732 let mut first_owner: Option<std::path::PathBuf> = None;
733
734 for &importer_id in importers {
735 let Some((owner_node, owner_path)) =
736 template_owner(importer_id, graph, module_by_id, file_paths)
737 else {
738 continue;
739 };
740 if first_owner.is_none() {
741 first_owner = Some((*owner_path).clone());
742 }
743 if test_coverage.covers_file(owner_node.file_id) {
744 any_reachable = true;
745 provenance.get_or_insert_with(|| (*owner_path).clone());
746 let refs = build_test_referenced_exports(
747 owner_node.file_id,
748 &owner_node.exports,
749 test_coverage,
750 );
751 combined_refs.extend(refs);
752 }
753 }
754
755 let provenance_owner = provenance.or(first_owner)?;
756 Some(TemplateInheritContext {
757 is_test_reachable: any_reachable,
758 test_referenced_exports: combined_refs,
759 provenance_owner,
760 })
761}
762
763fn template_owner<'a>(
764 importer_id: crate::discover::FileId,
765 graph: &'a fallow_graph::graph::ModuleGraph,
766 module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
767 file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
768) -> Option<(&'a fallow_graph::graph::ModuleNode, &'a std::path::PathBuf)> {
769 let owner_node = graph.modules.get(importer_id.0 as usize)?;
770 let owner_path = *file_paths.get(&importer_id)?;
771 if !is_template_owner_path(owner_path) || graph.test_entry_points.contains(&importer_id) {
772 return None;
773 }
774 let owner_has_component = module_by_id
775 .get(&importer_id)
776 .is_some_and(|module| module.has_angular_component_template_url);
777 owner_has_component.then_some((owner_node, owner_path))
778}
779
780fn is_template_owner_path(path: &std::path::Path) -> bool {
781 path.extension()
782 .and_then(|ext| ext.to_str())
783 .is_some_and(|ext| {
784 matches!(
785 ext.to_ascii_lowercase().as_str(),
786 "ts" | "tsx" | "mts" | "cts"
787 )
788 })
789}
790
791fn collect_direct_callers(
792 graph: &fallow_graph::graph::ModuleGraph,
793 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
794) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>> {
795 let mut callers_by_target = rustc_hash::FxHashMap::default();
796 for node in &graph.modules {
797 let Some(target_path) = file_paths.get(&node.file_id) else {
798 continue;
799 };
800 let mut callers = graph
801 .direct_importer_summaries(node.file_id)
802 .into_iter()
803 .filter_map(|summary| {
804 file_paths
805 .get(&summary.source)
806 .map(|caller_path| DirectCallerEvidence {
807 path: (*caller_path).clone(),
808 symbols: summary
809 .symbols
810 .into_iter()
811 .map(|symbol| DirectCallerSymbolEvidence {
812 imported: symbol.imported,
813 local: symbol.local,
814 type_only: symbol.type_only,
815 })
816 .collect(),
817 })
818 })
819 .collect::<Vec<_>>();
820 callers.sort_by(|a, b| a.path.cmp(&b.path));
821 callers.truncate(MAX_DIRECT_CALLER_EVIDENCE);
822 if !callers.is_empty() {
823 callers_by_target.insert((*target_path).clone(), callers);
824 }
825 }
826 callers_by_target
827}
828
829#[expect(
832 clippy::suboptimal_flops,
833 reason = "explicit multiplication matches the CRAP formula specification"
834)]
835fn crap_formula(cc: f64, coverage_pct: f64) -> f64 {
836 let uncovered = 1.0 - coverage_pct / 100.0;
837 cc * cc * uncovered * uncovered * uncovered + cc
838}
839
840const ANONYMOUS_FALLBACK_MAX_COLUMN_DRIFT: u32 = 16;
846
847const ALIAS_FUZZ_MAX_LINE_DRIFT: u32 = 2;
852
853#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
854struct IstanbulPosition {
855 line: u32,
856 col: u32,
857}
858
859impl IstanbulPosition {
860 const fn new(line: u32, col: u32) -> Self {
861 Self { line, col }
862 }
863
864 const fn distance_from(self, target: Self) -> (u32, u32) {
865 (
866 self.line.abs_diff(target.line),
867 self.col.abs_diff(target.col),
868 )
869 }
870}
871
872#[derive(Clone, Copy, Debug, Eq, PartialEq)]
873struct IstanbulSpan {
874 start: IstanbulPosition,
875 end: IstanbulPosition,
876}
877
878impl IstanbulSpan {
879 fn from_entry(
880 fn_entry: &oxc_coverage_instrument::FnEntry,
881 source_index: Option<&IstanbulSourceIndex<'_>>,
882 ) -> Option<Self> {
883 let start = normalized_istanbul_position(
884 fn_entry.loc.start.line,
885 fn_entry.loc.start.column,
886 source_index,
887 )?;
888 let end = normalized_istanbul_position(
889 fn_entry.loc.end.line,
890 fn_entry.loc.end.column,
891 source_index,
892 )?;
893 (start.line > 0 && end.line > 0 && start < end).then_some(Self { start, end })
894 }
895
896 fn header_from_entry(
897 fn_entry: &oxc_coverage_instrument::FnEntry,
898 source_index: Option<&IstanbulSourceIndex<'_>>,
899 ) -> Option<Self> {
900 let start = normalized_istanbul_position(
901 fn_entry.decl.start.line,
902 fn_entry.decl.start.column,
903 source_index,
904 )?;
905 let end = normalized_istanbul_position(
906 fn_entry.loc.start.line,
907 fn_entry.loc.start.column,
908 source_index,
909 )?;
910 (start.line > 0 && end.line > 0 && start < end).then_some(Self { start, end })
911 }
912
913 fn contains(self, position: IstanbulPosition) -> bool {
915 self.start <= position && position < self.end
916 }
917
918 fn strictly_contains(self, other: Self) -> bool {
919 self != other && self.start <= other.start && other.end <= self.end
920 }
921}
922
923#[derive(Clone, Copy, Debug, Eq, PartialEq)]
932struct IstanbulAlias {
933 position: IstanbulPosition,
934 primary: bool,
935}
936
937#[derive(Clone, Copy, Debug, Default)]
940struct IstanbulAliasCounts {
941 primary: usize,
942 secondary: usize,
943}
944
945impl IstanbulAliasCounts {
946 fn add(&mut self, alias: IstanbulAlias) {
947 if alias.primary {
948 self.primary += 1;
949 } else {
950 self.secondary += 1;
951 }
952 }
953
954 const fn is_unique(self, alias: IstanbulAlias) -> bool {
957 if alias.primary {
958 self.primary == 1
959 } else {
960 self.primary == 0 && self.secondary == 1
961 }
962 }
963
964 const fn has_secondary_only_collision(self) -> bool {
965 self.primary == 0 && self.secondary > 1
966 }
967}
968
969fn is_anonymous_istanbul_name(name: &str) -> bool {
970 name.starts_with("(anonymous_")
971}
972
973struct IstanbulFunctionCoverage {
974 name: String,
975 coverage_pct: f64,
976 aliases: Vec<IstanbulAlias>,
977 decl_start: IstanbulPosition,
981 header_holds_other_fn: bool,
985 header_span: Option<IstanbulSpan>,
986 body_span: Option<IstanbulSpan>,
987}
988
989impl IstanbulFunctionCoverage {
990 fn answers_to(&self, name: &str) -> bool {
993 if self.name == name {
994 return true;
995 }
996 accessor_property_name(&self.name) == Some(name)
997 }
998
999 fn nearest_alias(
1000 &self,
1001 target: IstanbulPosition,
1002 max_column_drift: Option<u32>,
1003 ) -> Option<(u32, u32)> {
1004 self.aliases
1005 .iter()
1006 .filter_map(|alias| {
1007 let distance = alias.position.distance_from(target);
1008 if distance.0 > ALIAS_FUZZ_MAX_LINE_DRIFT {
1009 return None;
1010 }
1011 if distance.0 > 0 && max_column_drift.is_some_and(|maximum| distance.1 > maximum) {
1012 return None;
1013 }
1014 Some(distance)
1015 })
1016 .min()
1017 }
1018}
1019
1020pub struct IstanbulFileCoverage {
1023 functions: Vec<IstanbulFunctionCoverage>,
1027 alias_index: rustc_hash::FxHashMap<(String, u32, u32), usize>,
1032 ambiguous_aliases: rustc_hash::FxHashSet<(String, u32, u32)>,
1036 ambiguous_anonymous_aliases: rustc_hash::FxHashSet<IstanbulPosition>,
1040 alias_lines: Vec<(u32, usize)>,
1045 header_starts: Vec<(u32, usize)>,
1048 max_header_height: u32,
1052 relocated: bool,
1056}
1057
1058fn mark_headers_holding_other_fns(functions: &mut [IstanbulFunctionCoverage]) {
1064 let mut declarations: Vec<IstanbulPosition> = functions
1065 .iter()
1066 .map(|function| function.decl_start)
1067 .collect();
1068 declarations.sort_unstable();
1069 for function in functions {
1070 let Some(span) = function.header_span else {
1071 continue;
1072 };
1073 let first = declarations.partition_point(|position| *position < span.start);
1076 let past = declarations.partition_point(|position| *position < span.end);
1077 function.header_holds_other_fn = past - first > 1;
1078 }
1079}
1080
1081struct IstanbulLineIndexes {
1085 alias_lines: Vec<(u32, usize)>,
1086 header_starts: Vec<(u32, usize)>,
1087 max_header_height: u32,
1088}
1089
1090impl IstanbulLineIndexes {
1091 fn build(functions: &[IstanbulFunctionCoverage]) -> Self {
1092 let mut alias_lines: Vec<(u32, usize)> = functions
1093 .iter()
1094 .enumerate()
1095 .flat_map(|(function_index, function)| {
1096 function
1097 .aliases
1098 .iter()
1099 .map(move |alias| (alias.position.line, function_index))
1100 })
1101 .collect();
1102 alias_lines.sort_unstable();
1103
1104 let mut header_starts: Vec<(u32, usize)> = Vec::new();
1105 let mut max_header_height = 0;
1106 for (function_index, function) in functions.iter().enumerate() {
1107 if let Some(span) = function.header_span {
1108 header_starts.push((span.start.line, function_index));
1109 max_header_height = max_header_height.max(span.end.line - span.start.line);
1112 }
1113 }
1114 header_starts.sort_unstable();
1115
1116 Self {
1117 alias_lines,
1118 header_starts,
1119 max_header_height,
1120 }
1121 }
1122}
1123
1124impl IstanbulFileCoverage {
1125 pub fn lookup_function(
1131 &self,
1132 function: &fallow_types::extract::FunctionComplexity,
1133 ) -> Option<f64> {
1134 if function.is_private_member {
1135 return self.lookup_private(&function.name, function.line, function.col);
1136 }
1137 self.lookup(function.identity_name(), function.line, function.col)
1142 }
1143
1144 fn new(mut functions: Vec<IstanbulFunctionCoverage>, relocated: bool) -> Self {
1145 let mut named_alias_counts: rustc_hash::FxHashMap<
1146 (String, IstanbulPosition),
1147 IstanbulAliasCounts,
1148 > = rustc_hash::FxHashMap::default();
1149 let mut anonymous_alias_counts: rustc_hash::FxHashMap<
1150 IstanbulPosition,
1151 IstanbulAliasCounts,
1152 > = rustc_hash::FxHashMap::default();
1153 for function in &functions {
1154 let is_anonymous = is_anonymous_istanbul_name(&function.name);
1155 for alias in &function.aliases {
1156 named_alias_counts
1157 .entry((function.name.clone(), alias.position))
1158 .or_default()
1159 .add(*alias);
1160 if is_anonymous {
1161 anonymous_alias_counts
1162 .entry(alias.position)
1163 .or_default()
1164 .add(*alias);
1165 }
1166 }
1167 }
1168
1169 let mut ambiguous_aliases = rustc_hash::FxHashSet::default();
1174 let mut ambiguous_anonymous_aliases = rustc_hash::FxHashSet::default();
1175 for function in &mut functions {
1176 let name = function.name.clone();
1177 let is_anonymous = is_anonymous_istanbul_name(&name);
1178 function.aliases.retain(|alias| {
1179 let named = named_alias_counts
1180 .get(&(name.clone(), alias.position))
1181 .copied()
1182 .unwrap_or_default();
1183 let anonymous = is_anonymous
1184 .then(|| anonymous_alias_counts.get(&alias.position).copied())
1185 .flatten();
1186 let unique = named.is_unique(*alias)
1187 && anonymous.is_none_or(|counts| counts.is_unique(*alias));
1188 if unique {
1189 return true;
1190 }
1191 if alias.primary {
1192 ambiguous_aliases.insert((
1193 name.clone(),
1194 alias.position.line,
1195 alias.position.col,
1196 ));
1197 if anonymous.is_some_and(|counts| counts.primary > 1) {
1198 ambiguous_anonymous_aliases.insert(alias.position);
1199 }
1200 } else {
1201 if named.has_secondary_only_collision() {
1202 ambiguous_aliases.insert((
1203 name.clone(),
1204 alias.position.line,
1205 alias.position.col,
1206 ));
1207 }
1208 if anonymous.is_some_and(IstanbulAliasCounts::has_secondary_only_collision) {
1209 ambiguous_anonymous_aliases.insert(alias.position);
1210 }
1211 }
1212 false
1213 });
1214 }
1215
1216 let mut alias_index = rustc_hash::FxHashMap::default();
1217 for (function_index, function) in functions.iter().enumerate() {
1218 for alias in &function.aliases {
1219 alias_index.insert(
1220 (
1221 function.name.clone(),
1222 alias.position.line,
1223 alias.position.col,
1224 ),
1225 function_index,
1226 );
1227 if let Some(property) = accessor_property_name(&function.name) {
1230 alias_index
1231 .entry((
1232 property.to_string(),
1233 alias.position.line,
1234 alias.position.col,
1235 ))
1236 .or_insert(function_index);
1237 }
1238 }
1239 }
1240
1241 mark_headers_holding_other_fns(&mut functions);
1242 let indexes = IstanbulLineIndexes::build(&functions);
1243
1244 Self {
1245 functions,
1246 alias_index,
1247 ambiguous_aliases,
1248 ambiguous_anonymous_aliases,
1249 alias_lines: indexes.alias_lines,
1250 header_starts: indexes.header_starts,
1251 max_header_height: indexes.max_header_height,
1252 relocated,
1253 }
1254 }
1255
1256 fn fuzz_window(&self, target: IstanbulPosition) -> Vec<usize> {
1268 let low = target.line.saturating_sub(ALIAS_FUZZ_MAX_LINE_DRIFT);
1269 let high = target.line.saturating_add(ALIAS_FUZZ_MAX_LINE_DRIFT);
1270 let first = self.alias_lines.partition_point(|(line, _)| *line < low);
1271 let past = self.alias_lines.partition_point(|(line, _)| *line <= high);
1272 let mut window: Vec<usize> = self.alias_lines[first..past]
1273 .iter()
1274 .map(|(_, function_index)| *function_index)
1275 .collect();
1276 window.sort_unstable();
1277 window.dedup();
1278 window
1279 }
1280
1281 fn lookup_private(&self, name: &str, line: u32, col: u32) -> Option<f64> {
1290 let exact_key = (name.to_string(), line, col);
1291 if self.ambiguous_aliases.contains(&exact_key) {
1292 return None;
1293 }
1294 if let Some(&function_index) = self.alias_index.get(&exact_key) {
1295 return Some(self.functions[function_index].coverage_pct);
1296 }
1297 let target = IstanbulPosition::new(line, col);
1298 let window = self.fuzz_window(target);
1299 let signature_owners = self.header_spans_containing(target);
1300 let mut candidates = self.named_candidates(name, target, &window, &signature_owners);
1301 let (_, function_index) = candidates.next()?;
1302 if candidates.next().is_some() {
1303 return None;
1304 }
1305 Some(self.functions[function_index].coverage_pct)
1306 }
1307
1308 fn named_candidates<'a>(
1317 &'a self,
1318 name: &'a str,
1319 target: IstanbulPosition,
1320 window: &'a [usize],
1321 signature_owners: &'a [usize],
1322 ) -> impl Iterator<Item = ((u32, u32), usize)> + 'a {
1323 window
1324 .iter()
1325 .copied()
1326 .filter(move |function_index| self.functions[*function_index].answers_to(name))
1327 .filter_map(move |function_index| {
1328 self.functions[function_index]
1329 .nearest_alias(target, None)
1330 .map(|distance| (distance, function_index))
1331 })
1332 .filter(move |(distance, function_index)| {
1333 *distance == (0, 0)
1334 || !self.foreign_signature_blocks(signature_owners, *function_index, target)
1335 })
1336 }
1337
1338 pub(crate) fn lookup(&self, name: &str, line: u32, col: u32) -> Option<f64> {
1371 let exact_key = (name.to_string(), line, col);
1372 if self.ambiguous_aliases.contains(&exact_key) {
1373 return None;
1374 }
1375 if let Some(&function_index) = self.alias_index.get(&exact_key) {
1376 return Some(self.functions[function_index].coverage_pct);
1377 }
1378
1379 let target = IstanbulPosition::new(line, col);
1380 let window = self.fuzz_window(target);
1381 let signature_owners = self.header_spans_containing(target);
1382 if let Some(function) = self
1383 .named_candidates(name, target, &window, &signature_owners)
1384 .min_by_key(|(distance, _)| *distance)
1385 .map(|(_, function_index)| &self.functions[function_index])
1386 {
1387 return Some(function.coverage_pct);
1388 }
1389 if self.relocated
1390 && let Some(pct) = self.unambiguous_named_pct(name)
1391 {
1392 return Some(pct);
1393 }
1394 if self.ambiguous_anonymous_aliases.contains(&target) {
1395 return self.unique_anonymous_header_match(&signature_owners);
1396 }
1397
1398 let mut nearest_distance: Option<(u32, u32)> = None;
1399 let mut nearest_functions = Vec::new();
1400 for function_index in window {
1401 let function = &self.functions[function_index];
1402 if !is_anonymous_istanbul_name(&function.name) {
1403 continue;
1404 }
1405 let Some(distance) =
1406 function.nearest_alias(target, Some(ANONYMOUS_FALLBACK_MAX_COLUMN_DRIFT))
1407 else {
1408 continue;
1409 };
1410 if distance != (0, 0)
1414 && self.foreign_signature_blocks(&signature_owners, function_index, target)
1415 {
1416 continue;
1417 }
1418 match nearest_distance {
1419 None => {
1420 nearest_distance = Some(distance);
1421 nearest_functions.push(function_index);
1422 }
1423 Some(previous) if distance < previous => {
1424 nearest_distance = Some(distance);
1425 nearest_functions.clear();
1426 nearest_functions.push(function_index);
1427 }
1428 Some(previous) if distance == previous => {
1429 nearest_functions.push(function_index);
1430 }
1431 Some(_) => {}
1432 }
1433 }
1434 let established_match = match nearest_functions.as_slice() {
1435 [] => None,
1436 [function_index] => Some(self.functions[*function_index].coverage_pct),
1437 tied => self.innermost_anonymous_match(tied, target),
1438 };
1439 if established_match.is_some() {
1440 return established_match;
1441 }
1442
1443 self.unique_anonymous_header_match(&signature_owners)
1444 }
1445
1446 fn header_spans_containing(&self, target: IstanbulPosition) -> Vec<usize> {
1451 let low = target.line.saturating_sub(self.max_header_height);
1452 let first = self.header_starts.partition_point(|(line, _)| *line < low);
1453 let past = self
1454 .header_starts
1455 .partition_point(|(line, _)| *line <= target.line);
1456 self.header_starts[first..past]
1457 .iter()
1458 .filter(|(_, function_index)| {
1459 self.functions[*function_index]
1460 .header_span
1461 .is_some_and(|span| span.contains(target))
1462 })
1463 .map(|(_, function_index)| *function_index)
1464 .collect()
1465 }
1466
1467 fn foreign_signature_blocks(
1478 &self,
1479 owners: &[usize],
1480 candidate: usize,
1481 target: IstanbulPosition,
1482 ) -> bool {
1483 let function = &self.functions[candidate];
1484 if function
1485 .header_span
1486 .is_some_and(|span| span.contains(target))
1487 || function.body_span.is_some_and(|span| span.contains(target))
1488 {
1489 return false;
1490 }
1491 owners.iter().any(|&owner| {
1492 owner != candidate
1493 && self.functions[owner]
1494 .header_span
1495 .is_some_and(|span| span.contains(function.decl_start))
1496 })
1497 }
1498
1499 fn unique_anonymous_header_match(&self, signature_owners: &[usize]) -> Option<f64> {
1511 let [function_index] = signature_owners else {
1512 return None;
1513 };
1514 let function = &self.functions[*function_index];
1515 if !is_anonymous_istanbul_name(&function.name) || function.header_holds_other_fn {
1516 return None;
1517 }
1518 Some(function.coverage_pct)
1519 }
1520
1521 fn innermost_anonymous_match(&self, tied: &[usize], target: IstanbulPosition) -> Option<f64> {
1522 let containing: Option<Vec<_>> = tied
1523 .iter()
1524 .map(|&function_index| {
1525 self.functions[function_index]
1526 .body_span
1527 .filter(|span| span.contains(target))
1528 .map(|span| (function_index, span))
1529 })
1530 .collect();
1531 let containing = containing?;
1532
1533 let mut winner = None;
1534 for &(function_index, candidate_span) in &containing {
1535 let is_strictly_innermost = containing.iter().all(|&(other_index, other_span)| {
1536 other_index == function_index || other_span.strictly_contains(candidate_span)
1537 });
1538 if !is_strictly_innermost {
1539 continue;
1540 }
1541 if winner.replace(function_index).is_some() {
1542 return None;
1543 }
1544 }
1545 winner.map(|function_index| self.functions[function_index].coverage_pct)
1546 }
1547
1548 fn unambiguous_named_pct(&self, name: &str) -> Option<f64> {
1553 let mut found: Option<f64> = None;
1554 for function in &self.functions {
1555 if !function.answers_to(name) {
1556 continue;
1557 }
1558 match found {
1559 None => found = Some(function.coverage_pct),
1560 Some(previous) if previous.to_bits() == function.coverage_pct.to_bits() => {}
1561 Some(_) => return None,
1562 }
1563 }
1564 found
1565 }
1566}
1567
1568pub struct IstanbulCoverage {
1570 files: rustc_hash::FxHashMap<std::path::PathBuf, IstanbulFileCoverage>,
1571 format: fallow_output::CoverageInputFormat,
1572}
1573
1574impl IstanbulCoverage {
1575 pub fn get(&self, path: &std::path::Path) -> Option<&IstanbulFileCoverage> {
1577 self.files.get(path)
1578 }
1579
1580 pub fn file_count(&self) -> usize {
1582 self.files.len()
1583 }
1584
1585 pub const fn format(&self) -> fallow_output::CoverageInputFormat {
1587 self.format
1588 }
1589}
1590
1591enum CrapCoverageResolution<'a> {
1599 TemplateInherited(&'a TemplateInheritContext),
1600 Istanbul {
1601 file_coverage: Option<&'a IstanbulFileCoverage>,
1602 },
1603 StaticEstimated,
1604}
1605
1606fn resolve_crap_coverage<'a>(
1607 template_inherit: Option<&'a TemplateInheritContext>,
1608 istanbul_coverage: Option<&'a IstanbulCoverage>,
1609 path: &std::path::Path,
1610) -> CrapCoverageResolution<'a> {
1611 if let Some(inherit_ctx) = template_inherit {
1612 CrapCoverageResolution::TemplateInherited(inherit_ctx)
1613 } else if let Some(istanbul) = istanbul_coverage {
1614 let canonical = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
1615 CrapCoverageResolution::Istanbul {
1616 file_coverage: istanbul.get(&canonical),
1617 }
1618 } else {
1619 CrapCoverageResolution::StaticEstimated
1620 }
1621}
1622
1623pub fn auto_detect_coverage(root: &std::path::Path) -> Option<std::path::PathBuf> {
1631 let candidates = [
1632 root.join("coverage/coverage-final.json"),
1633 root.join(".nyc_output/coverage-final.json"),
1634 ];
1635 candidates.into_iter().find(|p| p.is_file())
1636}
1637
1638pub fn resolve_relative_to_root(
1644 path: &std::path::Path,
1645 project_root: Option<&std::path::Path>,
1646) -> std::path::PathBuf {
1647 if fallow_types::path_util::is_absolute_path_any_platform(path) {
1648 return path.to_path_buf();
1649 }
1650 match project_root {
1651 Some(root) => root.join(path),
1652 None => path.to_path_buf(),
1653 }
1654}
1655
1656#[cfg(test)]
1671fn load_istanbul_coverage(
1672 path: &std::path::Path,
1673 coverage_root: Option<&std::path::Path>,
1674 project_root: Option<&std::path::Path>,
1675 relocated: bool,
1676) -> Result<IstanbulCoverage, String> {
1677 load_istanbul_coverage_for_sources(path, coverage_root, project_root, None, relocated)
1678}
1679
1680pub(super) fn load_istanbul_coverage_for_sources(
1681 path: &std::path::Path,
1682 coverage_root: Option<&std::path::Path>,
1683 project_root: Option<&std::path::Path>,
1684 discovered_sources: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1685 relocated: bool,
1686) -> Result<IstanbulCoverage, String> {
1687 super::validate_coverage_root_absolute(coverage_root)?;
1688 let resolved = resolve_relative_to_root(path, project_root);
1689 match read_coverage_input(&resolved)? {
1690 CoverageInput::Istanbul { file_path, json } => {
1691 let raw = parse_coverage_map_tolerantly(&json).map_err(|e| {
1692 format!(
1693 "failed to parse coverage data from {}: {e}",
1694 file_path.display()
1695 )
1696 })?;
1697 let sources = CoverageMapSources {
1698 coverage_root,
1699 project_root,
1700 discovered_sources,
1701 relocated,
1702 };
1703 Ok(build_istanbul_coverage(
1704 &raw,
1705 &sources,
1706 fallow_output::CoverageInputFormat::Istanbul,
1707 ))
1708 }
1709 CoverageInput::V8 { dump_files } => {
1710 let scope = super::coverage_v8::V8ScriptScope {
1711 coverage_root,
1712 project_root,
1713 discovered_sources,
1714 };
1715 let raw = super::coverage_v8::load_v8_coverage_map(&dump_files, &scope)?;
1716 let sources = CoverageMapSources {
1718 coverage_root: None,
1719 project_root,
1720 discovered_sources,
1721 relocated,
1722 };
1723 Ok(build_istanbul_coverage(
1724 &raw,
1725 &sources,
1726 fallow_output::CoverageInputFormat::V8,
1727 ))
1728 }
1729 }
1730}
1731
1732enum CoverageInput {
1734 Istanbul {
1735 file_path: std::path::PathBuf,
1736 json: String,
1737 },
1738 V8 {
1739 dump_files: Vec<std::path::PathBuf>,
1740 },
1741}
1742
1743fn read_coverage_input(resolved: &std::path::Path) -> Result<CoverageInput, String> {
1747 if resolved.is_dir() {
1748 let candidate = resolved.join("coverage-final.json");
1749 if candidate.is_file() {
1750 return read_coverage_file(candidate);
1751 }
1752 let dump_files = super::coverage_v8::dump_files_in(resolved)?;
1753 if dump_files.is_empty() {
1754 return Err(format!(
1755 "no coverage-final.json or V8 coverage files found in {}",
1756 resolved.display()
1757 ));
1758 }
1759 return Ok(CoverageInput::V8 { dump_files });
1760 }
1761 read_coverage_file(resolved.to_path_buf())
1762}
1763
1764fn read_coverage_file(file_path: std::path::PathBuf) -> Result<CoverageInput, String> {
1765 let json = std::fs::read_to_string(&file_path)
1766 .map_err(|e| format!("failed to read coverage file {}: {e}", file_path.display()))?;
1767 if super::coverage_v8::is_v8_dump(&json) {
1768 return Ok(CoverageInput::V8 {
1769 dump_files: vec![file_path],
1770 });
1771 }
1772 Ok(CoverageInput::Istanbul { file_path, json })
1773}
1774
1775#[derive(Clone, Copy)]
1777struct CoverageMapSources<'a> {
1778 coverage_root: Option<&'a std::path::Path>,
1779 project_root: Option<&'a std::path::Path>,
1780 discovered_sources: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
1781 relocated: bool,
1782}
1783
1784fn build_istanbul_coverage(
1785 raw: &std::collections::BTreeMap<String, oxc_coverage_instrument::FileCoverage>,
1786 sources: &CoverageMapSources<'_>,
1787 format: fallow_output::CoverageInputFormat,
1788) -> IstanbulCoverage {
1789 let CoverageMapSources {
1790 coverage_root,
1791 project_root,
1792 discovered_sources,
1793 relocated,
1794 } = *sources;
1795 let mut files = rustc_hash::FxHashMap::default();
1796 for file_cov in raw.values() {
1797 let raw_path = resolve_relative_to_root(std::path::Path::new(&file_cov.path), project_root);
1802 let file_path = if let (Some(cov_root), Some(proj_root)) = (coverage_root, project_root) {
1803 rebase_coverage_path(raw_path, cov_root, proj_root)
1804 } else {
1805 raw_path
1806 };
1807 let canonical = dunce::canonicalize(&file_path).unwrap_or(file_path);
1808 let source = read_discovered_source(&canonical, discovered_sources, relocated);
1809 let source_index = source
1810 .as_deref()
1811 .map(|source| IstanbulSourceIndex::new(source, &canonical));
1812
1813 let statement_owners = tally_statements_by_owner(file_cov);
1814 let mut functions = Vec::with_capacity(file_cov.fn_map.len());
1815 for (fn_id, fn_entry) in &file_cov.fn_map {
1816 let coverage_pct = compute_function_statement_coverage(
1817 file_cov,
1818 fn_id,
1819 statement_owners.get(fn_id.as_str()),
1820 );
1821 if let Some(function) =
1822 istanbul_function_coverage(fn_entry, coverage_pct, source_index.as_ref())
1823 {
1824 functions.push(function);
1825 }
1826 }
1827
1828 files.insert(canonical, IstanbulFileCoverage::new(functions, relocated));
1829 }
1830
1831 IstanbulCoverage { files, format }
1832}
1833
1834#[expect(
1835 clippy::filetype_is_file,
1836 reason = "coverage provenance must admit regular files and reject every special file type"
1837)]
1838fn read_discovered_source(
1839 path: &std::path::Path,
1840 discovered_sources: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1841 relocated: bool,
1842) -> Option<String> {
1843 if relocated || !discovered_sources.is_some_and(|sources| sources.contains(path)) {
1844 return None;
1845 }
1846 if std::fs::symlink_metadata(path).ok()?.file_type().is_file() {
1847 std::fs::read_to_string(path).ok()
1848 } else {
1849 None
1850 }
1851}
1852
1853fn parse_coverage_map_tolerantly(
1863 json: &str,
1864) -> Result<std::collections::BTreeMap<String, oxc_coverage_instrument::FileCoverage>, String> {
1865 match oxc_coverage_instrument::parse_coverage_map(json) {
1866 Ok(raw) => Ok(raw),
1867 Err(strict_error) => {
1868 let mut value: serde_json::Value =
1869 serde_json::from_str(json).map_err(|_| strict_error.to_string())?;
1870 let positions = clamp_negative_positions(&mut value);
1871 let counts = clamp_negative_counts(&mut value);
1872 if !positions && !counts {
1873 return Err(strict_error.to_string());
1874 }
1875 serde_json::from_value(value).map_err(|_| strict_error.to_string())
1876 }
1877 }
1878}
1879
1880fn clamp_negative_positions(value: &mut serde_json::Value) -> bool {
1884 match value {
1885 serde_json::Value::Object(entries) => {
1886 let mut clamped = false;
1887 for (key, child) in entries.iter_mut() {
1888 if matches!(key.as_str(), "line" | "column")
1889 && child.as_i64().is_some_and(|number| number < 0)
1890 {
1891 *child = serde_json::Value::from(0);
1892 clamped = true;
1893 continue;
1894 }
1895 clamped |= clamp_negative_positions(child);
1896 }
1897 clamped
1898 }
1899 serde_json::Value::Array(items) => items.iter_mut().fold(false, |clamped, item| {
1900 clamped | clamp_negative_positions(item)
1901 }),
1902 _ => false,
1903 }
1904}
1905
1906const COVERAGE_COUNT_KEYS: [&str; 4] = ["s", "f", "b", "b_T"];
1908
1909fn clamp_negative_counts(value: &mut serde_json::Value) -> bool {
1913 let serde_json::Value::Object(files) = value else {
1914 return false;
1915 };
1916 let mut clamped = false;
1917 for file in files.values_mut() {
1918 let serde_json::Value::Object(sections) = file else {
1919 continue;
1920 };
1921 for key in COVERAGE_COUNT_KEYS {
1922 if let Some(counts) = sections.get_mut(key) {
1923 clamped |= clamp_negative_numbers(counts);
1924 }
1925 }
1926 }
1927 clamped
1928}
1929
1930fn clamp_negative_numbers(value: &mut serde_json::Value) -> bool {
1933 match value {
1934 serde_json::Value::Number(number) if number.as_f64().is_some_and(|n| n < 0.0) => {
1935 *value = serde_json::Value::from(0);
1936 true
1937 }
1938 serde_json::Value::Object(entries) => entries.values_mut().fold(false, |clamped, child| {
1939 clamped | clamp_negative_numbers(child)
1940 }),
1941 serde_json::Value::Array(items) => items.iter_mut().fold(false, |clamped, item| {
1942 clamped | clamp_negative_numbers(item)
1943 }),
1944 _ => false,
1945 }
1946}
1947
1948fn accessor_property_name(name: &str) -> Option<&str> {
1956 let property = name
1957 .strip_prefix("get ")
1958 .or_else(|| name.strip_prefix("set "))?;
1959 (!property.is_empty() && !property.contains(' ')).then_some(property)
1960}
1961
1962fn rebase_coverage_path(
1970 raw_path: std::path::PathBuf,
1971 coverage_root: &std::path::Path,
1972 project_root: &std::path::Path,
1973) -> std::path::PathBuf {
1974 if let Ok(rel) = raw_path.strip_prefix(coverage_root) {
1975 return project_root.join(rel);
1976 }
1977 if let Ok(canonical) = dunce::canonicalize(&raw_path)
1978 && let Ok(rel) = canonical.strip_prefix(coverage_root)
1979 {
1980 return project_root.join(rel);
1981 }
1982 raw_path
1983}
1984
1985fn istanbul_function_coverage(
1986 fn_entry: &oxc_coverage_instrument::FnEntry,
1987 coverage_pct: f64,
1988 source_index: Option<&IstanbulSourceIndex<'_>>,
1989) -> Option<IstanbulFunctionCoverage> {
1990 let body_span = IstanbulSpan::from_entry(fn_entry, source_index);
1991 let header_span = IstanbulSpan::header_from_entry(fn_entry, source_index);
1992 let decl_start = normalized_istanbul_position(
1993 fn_entry.decl.start.line,
1994 fn_entry.decl.start.column,
1995 source_index,
1996 )?;
1997 let effective_position = normalized_istanbul_position(
1998 effective_istanbul_fn_line(fn_entry),
1999 fn_entry.decl.start.column,
2000 source_index,
2001 );
2002 let candidates = [
2003 effective_position.map(|position| IstanbulAlias {
2004 position,
2005 primary: true,
2006 }),
2007 Some(IstanbulAlias {
2008 position: decl_start,
2009 primary: true,
2010 }),
2011 body_span.map(|span| IstanbulAlias {
2012 position: span.start,
2013 primary: false,
2014 }),
2015 named_function_syntax_alias(fn_entry, source_index),
2016 ];
2017 let mut aliases: Vec<IstanbulAlias> = Vec::with_capacity(candidates.len());
2018 for candidate in candidates.into_iter().flatten() {
2019 if !aliases
2020 .iter()
2021 .any(|alias| alias.position == candidate.position)
2022 {
2023 aliases.push(candidate);
2024 }
2025 }
2026
2027 Some(IstanbulFunctionCoverage {
2028 name: fn_entry.name.clone(),
2029 coverage_pct,
2030 aliases,
2031 decl_start,
2032 header_holds_other_fn: false,
2033 header_span,
2034 body_span,
2035 })
2036}
2037
2038struct IstanbulSourceIndex<'a> {
2041 source: &'a str,
2042 line_starts: Vec<usize>,
2043 non_ascii_lines: rustc_hash::FxHashMap<usize, Utf16LineIndex>,
2044 named_function_starts: rustc_hash::FxHashMap<usize, usize>,
2045}
2046
2047struct Utf16LineIndex {
2048 utf16_len: u32,
2049 byte_len: usize,
2050 checkpoints: Vec<Utf16Checkpoint>,
2051}
2052
2053struct Utf16Checkpoint {
2054 utf16_start: u32,
2055 utf16_end: u32,
2056 byte_end: usize,
2057}
2058
2059impl<'a> IstanbulSourceIndex<'a> {
2060 fn new(source: &'a str, path: &std::path::Path) -> Self {
2061 let mut line_starts = vec![0];
2062 line_starts.extend(
2063 source
2064 .bytes()
2065 .enumerate()
2066 .filter_map(|(index, byte)| (byte == b'\n').then_some(index + 1)),
2067 );
2068 let non_ascii_lines = utf16_line_indexes(source, &line_starts);
2069
2070 let named_function_starts = named_function_starts_from_clean_parse(source, path);
2071
2072 Self {
2073 source,
2074 line_starts,
2075 non_ascii_lines,
2076 named_function_starts,
2077 }
2078 }
2079
2080 fn byte_position(&self, line: u32, utf16_column: u32) -> Option<IstanbulPosition> {
2081 let line_index = usize::try_from(line.checked_sub(1)?).ok()?;
2082 let line_start = *self.line_starts.get(line_index)?;
2083 let line_end = self
2084 .line_starts
2085 .get(line_index + 1)
2086 .copied()
2087 .map_or(self.source.len(), |next_start| next_start - 1);
2088 let line_source = self.source.get(line_start..line_end)?;
2089 let byte_column = if let Some(index) = self.non_ascii_lines.get(&line_index) {
2090 index.byte_column(utf16_column)?
2091 } else {
2092 let byte_column = usize::try_from(utf16_column).ok()?;
2093 (byte_column <= line_source.len()).then_some(byte_column)?
2094 };
2095 Some(IstanbulPosition::new(
2096 line,
2097 u32::try_from(byte_column).ok()?,
2098 ))
2099 }
2100
2101 fn absolute_offset(&self, line: u32, utf16_column: u32) -> Option<usize> {
2102 let position = self.byte_position(line, utf16_column)?;
2103 let line_index = usize::try_from(position.line.checked_sub(1)?).ok()?;
2104 self.line_starts
2105 .get(line_index)?
2106 .checked_add(position.col as usize)
2107 }
2108
2109 fn position_at_offset(&self, offset: usize) -> Option<IstanbulPosition> {
2110 if offset > self.source.len() {
2111 return None;
2112 }
2113 let line_index = self.line_starts.partition_point(|start| *start <= offset) - 1;
2114 Some(IstanbulPosition::new(
2115 u32::try_from(line_index + 1).ok()?,
2116 u32::try_from(offset.checked_sub(self.line_starts[line_index])?).ok()?,
2117 ))
2118 }
2119
2120 fn named_function_start(
2121 &self,
2122 fn_entry: &oxc_coverage_instrument::FnEntry,
2123 ) -> Option<IstanbulPosition> {
2124 let declaration_offset =
2125 self.absolute_offset(fn_entry.decl.start.line, fn_entry.decl.start.column)?;
2126 let syntax_offset = *self.named_function_starts.get(&declaration_offset)?;
2127 self.position_at_offset(syntax_offset)
2128 }
2129}
2130
2131impl Utf16LineIndex {
2132 fn byte_column(&self, utf16_column: u32) -> Option<usize> {
2133 if utf16_column > self.utf16_len {
2134 return None;
2135 }
2136 let completed = self
2137 .checkpoints
2138 .partition_point(|checkpoint| checkpoint.utf16_end <= utf16_column);
2139 if let Some(next) = self.checkpoints.get(completed)
2140 && utf16_column > next.utf16_start
2141 {
2142 return None;
2143 }
2144 let (utf16_base, byte_base) = completed
2145 .checked_sub(1)
2146 .and_then(|index| self.checkpoints.get(index))
2147 .map_or((0, 0), |checkpoint| {
2148 (checkpoint.utf16_end, checkpoint.byte_end)
2149 });
2150 let ascii_width = usize::try_from(utf16_column.checked_sub(utf16_base)?).ok()?;
2151 let byte_column = byte_base.checked_add(ascii_width)?;
2152 (byte_column <= self.byte_len).then_some(byte_column)
2153 }
2154}
2155
2156fn utf16_line_indexes(
2157 source: &str,
2158 line_starts: &[usize],
2159) -> rustc_hash::FxHashMap<usize, Utf16LineIndex> {
2160 let mut indexes = rustc_hash::FxHashMap::default();
2161 for (line_index, &line_start) in line_starts.iter().enumerate() {
2162 let line_end = line_starts
2163 .get(line_index + 1)
2164 .copied()
2165 .map_or(source.len(), |next_start| next_start - 1);
2166 let Some(line) = source.get(line_start..line_end) else {
2167 continue;
2168 };
2169 if line.is_ascii() {
2170 continue;
2171 }
2172 let mut utf16_column = 0_u32;
2173 let mut checkpoints = Vec::new();
2174 for (byte_column, character) in line.char_indices() {
2175 let utf16_width = character.len_utf16() as u32;
2176 if !character.is_ascii() {
2177 checkpoints.push(Utf16Checkpoint {
2178 utf16_start: utf16_column,
2179 utf16_end: utf16_column.saturating_add(utf16_width),
2180 byte_end: byte_column.saturating_add(character.len_utf8()),
2181 });
2182 }
2183 utf16_column = utf16_column.saturating_add(utf16_width);
2184 }
2185 indexes.insert(
2186 line_index,
2187 Utf16LineIndex {
2188 utf16_len: utf16_column,
2189 byte_len: line.len(),
2190 checkpoints,
2191 },
2192 );
2193 }
2194 indexes
2195}
2196
2197fn named_function_starts_from_clean_parse(
2198 source: &str,
2199 path: &std::path::Path,
2200) -> rustc_hash::FxHashMap<usize, usize> {
2201 let source_type = match path.extension().and_then(|extension| extension.to_str()) {
2202 Some("gts") => oxc_span::SourceType::ts(),
2203 Some("gjs") => oxc_span::SourceType::mjs(),
2204 _ => oxc_span::SourceType::from_path(path).unwrap_or_default(),
2205 };
2206 if let Some(starts) = collect_named_function_starts(source, source_type) {
2207 return starts;
2208 }
2209 if source_type.is_jsx() {
2210 return rustc_hash::FxHashMap::default();
2211 }
2212 let jsx_source_type = if source_type.is_typescript() {
2213 oxc_span::SourceType::tsx()
2214 } else {
2215 oxc_span::SourceType::jsx()
2216 };
2217 collect_named_function_starts(source, jsx_source_type).unwrap_or_default()
2218}
2219
2220fn collect_named_function_starts(
2221 source: &str,
2222 source_type: oxc_span::SourceType,
2223) -> Option<rustc_hash::FxHashMap<usize, usize>> {
2224 fallow_extract::parse_bounded_or_default(source, source_type, |parsed| {
2225 if parsed.fatal_error || !parsed.diagnostics.is_empty() {
2226 return None;
2227 }
2228 let mut starts = rustc_hash::FxHashMap::default();
2229 let mut collector = NamedFunctionSyntaxCollector {
2230 starts: &mut starts,
2231 };
2232 oxc_ast_visit::Visit::visit_program(&mut collector, &parsed.program);
2233 Some(starts)
2234 })
2235}
2236
2237struct NamedFunctionSyntaxCollector<'a> {
2238 starts: &'a mut rustc_hash::FxHashMap<usize, usize>,
2239}
2240
2241impl<'ast> oxc_ast_visit::Visit<'ast> for NamedFunctionSyntaxCollector<'_> {
2242 fn visit_function(
2243 &mut self,
2244 function: &oxc_ast::ast::Function<'ast>,
2245 flags: oxc_syntax::scope::ScopeFlags,
2246 ) {
2247 if let Some(identifier) = &function.id
2248 && let (Ok(identifier_start), Ok(syntax_start)) = (
2249 usize::try_from(identifier.span.start),
2250 usize::try_from(function.span.start),
2251 )
2252 {
2253 self.starts.insert(identifier_start, syntax_start);
2254 }
2255 oxc_ast_visit::walk::walk_function(self, function, flags);
2256 }
2257}
2258
2259fn normalized_istanbul_position(
2260 line: u32,
2261 column: u32,
2262 source_index: Option<&IstanbulSourceIndex<'_>>,
2263) -> Option<IstanbulPosition> {
2264 match source_index {
2265 Some(index) => index.byte_position(line, column),
2266 None => Some(IstanbulPosition::new(line, column)),
2267 }
2268}
2269
2270fn named_function_syntax_alias(
2276 fn_entry: &oxc_coverage_instrument::FnEntry,
2277 source_index: Option<&IstanbulSourceIndex<'_>>,
2278) -> Option<IstanbulAlias> {
2279 if is_anonymous_istanbul_name(&fn_entry.name) {
2280 return None;
2281 }
2282 Some(IstanbulAlias {
2283 position: source_index?.named_function_start(fn_entry)?,
2284 primary: true,
2285 })
2286}
2287
2288fn effective_istanbul_fn_line(fn_entry: &oxc_coverage_instrument::FnEntry) -> u32 {
2289 if fn_entry.line > 0 {
2290 fn_entry.line
2291 } else {
2292 fn_entry.decl.start.line
2293 }
2294}
2295
2296#[derive(Default)]
2298struct StatementTally {
2299 covered: u32,
2300 total: u32,
2301}
2302
2303fn istanbul_range_contains(
2309 outer: &oxc_coverage_instrument::Location,
2310 inner: &oxc_coverage_instrument::Location,
2311) -> bool {
2312 let after_start = inner.start.line > outer.start.line
2313 || (inner.start.line == outer.start.line && inner.start.column >= outer.start.column);
2314 let before_end = inner.end.line < outer.end.line
2315 || (inner.end.line == outer.end.line && inner.end.column <= outer.end.column);
2316 after_start && before_end
2317}
2318
2319fn tally_statements_by_owner(
2339 file_cov: &oxc_coverage_instrument::FileCoverage,
2340) -> rustc_hash::FxHashMap<&str, StatementTally> {
2341 let mut owners: rustc_hash::FxHashMap<&str, StatementTally> = rustc_hash::FxHashMap::default();
2342
2343 for (stmt_id, stmt_loc) in &file_cov.statement_map {
2344 let mut owner: Option<(&str, &oxc_coverage_instrument::Location)> = None;
2345
2346 for (fn_id, fn_entry) in &file_cov.fn_map {
2347 if !istanbul_range_contains(&fn_entry.loc, stmt_loc) {
2348 continue;
2349 }
2350 let inner_than_current = owner.is_none_or(|(_, best)| {
2351 let candidate = (
2352 (fn_entry.loc.start.line, fn_entry.loc.start.column),
2353 std::cmp::Reverse((fn_entry.loc.end.line, fn_entry.loc.end.column)),
2354 );
2355 let incumbent = (
2356 (best.start.line, best.start.column),
2357 std::cmp::Reverse((best.end.line, best.end.column)),
2358 );
2359 candidate > incumbent
2360 });
2361 if inner_than_current {
2362 owner = Some((fn_id.as_str(), &fn_entry.loc));
2363 }
2364 }
2365
2366 let Some((fn_id, _)) = owner else {
2367 continue;
2368 };
2369 let tally = owners.entry(fn_id).or_default();
2370 tally.total += 1;
2371 if file_cov.s.get(stmt_id).copied().unwrap_or(0) > 0 {
2372 tally.covered += 1;
2373 }
2374 }
2375
2376 owners
2377}
2378
2379fn compute_function_statement_coverage(
2388 file_cov: &oxc_coverage_instrument::FileCoverage,
2389 fn_id: &str,
2390 owned: Option<&StatementTally>,
2391) -> f64 {
2392 match owned {
2393 Some(tally) if tally.total > 0 => f64::from(tally.covered) / f64::from(tally.total) * 100.0,
2394 _ => {
2395 let hit = file_cov.f.get(fn_id).copied().unwrap_or(0);
2396 if hit > 0 { 100.0 } else { 0.0 }
2397 }
2398 }
2399}
2400
2401fn count_unused_exports_by_path(
2406 unused_exports: &[crate::results::UnusedExportFinding],
2407) -> rustc_hash::FxHashMap<&std::path::Path, usize> {
2408 let mut map: rustc_hash::FxHashMap<&std::path::Path, usize> = rustc_hash::FxHashMap::default();
2409 for exp in unused_exports {
2410 *map.entry(exp.export.path.as_path()).or_default() += 1;
2411 }
2412 map
2413}
2414
2415fn compute_maintainability_index(
2435 complexity_density: f64,
2436 dead_code_ratio: f64,
2437 fan_out: usize,
2438 lines: u32,
2439) -> f64 {
2440 let dampening = (f64::from(lines) / fallow_output::MI_DENSITY_MIN_LINES).min(1.0);
2441 let fan_out_penalty = ((fan_out as f64).ln_1p() * 4.0).min(15.0);
2442 #[expect(
2443 clippy::suboptimal_flops,
2444 reason = "formula matches documented specification"
2445 )]
2446 let score = 100.0
2447 - (complexity_density * 30.0 * dampening)
2448 - (dead_code_ratio * 20.0)
2449 - fan_out_penalty;
2450 score.clamp(0.0, 100.0)
2451}
2452
2453fn file_score_structural_concern(score: &FileHealthScore) -> f64 {
2454 (100.0 - score.maintainability_index).clamp(0.0, 100.0)
2455}
2456
2457#[must_use]
2463pub fn file_score_fully_crap_exempt(score: &FileHealthScore, max_crap_threshold: f64) -> bool {
2464 let signal = file_score_crap_signal(score, max_crap_threshold);
2465 max_crap_threshold <= 0.0
2466 || (score.crap_above_threshold == 0
2467 && if signal.suppression_aware {
2468 signal.maximum >= CRAP_THRESHOLD
2469 } else {
2470 score.crap_exempted > 0
2471 })
2472}
2473
2474pub struct FileScoreCrapSignal {
2476 pub maximum: f64,
2478 pub threshold: f64,
2480 suppression_aware: bool,
2481}
2482
2483impl FileScoreCrapSignal {
2484 pub const fn metric(&self) -> &'static str {
2486 if self.suppression_aware {
2487 "crap_unsuppressed_max"
2488 } else {
2489 "crap_max"
2490 }
2491 }
2492}
2493
2494pub fn file_score_crap_signal(score: &FileHealthScore, global: f64) -> FileScoreCrapSignal {
2497 match (
2498 score.crap_unsuppressed_max,
2499 score.crap_unsuppressed_effective_threshold,
2500 ) {
2501 (Some(maximum), Some(threshold)) => FileScoreCrapSignal {
2502 maximum,
2503 threshold,
2504 suppression_aware: true,
2505 },
2506 _ => FileScoreCrapSignal {
2507 maximum: score.crap_max,
2508 threshold: score.crap_effective_threshold.unwrap_or(global),
2509 suppression_aware: false,
2510 },
2511 }
2512}
2513
2514fn file_score_crap_concern(score: &FileHealthScore, max_crap_threshold: f64) -> f64 {
2521 if file_score_fully_crap_exempt(score, max_crap_threshold) {
2522 return 0.0;
2523 }
2524 let signal = file_score_crap_signal(score, max_crap_threshold);
2525 let crap_max = signal.maximum;
2526 let t = signal.threshold;
2527 let half = t / 2.0;
2528 let saturation = t * 10.0 / 3.0;
2529 if crap_max <= 0.0 {
2530 0.0
2531 } else if crap_max < half {
2532 (crap_max / half) * 45.0
2533 } else if crap_max < t {
2534 ((crap_max - half) / half).mul_add(30.0, 45.0)
2535 } else if crap_max < saturation {
2536 ((crap_max - t) / (saturation - t)).mul_add(25.0, 75.0)
2537 } else {
2538 100.0
2539 }
2540}
2541
2542fn file_score_triage_concern(score: &FileHealthScore, max_crap_threshold: f64) -> f64 {
2543 file_score_structural_concern(score).max(file_score_crap_concern(score, max_crap_threshold))
2544}
2545
2546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2552pub enum FileScoreConcern {
2553 Structural,
2555 Risk,
2557}
2558
2559impl FileScoreConcern {
2560 pub const fn label(self) -> &'static str {
2562 match self {
2563 Self::Structural => "structure",
2564 Self::Risk => "risk",
2565 }
2566 }
2567}
2568
2569pub fn file_score_concern_axis(
2578 score: &FileHealthScore,
2579 max_crap_threshold: f64,
2580) -> FileScoreConcern {
2581 let crap_concern = file_score_crap_concern(score, max_crap_threshold);
2582 if crap_concern <= 0.0 {
2583 FileScoreConcern::Structural
2584 } else if crap_concern >= file_score_structural_concern(score) {
2585 FileScoreConcern::Risk
2586 } else {
2587 FileScoreConcern::Structural
2588 }
2589}
2590
2591fn compare_file_score_triage(
2592 a: &FileHealthScore,
2593 b: &FileHealthScore,
2594 max_crap_threshold: f64,
2595) -> std::cmp::Ordering {
2596 file_score_triage_concern(b, max_crap_threshold)
2597 .total_cmp(&file_score_triage_concern(a, max_crap_threshold))
2598 .then_with(|| {
2599 file_score_crap_signal(b, max_crap_threshold)
2600 .maximum
2601 .total_cmp(&file_score_crap_signal(a, max_crap_threshold).maximum)
2602 })
2603 .then_with(|| a.maintainability_index.total_cmp(&b.maintainability_index))
2604 .then_with(|| a.path.cmp(&b.path))
2605}
2606
2607#[derive(Clone, Copy)]
2610pub(super) struct FileScoreComputeInput<'a> {
2611 pub(super) modules: &'a [crate::source::ModuleInfo],
2612 pub(super) file_paths:
2613 &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
2614 pub(super) changed_files: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
2615 pub(super) istanbul_coverage: Option<&'a IstanbulCoverage>,
2616 pub(super) root: &'a std::path::Path,
2617 pub(super) crap_thresholds: CrapScoreThresholds<'a>,
2618 pub(super) with_static_links: bool,
2621 pub(super) test_reach: Option<&'a super::test_reach::TestReachGraph>,
2624}
2625
2626pub(super) fn compute_file_scores(
2632 input: FileScoreComputeInput<'_>,
2633 analysis_output: crate::results::DeadCodeAnalysisArtifacts,
2634) -> Result<FileScoreOutput, String> {
2635 let FileScoreComputeInput {
2636 modules,
2637 file_paths,
2638 changed_files,
2639 istanbul_coverage,
2640 root,
2641 crap_thresholds,
2642 with_static_links,
2643 test_reach,
2644 } = input;
2645 let retained_graph = analysis_output.graph.ok_or("graph not available")?;
2646 let test_coverage = test_reach.map_or_else(
2647 || retained_graph.static_test_coverage(),
2648 super::test_reach::TestReachGraph::static_test_coverage,
2649 );
2650 let graph = retained_graph.as_graph();
2651 let results = &analysis_output.results;
2652
2653 let circular_files = collect_circular_files(results);
2654 let top_complex_fns = collect_top_complex_fns(modules, file_paths);
2655 let cycle_members = collect_cycle_members(results);
2656 let direct_callers = collect_direct_callers(graph, file_paths);
2657 let unused_export_names = collect_unused_export_names(results);
2658
2659 let unused_files: rustc_hash::FxHashSet<&std::path::Path> = results
2660 .unused_files
2661 .iter()
2662 .map(|f| f.file.path.as_path())
2663 .collect();
2664
2665 let unused_exports_by_path = count_unused_exports_by_path(&results.unused_exports);
2666
2667 let FileScoreCoverageSetup {
2668 module_by_id,
2669 coverage,
2670 } = prepare_file_score_coverage_setup(modules, file_paths, results, graph, test_coverage, root);
2671
2672 let template_inherit =
2673 build_template_inherit_contexts(graph, test_coverage, &module_by_id, file_paths);
2674
2675 let mut acc = accumulate_file_scores(
2676 unused_export_names,
2677 &FileScoreLoopCtx {
2678 graph,
2679 test_coverage,
2680 file_paths,
2681 module_by_id: &module_by_id,
2682 unused_files: &unused_files,
2683 unused_exports_by_path: &unused_exports_by_path,
2684 template_inherit: &template_inherit,
2685 istanbul_coverage,
2686 root,
2687 crap_thresholds,
2688 },
2689 );
2690 acc.scores = finalize_file_score_list(
2691 acc.scores,
2692 changed_files,
2693 crap_thresholds.resolver.global.crap,
2694 );
2695
2696 Ok(build_file_score_output(FileScoreOutputParts {
2697 graph,
2698 with_static_links,
2699 file_paths,
2700 results,
2701 scores: acc.scores,
2702 coverage,
2703 circular_files,
2704 top_complex_fns,
2705 crap_target_fns: acc.crap_target_fns,
2706 entry_points: acc.entry_points,
2707 value_export_counts: acc.value_export_counts,
2708 unused_export_names: acc.unused_export_names,
2709 cycle_members,
2710 direct_callers,
2711 istanbul_matched: acc.istanbul_matched,
2712 istanbul_total: acc.istanbul_total,
2713 istanbul_files_joined: acc.istanbul_files_joined,
2714 istanbul_files_total: acc.istanbul_files_total,
2715 coverage_input_format: istanbul_coverage.map(IstanbulCoverage::format),
2716 per_function_crap: acc.per_function_crap,
2717 template_inherit,
2718 }))
2719}
2720
2721struct FileScoreLoopCtx<'a> {
2723 graph: &'a fallow_graph::graph::ModuleGraph,
2724 test_coverage: StaticTestCoverage<'a>,
2725 file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
2726 module_by_id: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
2727 unused_files: &'a rustc_hash::FxHashSet<&'a std::path::Path>,
2728 unused_exports_by_path: &'a rustc_hash::FxHashMap<&'a std::path::Path, usize>,
2729 template_inherit: &'a rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
2730 istanbul_coverage: Option<&'a IstanbulCoverage>,
2731 root: &'a std::path::Path,
2734 crap_thresholds: CrapScoreThresholds<'a>,
2735}
2736
2737struct FileScoreAccumulator {
2739 scores: Vec<FileHealthScore>,
2740 entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
2741 value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
2742 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2743 crap_target_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
2744 per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
2745 istanbul_matched: usize,
2746 istanbul_files_joined: usize,
2747 istanbul_files_total: usize,
2748 istanbul_total: usize,
2749}
2750
2751impl FileScoreAccumulator {
2752 fn with_capacity(modules: usize) -> Self {
2754 FileScoreAccumulator {
2755 scores: Vec::with_capacity(modules),
2756 entry_points: rustc_hash::FxHashSet::default(),
2757 value_export_counts: rustc_hash::FxHashMap::default(),
2758 unused_export_names: rustc_hash::FxHashMap::default(),
2759 crap_target_fns: rustc_hash::FxHashMap::default(),
2760 per_function_crap: rustc_hash::FxHashMap::default(),
2761 istanbul_matched: 0,
2762 istanbul_total: 0,
2763 istanbul_files_joined: 0,
2764 istanbul_files_total: 0,
2765 }
2766 }
2767}
2768
2769fn accumulate_file_scores(
2772 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2773 ctx: &FileScoreLoopCtx<'_>,
2774) -> FileScoreAccumulator {
2775 let mut acc = FileScoreAccumulator {
2776 unused_export_names,
2777 istanbul_files_total: ctx
2778 .istanbul_coverage
2779 .map_or(0, IstanbulCoverage::file_count),
2780 ..FileScoreAccumulator::with_capacity(ctx.graph.modules.len())
2781 };
2782 for node in &ctx.graph.modules {
2783 let Some(path) = ctx.file_paths.get(&node.file_id) else {
2784 continue;
2785 };
2786 record_entry_point(&mut acc.entry_points, node, path);
2787 let score = compute_one_file_score(&mut acc, ctx, node, path);
2788 acc.scores.push(score);
2789 }
2790 acc
2791}
2792
2793fn finalize_file_score_list(
2796 mut scores: Vec<FileHealthScore>,
2797 changed_files: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
2798 max_crap_threshold: f64,
2799) -> Vec<FileHealthScore> {
2800 if let Some(changed) = changed_files {
2801 scores.retain(|s| changed.contains(&s.path));
2802 }
2803 scores.retain(|s| s.function_count > 0);
2804 scores.sort_by(|a, b| compare_file_score_triage(a, b, max_crap_threshold));
2805 scores
2806}
2807
2808fn compute_one_file_score(
2810 acc: &mut FileScoreAccumulator,
2811 ctx: &FileScoreLoopCtx<'_>,
2812 node: &fallow_graph::graph::ModuleNode,
2813 path: &std::path::Path,
2814) -> FileHealthScore {
2815 let fan_in = ctx
2816 .graph
2817 .reverse_deps
2818 .get(node.file_id.0 as usize)
2819 .map_or(0, Vec::len);
2820 let fan_out = node.edge_range.len();
2821
2822 let (total_cyclomatic, total_cognitive, function_count, lines) = ctx
2823 .module_by_id
2824 .get(&node.file_id)
2825 .map_or((0, 0, 0, 0), |module| aggregate_complexity(module));
2826
2827 let value_exports = node.exports.iter().filter(|e| !e.is_type_only).count();
2828 let path_owned = path.to_path_buf();
2829 acc.value_export_counts
2830 .insert(path_owned.clone(), value_exports);
2831 record_unused_file_export_names(
2832 path_owned.as_path(),
2833 &node.exports,
2834 ctx.unused_files,
2835 &mut acc.unused_export_names,
2836 );
2837
2838 let (dead_code_ratio_rounded, complexity_density_rounded, maintainability_index_rounded) =
2839 compute_file_score_metrics(node, &path_owned, ctx, total_cyclomatic, lines, fan_out);
2840
2841 let relative = path_owned.strip_prefix(ctx.root).unwrap_or(&path_owned);
2842 let suppressions = ctx
2843 .module_by_id
2844 .get(&node.file_id)
2845 .map_or(&[][..], |module| module.suppressions.as_slice());
2846 let ceilings = CrapCeilingLookup::new(ctx.crap_thresholds, relative, suppressions);
2847 let crap = compute_file_score_crap(node, ctx, &path_owned, &ceilings);
2848 acc.istanbul_matched += crap.istanbul_matched;
2849 acc.istanbul_total += crap.istanbul_total;
2850 acc.istanbul_files_joined += usize::from(crap.coverage_file_joined);
2851 record_per_function_crap(&mut acc.per_function_crap, &path_owned, crap.per_function);
2852 let mut eligible_functions = crap.signals.eligible_functions;
2853 if !eligible_functions.is_empty() {
2854 eligible_functions.sort_by_key(|function| std::cmp::Reverse(function.2));
2855 eligible_functions.truncate(MAX_FUNCTION_EVIDENCE);
2856 acc.crap_target_fns
2857 .insert(path_owned.clone(), eligible_functions);
2858 }
2859
2860 let global_crap = ctx.crap_thresholds.resolver.global.crap;
2865 let crap_effective_threshold = crap
2866 .signals
2867 .min_ceiling
2868 .filter(|ceiling| (*ceiling - global_crap).abs() > f64::EPSILON);
2869
2870 FileHealthScore {
2871 path: path_owned,
2872 fan_in,
2873 fan_out,
2874 dead_code_ratio: dead_code_ratio_rounded,
2875 complexity_density: complexity_density_rounded,
2876 maintainability_index: maintainability_index_rounded,
2877 total_cyclomatic,
2878 total_cognitive,
2879 function_count,
2880 lines,
2881 crap_max: crap.max,
2882 crap_above_threshold: crap.signals.above,
2883 crap_exempted: crap.signals.exempted,
2884 crap_suppressed: crap.signals.suppressed,
2885 crap_unsuppressed_max: (crap.signals.suppressed > 0)
2886 .then_some(crap.signals.unsuppressed_max),
2887 crap_unsuppressed_effective_threshold: (crap.signals.suppressed > 0)
2888 .then_some(crap.signals.unsuppressed_min_ceiling.unwrap_or(global_crap)),
2889 crap_effective_threshold,
2890 }
2891}
2892
2893fn compute_file_score_metrics(
2896 node: &fallow_graph::graph::ModuleNode,
2897 path: &std::path::Path,
2898 ctx: &FileScoreLoopCtx<'_>,
2899 total_cyclomatic: u32,
2900 lines: u32,
2901 fan_out: usize,
2902) -> (f64, f64, f64) {
2903 let dead_code_ratio = compute_dead_code_ratio(
2904 path,
2905 &node.exports,
2906 ctx.unused_files,
2907 ctx.unused_exports_by_path,
2908 );
2909 let complexity_density = compute_complexity_density(total_cyclomatic, lines);
2910
2911 let dead_code_ratio_rounded = (dead_code_ratio * 100.0).round() / 100.0;
2912 let complexity_density_rounded = (complexity_density * 100.0).round() / 100.0;
2913
2914 let maintainability_index = compute_maintainability_index(
2915 complexity_density_rounded,
2916 dead_code_ratio_rounded,
2917 fan_out,
2918 lines,
2919 );
2920 (
2921 dead_code_ratio_rounded,
2922 complexity_density_rounded,
2923 (maintainability_index * 10.0).round() / 10.0,
2924 )
2925}
2926
2927fn build_file_score_output(parts: FileScoreOutputParts<'_>) -> FileScoreOutput {
2928 let total_exports: usize = parts.graph.modules.iter().map(|m| m.exports.len()).sum();
2929 let unused_deps = parts.results.unused_dependencies.len()
2930 + parts.results.unused_dev_dependencies.len()
2931 + parts.results.unused_optional_dependencies.len();
2932 let analysis_snapshot =
2933 build_analysis_counts_snapshot(parts.graph, parts.file_paths, parts.results, unused_deps);
2934 let analysis_counts =
2935 build_file_score_analysis_counts(parts.results, total_exports, unused_deps);
2936 let template_inherit_provenance =
2937 build_template_inherit_provenance(parts.template_inherit, parts.file_paths);
2938
2939 FileScoreOutput {
2940 scores: parts.scores,
2941 coverage: parts.coverage,
2942 circular_files: parts.circular_files,
2943 top_complex_fns: parts.top_complex_fns,
2944 crap_target_fns: parts.crap_target_fns,
2945 entry_points: parts.entry_points,
2946 value_export_counts: parts.value_export_counts,
2947 unused_export_names: parts.unused_export_names,
2948 cycle_members: parts.cycle_members,
2949 direct_callers: parts.direct_callers,
2950 analysis_counts,
2951 prop_drilling_chains: parts.results.prop_drilling_chains.clone(),
2952 render_fan_in: parts.results.render_fan_in.clone(),
2953 analysis_snapshot,
2954 istanbul_matched: parts.istanbul_matched,
2955 istanbul_total: parts.istanbul_total,
2956 istanbul_files_joined: parts.istanbul_files_joined,
2957 istanbul_files_total: parts.istanbul_files_total,
2958 coverage_input_format: parts.coverage_input_format,
2959 per_function_crap: parts.per_function_crap,
2960 template_inherit_provenance,
2961 static_links: parts
2962 .with_static_links
2963 .then(|| crate::change_coupling::StaticLinkIndex::from_graph(parts.graph)),
2964 }
2965}
2966
2967fn build_file_score_analysis_counts(
2968 results: &crate::results::AnalysisResults,
2969 total_exports: usize,
2970 unused_deps: usize,
2971) -> crate::vital_signs::AnalysisCounts {
2972 crate::vital_signs::AnalysisCounts {
2973 total_exports,
2974 dead_files: results.unused_files.len(),
2975 dead_exports: results.unused_exports.len() + results.unused_types.len(),
2976 unused_deps,
2977 circular_deps: results.circular_dependencies.len(),
2978 total_deps: 0usize,
2979 }
2980}
2981
2982fn build_template_inherit_provenance(
2983 template_inherit: rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
2984 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
2985) -> rustc_hash::FxHashMap<std::path::PathBuf, std::path::PathBuf> {
2986 template_inherit
2987 .into_iter()
2988 .filter_map(|(file_id, ctx)| {
2989 file_paths
2990 .get(&file_id)
2991 .map(|path| ((**path).clone(), ctx.provenance_owner))
2992 })
2993 .collect()
2994}
2995
2996fn record_entry_point(
2997 entry_points: &mut rustc_hash::FxHashSet<std::path::PathBuf>,
2998 node: &fallow_graph::graph::ModuleNode,
2999 path: &std::path::Path,
3000) {
3001 if node.is_entry_point() {
3002 entry_points.insert(path.to_path_buf());
3003 }
3004}
3005
3006fn record_unused_file_export_names(
3007 path: &std::path::Path,
3008 exports: &[fallow_graph::graph::ExportSymbol],
3009 unused_files: &rustc_hash::FxHashSet<&std::path::Path>,
3010 unused_export_names: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
3011) {
3012 if !unused_files.contains(path) || unused_export_names.contains_key(path) {
3013 return;
3014 }
3015
3016 let names: Vec<String> = exports
3017 .iter()
3018 .filter(|export| !export.is_type_only)
3019 .map(|export| export.name.to_string())
3020 .collect();
3021 if !names.is_empty() {
3022 unused_export_names.insert(path.to_path_buf(), names);
3023 }
3024}
3025
3026struct FileScoreCrap {
3027 max: f64,
3028 signals: CrapThresholdSignals,
3029 per_function: Vec<PerFunctionCrap>,
3030 istanbul_matched: usize,
3031 istanbul_total: usize,
3032 coverage_file_joined: bool,
3035}
3036
3037impl FileScoreCrap {
3038 fn empty() -> Self {
3039 Self {
3040 max: 0.0,
3041 signals: CrapThresholdSignals::default(),
3042 per_function: Vec::new(),
3043 istanbul_matched: 0,
3044 istanbul_total: 0,
3045 coverage_file_joined: false,
3046 }
3047 }
3048
3049 fn estimated(result: EstimatedCrapResult) -> Self {
3050 Self {
3051 max: result.max_crap,
3052 signals: result.signals,
3053 per_function: result.per_function,
3054 istanbul_matched: 0,
3055 istanbul_total: 0,
3056 coverage_file_joined: false,
3057 }
3058 }
3059
3060 fn istanbul(result: IstanbulCrapResult, coverage_file_joined: bool) -> Self {
3061 Self {
3062 max: result.max_crap,
3063 signals: result.signals,
3064 per_function: result.per_function,
3065 istanbul_matched: result.matched,
3066 istanbul_total: result.total,
3067 coverage_file_joined,
3068 }
3069 }
3070}
3071
3072fn compute_file_score_crap(
3073 node: &fallow_graph::graph::ModuleNode,
3074 ctx: &FileScoreLoopCtx<'_>,
3075 path: &std::path::Path,
3076 ceilings: &CrapCeilingLookup<'_>,
3077) -> FileScoreCrap {
3078 let Some(module) = ctx.module_by_id.get(&node.file_id).copied() else {
3079 return FileScoreCrap::empty();
3080 };
3081
3082 let is_coverage_suppressed = crate::suppress::is_file_suppressed(
3083 &module.suppressions,
3084 fallow_types::suppress::IssueKind::CoverageGaps,
3085 );
3086 let is_test_reachable = ctx.test_coverage.covers_file(node.file_id) || is_coverage_suppressed;
3087 let resolution = resolve_crap_coverage(
3088 ctx.template_inherit.get(&node.file_id),
3089 ctx.istanbul_coverage,
3090 path,
3091 );
3092 match resolution {
3093 CrapCoverageResolution::TemplateInherited(inherit_ctx) => {
3094 compute_template_inherited_crap(module, inherit_ctx, ceilings)
3095 }
3096 CrapCoverageResolution::Istanbul { file_coverage } => {
3097 compute_istanbul_file_crap(module, file_coverage, is_test_reachable, ceilings)
3098 }
3099 CrapCoverageResolution::StaticEstimated => {
3100 compute_static_file_crap(module, node, ctx.test_coverage, is_test_reachable, ceilings)
3101 }
3102 }
3103}
3104
3105fn compute_template_inherited_crap(
3106 module: &crate::source::ModuleInfo,
3107 inherit_ctx: &TemplateInheritContext,
3108 ceilings: &CrapCeilingLookup<'_>,
3109) -> FileScoreCrap {
3110 FileScoreCrap::estimated(compute_crap_scores_estimated(
3111 &module.complexity,
3112 &inherit_ctx.test_referenced_exports,
3113 inherit_ctx.is_test_reachable,
3114 fallow_output::CoverageSource::EstimatedComponentInherited,
3115 ceilings,
3116 ))
3117}
3118
3119fn compute_istanbul_file_crap(
3120 module: &crate::source::ModuleInfo,
3121 file_coverage: Option<&IstanbulFileCoverage>,
3122 is_test_reachable: bool,
3123 ceilings: &CrapCeilingLookup<'_>,
3124) -> FileScoreCrap {
3125 FileScoreCrap::istanbul(
3126 compute_crap_scores_istanbul(
3127 &module.complexity,
3128 file_coverage,
3129 is_test_reachable,
3130 ceilings,
3131 ),
3132 file_coverage.is_some(),
3133 )
3134}
3135
3136fn compute_static_file_crap(
3137 module: &crate::source::ModuleInfo,
3138 node: &fallow_graph::graph::ModuleNode,
3139 test_coverage: StaticTestCoverage<'_>,
3140 is_test_reachable: bool,
3141 ceilings: &CrapCeilingLookup<'_>,
3142) -> FileScoreCrap {
3143 let test_refs = build_test_referenced_exports(node.file_id, &node.exports, test_coverage);
3144 FileScoreCrap::estimated(compute_crap_scores_estimated(
3145 &module.complexity,
3146 &test_refs,
3147 is_test_reachable,
3148 fallow_output::CoverageSource::Estimated,
3149 ceilings,
3150 ))
3151}
3152
3153fn record_per_function_crap(
3154 per_function_crap: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
3155 path: &std::path::Path,
3156 per_function: Vec<PerFunctionCrap>,
3157) {
3158 if !per_function.is_empty() {
3159 per_function_crap.insert(path.to_path_buf(), per_function);
3160 }
3161}
3162
3163struct FileScoreCoverageSetup<'a> {
3164 module_by_id: rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
3165 coverage: CoverageGapData,
3166}
3167
3168fn prepare_file_score_coverage_setup<'a>(
3169 modules: &'a [crate::source::ModuleInfo],
3170 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3171 results: &crate::results::AnalysisResults,
3172 graph: &fallow_graph::graph::ModuleGraph,
3173 test_coverage: StaticTestCoverage<'_>,
3174 root: &std::path::Path,
3175) -> FileScoreCoverageSetup<'a> {
3176 let module_by_id: rustc_hash::FxHashMap<_, _> =
3177 modules.iter().map(|m| (m.file_id, m)).collect();
3178 let unused_exports: rustc_hash::FxHashSet<(&std::path::Path, String)> = results
3179 .unused_exports
3180 .iter()
3181 .map(|export| {
3182 (
3183 export.export.path.as_path(),
3184 export.export.export_name.clone(),
3185 )
3186 })
3187 .collect();
3188 let coverage = compute_coverage_gaps(
3189 graph,
3190 test_coverage,
3191 file_paths,
3192 &module_by_id,
3193 &unused_exports,
3194 root,
3195 );
3196 FileScoreCoverageSetup {
3197 module_by_id,
3198 coverage,
3199 }
3200}
3201
3202fn collect_circular_files(
3203 results: &crate::results::AnalysisResults,
3204) -> rustc_hash::FxHashSet<std::path::PathBuf> {
3205 results
3206 .circular_dependencies
3207 .iter()
3208 .flat_map(|c| c.cycle.files.iter().cloned())
3209 .collect()
3210}
3211
3212fn collect_top_complex_fns(
3213 modules: &[crate::source::ModuleInfo],
3214 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3215) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>> {
3216 let mut top_complex_fns = rustc_hash::FxHashMap::default();
3217 for module in modules {
3218 if module.complexity.is_empty() {
3219 continue;
3220 }
3221 let Some(path) = file_paths.get(&module.file_id) else {
3222 continue;
3223 };
3224 let mut funcs: Vec<(String, u32, u16)> = module
3229 .complexity
3230 .iter()
3231 .filter(|f| !fallow_types::extract::is_synthetic_module_unit(&f.name))
3232 .map(|f| (f.name.clone(), f.line, f.cognitive))
3233 .collect();
3234 funcs.sort_by_key(|f| std::cmp::Reverse(f.2));
3235 funcs.truncate(MAX_FUNCTION_EVIDENCE);
3236 if funcs.first().is_some_and(|worst| worst.2 > 0) {
3237 top_complex_fns.insert((*path).clone(), funcs);
3238 }
3239 }
3240 top_complex_fns
3241}
3242
3243fn collect_cycle_members(
3244 results: &crate::results::AnalysisResults,
3245) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>> {
3246 let mut cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>> =
3247 rustc_hash::FxHashMap::default();
3248 for cycle in &results.circular_dependencies {
3249 for file in &cycle.cycle.files {
3250 let others: Vec<std::path::PathBuf> = cycle
3251 .cycle
3252 .files
3253 .iter()
3254 .filter(|f| *f != file)
3255 .cloned()
3256 .collect();
3257 cycle_members
3258 .entry(file.clone())
3259 .or_default()
3260 .extend(others);
3261 }
3262 }
3263 for members in cycle_members.values_mut() {
3264 members.sort();
3265 members.dedup();
3266 }
3267 cycle_members
3268}
3269
3270fn collect_unused_export_names(
3271 results: &crate::results::AnalysisResults,
3272) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> {
3273 let mut unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> =
3274 rustc_hash::FxHashMap::default();
3275 for exp in &results.unused_exports {
3276 unused_export_names
3277 .entry(exp.export.path.clone())
3278 .or_default()
3279 .push(exp.export.export_name.clone());
3280 }
3281 unused_export_names
3282}
3283
3284fn build_analysis_counts_snapshot(
3285 graph: &fallow_graph::graph::ModuleGraph,
3286 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3287 results: &crate::results::AnalysisResults,
3288 unused_deps: usize,
3289) -> AnalysisCountsSnapshot {
3290 let mut module_export_counts = rustc_hash::FxHashMap::with_capacity_and_hasher(
3291 graph.modules.len(),
3292 rustc_hash::FxBuildHasher,
3293 );
3294 for module in &graph.modules {
3295 if let Some(path) = file_paths.get(&module.file_id) {
3296 module_export_counts.insert((*path).clone(), module.exports.len());
3297 }
3298 }
3299
3300 let mut unused_export_paths =
3301 Vec::with_capacity(results.unused_exports.len() + results.unused_types.len());
3302 unused_export_paths.extend(results.unused_exports.iter().map(|e| e.export.path.clone()));
3303 unused_export_paths.extend(results.unused_types.iter().map(|e| e.export.path.clone()));
3304
3305 let mut unused_dep_package_paths = Vec::with_capacity(unused_deps);
3306 unused_dep_package_paths.extend(
3307 results
3308 .unused_dependencies
3309 .iter()
3310 .map(|d| d.dep.path.clone()),
3311 );
3312 unused_dep_package_paths.extend(
3313 results
3314 .unused_dev_dependencies
3315 .iter()
3316 .map(|d| d.dep.path.clone()),
3317 );
3318 unused_dep_package_paths.extend(
3319 results
3320 .unused_optional_dependencies
3321 .iter()
3322 .map(|d| d.dep.path.clone()),
3323 );
3324
3325 AnalysisCountsSnapshot {
3326 unused_file_paths: results
3327 .unused_files
3328 .iter()
3329 .map(|f| f.file.path.clone())
3330 .collect(),
3331 unused_export_paths,
3332 unused_dep_package_paths,
3333 circular_dep_groups: results
3334 .circular_dependencies
3335 .iter()
3336 .map(|c| c.cycle.files.clone())
3337 .collect(),
3338 module_export_counts,
3339 }
3340}
3341
3342#[cfg(test)]
3343#[path = "scoring_private_member_tests.rs"]
3344mod private_member_tests;
3345
3346#[cfg(test)]
3347#[path = "scoring_tests.rs"]
3348mod tests;