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