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