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> {
1631 let candidates = [
1632 root.join("coverage/coverage-final.json"),
1633 root.join(".nyc_output/coverage-final.json"),
1634 ];
1635 candidates
1636 .into_iter()
1637 .find(|p| p.is_file() && fallow_types::read_guard::is_inside_root(root, p))
1638}
1639
1640pub fn resolve_relative_to_root(
1646 path: &std::path::Path,
1647 project_root: Option<&std::path::Path>,
1648) -> std::path::PathBuf {
1649 if fallow_types::path_util::is_absolute_path_any_platform(path) {
1650 return path.to_path_buf();
1651 }
1652 match project_root {
1653 Some(root) => root.join(path),
1654 None => path.to_path_buf(),
1655 }
1656}
1657
1658#[cfg(test)]
1673fn load_istanbul_coverage(
1674 path: &std::path::Path,
1675 coverage_root: Option<&std::path::Path>,
1676 project_root: Option<&std::path::Path>,
1677 relocated: bool,
1678) -> Result<IstanbulCoverage, String> {
1679 load_istanbul_coverage_for_sources(path, coverage_root, project_root, None, relocated)
1680}
1681
1682pub(super) fn load_istanbul_coverage_for_sources(
1683 path: &std::path::Path,
1684 coverage_root: Option<&std::path::Path>,
1685 project_root: Option<&std::path::Path>,
1686 discovered_sources: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1687 relocated: bool,
1688) -> Result<IstanbulCoverage, String> {
1689 super::validate_coverage_root_absolute(coverage_root)?;
1690 let resolved = resolve_relative_to_root(path, project_root);
1691 match read_coverage_input(&resolved, project_root)? {
1692 CoverageInput::Istanbul { file_path, json } => {
1693 let raw = parse_coverage_map_tolerantly(&json).map_err(|e| {
1694 format!(
1695 "failed to parse coverage data from {}: {e}",
1696 file_path.display()
1697 )
1698 })?;
1699 let sources = CoverageMapSources {
1700 coverage_root,
1701 project_root,
1702 discovered_sources,
1703 relocated,
1704 };
1705 Ok(build_istanbul_coverage(
1706 &raw,
1707 &sources,
1708 fallow_output::CoverageInputFormat::Istanbul,
1709 ))
1710 }
1711 CoverageInput::V8 { dump_files } => {
1712 let scope = super::coverage_v8::V8ScriptScope {
1713 coverage_root,
1714 project_root,
1715 discovered_sources,
1716 };
1717 let raw = super::coverage_v8::load_v8_coverage_map(&dump_files, &scope)?;
1718 let sources = CoverageMapSources {
1720 coverage_root: None,
1721 project_root,
1722 discovered_sources,
1723 relocated,
1724 };
1725 Ok(build_istanbul_coverage(
1726 &raw,
1727 &sources,
1728 fallow_output::CoverageInputFormat::V8,
1729 ))
1730 }
1731 }
1732}
1733
1734#[derive(Clone, Copy)]
1736struct CoverageMapSources<'a> {
1737 coverage_root: Option<&'a std::path::Path>,
1738 project_root: Option<&'a std::path::Path>,
1739 discovered_sources: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
1740 relocated: bool,
1741}
1742
1743fn build_istanbul_coverage(
1744 raw: &std::collections::BTreeMap<String, oxc_coverage_instrument::FileCoverage>,
1745 sources: &CoverageMapSources<'_>,
1746 format: fallow_output::CoverageInputFormat,
1747) -> IstanbulCoverage {
1748 let CoverageMapSources {
1749 coverage_root,
1750 project_root,
1751 discovered_sources,
1752 relocated,
1753 } = *sources;
1754 let mut files = rustc_hash::FxHashMap::default();
1755 for file_cov in raw.values() {
1756 let raw_path = resolve_relative_to_root(std::path::Path::new(&file_cov.path), project_root);
1761 let file_path = if let (Some(cov_root), Some(proj_root)) = (coverage_root, project_root) {
1762 rebase_coverage_path(raw_path, cov_root, proj_root)
1763 } else {
1764 raw_path
1765 };
1766 let canonical = dunce::canonicalize(&file_path).unwrap_or(file_path);
1767 let source = read_discovered_source(&canonical, discovered_sources, relocated);
1768 let source_index = source
1769 .as_deref()
1770 .map(|source| IstanbulSourceIndex::new(source, &canonical));
1771
1772 let statement_owners = tally_statements_by_owner(file_cov);
1773 let mut functions = Vec::with_capacity(file_cov.fn_map.len());
1774 for (fn_id, fn_entry) in &file_cov.fn_map {
1775 let coverage_pct = compute_function_statement_coverage(
1776 file_cov,
1777 fn_id,
1778 statement_owners.get(fn_id.as_str()),
1779 );
1780 if let Some(function) =
1781 istanbul_function_coverage(fn_entry, coverage_pct, source_index.as_ref())
1782 {
1783 functions.push(function);
1784 }
1785 }
1786
1787 files.insert(canonical, IstanbulFileCoverage::new(functions, relocated));
1788 }
1789
1790 IstanbulCoverage { files, format }
1791}
1792
1793#[expect(
1794 clippy::filetype_is_file,
1795 reason = "coverage provenance must admit regular files and reject every special file type"
1796)]
1797fn read_discovered_source(
1798 path: &std::path::Path,
1799 discovered_sources: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1800 relocated: bool,
1801) -> Option<String> {
1802 if relocated || !discovered_sources.is_some_and(|sources| sources.contains(path)) {
1803 return None;
1804 }
1805 if std::fs::symlink_metadata(path).ok()?.file_type().is_file() {
1806 std::fs::read_to_string(path).ok()
1807 } else {
1808 None
1809 }
1810}
1811
1812fn parse_coverage_map_tolerantly(
1822 json: &str,
1823) -> Result<std::collections::BTreeMap<String, oxc_coverage_instrument::FileCoverage>, String> {
1824 match oxc_coverage_instrument::parse_coverage_map(json) {
1825 Ok(raw) => Ok(raw),
1826 Err(strict_error) => {
1827 let mut value: serde_json::Value =
1828 serde_json::from_str(json).map_err(|_| strict_error.to_string())?;
1829 let positions = clamp_negative_positions(&mut value);
1830 let counts = clamp_negative_counts(&mut value);
1831 if !positions && !counts {
1832 return Err(strict_error.to_string());
1833 }
1834 serde_json::from_value(value).map_err(|_| strict_error.to_string())
1835 }
1836 }
1837}
1838
1839fn clamp_negative_positions(value: &mut serde_json::Value) -> bool {
1843 match value {
1844 serde_json::Value::Object(entries) => {
1845 let mut clamped = false;
1846 for (key, child) in entries.iter_mut() {
1847 if matches!(key.as_str(), "line" | "column")
1848 && child.as_i64().is_some_and(|number| number < 0)
1849 {
1850 *child = serde_json::Value::from(0);
1851 clamped = true;
1852 continue;
1853 }
1854 clamped |= clamp_negative_positions(child);
1855 }
1856 clamped
1857 }
1858 serde_json::Value::Array(items) => items.iter_mut().fold(false, |clamped, item| {
1859 clamped | clamp_negative_positions(item)
1860 }),
1861 _ => false,
1862 }
1863}
1864
1865const COVERAGE_COUNT_KEYS: [&str; 4] = ["s", "f", "b", "b_T"];
1867
1868fn clamp_negative_counts(value: &mut serde_json::Value) -> bool {
1872 let serde_json::Value::Object(files) = value else {
1873 return false;
1874 };
1875 let mut clamped = false;
1876 for file in files.values_mut() {
1877 let serde_json::Value::Object(sections) = file else {
1878 continue;
1879 };
1880 for key in COVERAGE_COUNT_KEYS {
1881 if let Some(counts) = sections.get_mut(key) {
1882 clamped |= clamp_negative_numbers(counts);
1883 }
1884 }
1885 }
1886 clamped
1887}
1888
1889fn clamp_negative_numbers(value: &mut serde_json::Value) -> bool {
1892 match value {
1893 serde_json::Value::Number(number) if number.as_f64().is_some_and(|n| n < 0.0) => {
1894 *value = serde_json::Value::from(0);
1895 true
1896 }
1897 serde_json::Value::Object(entries) => entries.values_mut().fold(false, |clamped, child| {
1898 clamped | clamp_negative_numbers(child)
1899 }),
1900 serde_json::Value::Array(items) => items.iter_mut().fold(false, |clamped, item| {
1901 clamped | clamp_negative_numbers(item)
1902 }),
1903 _ => false,
1904 }
1905}
1906
1907fn accessor_property_name(name: &str) -> Option<&str> {
1915 let property = name
1916 .strip_prefix("get ")
1917 .or_else(|| name.strip_prefix("set "))?;
1918 (!property.is_empty() && !property.contains(' ')).then_some(property)
1919}
1920
1921fn rebase_coverage_path(
1929 raw_path: std::path::PathBuf,
1930 coverage_root: &std::path::Path,
1931 project_root: &std::path::Path,
1932) -> std::path::PathBuf {
1933 if let Ok(rel) = raw_path.strip_prefix(coverage_root) {
1934 return project_root.join(rel);
1935 }
1936 if let Ok(canonical) = dunce::canonicalize(&raw_path)
1937 && let Ok(rel) = canonical.strip_prefix(coverage_root)
1938 {
1939 return project_root.join(rel);
1940 }
1941 raw_path
1942}
1943
1944fn istanbul_function_coverage(
1945 fn_entry: &oxc_coverage_instrument::FnEntry,
1946 coverage_pct: f64,
1947 source_index: Option<&IstanbulSourceIndex<'_>>,
1948) -> Option<IstanbulFunctionCoverage> {
1949 let body_span = IstanbulSpan::from_entry(fn_entry, source_index);
1950 let header_span = IstanbulSpan::header_from_entry(fn_entry, source_index);
1951 let decl_start = normalized_istanbul_position(
1952 fn_entry.decl.start.line,
1953 fn_entry.decl.start.column,
1954 source_index,
1955 )?;
1956 let effective_position = normalized_istanbul_position(
1957 effective_istanbul_fn_line(fn_entry),
1958 fn_entry.decl.start.column,
1959 source_index,
1960 );
1961 let candidates = [
1962 effective_position.map(|position| IstanbulAlias {
1963 position,
1964 primary: true,
1965 }),
1966 Some(IstanbulAlias {
1967 position: decl_start,
1968 primary: true,
1969 }),
1970 body_span.map(|span| IstanbulAlias {
1971 position: span.start,
1972 primary: false,
1973 }),
1974 named_function_syntax_alias(fn_entry, source_index),
1975 ];
1976 let mut aliases: Vec<IstanbulAlias> = Vec::with_capacity(candidates.len());
1977 for candidate in candidates.into_iter().flatten() {
1978 if !aliases
1979 .iter()
1980 .any(|alias| alias.position == candidate.position)
1981 {
1982 aliases.push(candidate);
1983 }
1984 }
1985
1986 Some(IstanbulFunctionCoverage {
1987 name: fn_entry.name.clone(),
1988 coverage_pct,
1989 aliases,
1990 decl_start,
1991 header_holds_other_fn: false,
1992 header_span,
1993 body_span,
1994 })
1995}
1996
1997struct IstanbulSourceIndex<'a> {
2000 source: &'a str,
2001 line_starts: Vec<usize>,
2002 non_ascii_lines: rustc_hash::FxHashMap<usize, Utf16LineIndex>,
2003 named_function_starts: rustc_hash::FxHashMap<usize, usize>,
2004}
2005
2006struct Utf16LineIndex {
2007 utf16_len: u32,
2008 byte_len: usize,
2009 checkpoints: Vec<Utf16Checkpoint>,
2010}
2011
2012struct Utf16Checkpoint {
2013 utf16_start: u32,
2014 utf16_end: u32,
2015 byte_end: usize,
2016}
2017
2018impl<'a> IstanbulSourceIndex<'a> {
2019 fn new(source: &'a str, path: &std::path::Path) -> Self {
2020 let mut line_starts = vec![0];
2021 line_starts.extend(
2022 source
2023 .bytes()
2024 .enumerate()
2025 .filter_map(|(index, byte)| (byte == b'\n').then_some(index + 1)),
2026 );
2027 let non_ascii_lines = utf16_line_indexes(source, &line_starts);
2028
2029 let named_function_starts = named_function_starts_from_clean_parse(source, path);
2030
2031 Self {
2032 source,
2033 line_starts,
2034 non_ascii_lines,
2035 named_function_starts,
2036 }
2037 }
2038
2039 fn byte_position(&self, line: u32, utf16_column: u32) -> Option<IstanbulPosition> {
2040 let line_index = usize::try_from(line.checked_sub(1)?).ok()?;
2041 let line_start = *self.line_starts.get(line_index)?;
2042 let line_end = self
2043 .line_starts
2044 .get(line_index + 1)
2045 .copied()
2046 .map_or(self.source.len(), |next_start| next_start - 1);
2047 let line_source = self.source.get(line_start..line_end)?;
2048 let byte_column = if let Some(index) = self.non_ascii_lines.get(&line_index) {
2049 index.byte_column(utf16_column)?
2050 } else {
2051 let byte_column = usize::try_from(utf16_column).ok()?;
2052 (byte_column <= line_source.len()).then_some(byte_column)?
2053 };
2054 Some(IstanbulPosition::new(
2055 line,
2056 u32::try_from(byte_column).ok()?,
2057 ))
2058 }
2059
2060 fn absolute_offset(&self, line: u32, utf16_column: u32) -> Option<usize> {
2061 let position = self.byte_position(line, utf16_column)?;
2062 let line_index = usize::try_from(position.line.checked_sub(1)?).ok()?;
2063 self.line_starts
2064 .get(line_index)?
2065 .checked_add(position.col as usize)
2066 }
2067
2068 fn position_at_offset(&self, offset: usize) -> Option<IstanbulPosition> {
2069 if offset > self.source.len() {
2070 return None;
2071 }
2072 let line_index = self.line_starts.partition_point(|start| *start <= offset) - 1;
2073 Some(IstanbulPosition::new(
2074 u32::try_from(line_index + 1).ok()?,
2075 u32::try_from(offset.checked_sub(self.line_starts[line_index])?).ok()?,
2076 ))
2077 }
2078
2079 fn named_function_start(
2080 &self,
2081 fn_entry: &oxc_coverage_instrument::FnEntry,
2082 ) -> Option<IstanbulPosition> {
2083 let declaration_offset =
2084 self.absolute_offset(fn_entry.decl.start.line, fn_entry.decl.start.column)?;
2085 let syntax_offset = *self.named_function_starts.get(&declaration_offset)?;
2086 self.position_at_offset(syntax_offset)
2087 }
2088}
2089
2090impl Utf16LineIndex {
2091 fn byte_column(&self, utf16_column: u32) -> Option<usize> {
2092 if utf16_column > self.utf16_len {
2093 return None;
2094 }
2095 let completed = self
2096 .checkpoints
2097 .partition_point(|checkpoint| checkpoint.utf16_end <= utf16_column);
2098 if let Some(next) = self.checkpoints.get(completed)
2099 && utf16_column > next.utf16_start
2100 {
2101 return None;
2102 }
2103 let (utf16_base, byte_base) = completed
2104 .checked_sub(1)
2105 .and_then(|index| self.checkpoints.get(index))
2106 .map_or((0, 0), |checkpoint| {
2107 (checkpoint.utf16_end, checkpoint.byte_end)
2108 });
2109 let ascii_width = usize::try_from(utf16_column.checked_sub(utf16_base)?).ok()?;
2110 let byte_column = byte_base.checked_add(ascii_width)?;
2111 (byte_column <= self.byte_len).then_some(byte_column)
2112 }
2113}
2114
2115fn utf16_line_indexes(
2116 source: &str,
2117 line_starts: &[usize],
2118) -> rustc_hash::FxHashMap<usize, Utf16LineIndex> {
2119 let mut indexes = rustc_hash::FxHashMap::default();
2120 for (line_index, &line_start) in line_starts.iter().enumerate() {
2121 let line_end = line_starts
2122 .get(line_index + 1)
2123 .copied()
2124 .map_or(source.len(), |next_start| next_start - 1);
2125 let Some(line) = source.get(line_start..line_end) else {
2126 continue;
2127 };
2128 if line.is_ascii() {
2129 continue;
2130 }
2131 let mut utf16_column = 0_u32;
2132 let mut checkpoints = Vec::new();
2133 for (byte_column, character) in line.char_indices() {
2134 let utf16_width = character.len_utf16() as u32;
2135 if !character.is_ascii() {
2136 checkpoints.push(Utf16Checkpoint {
2137 utf16_start: utf16_column,
2138 utf16_end: utf16_column.saturating_add(utf16_width),
2139 byte_end: byte_column.saturating_add(character.len_utf8()),
2140 });
2141 }
2142 utf16_column = utf16_column.saturating_add(utf16_width);
2143 }
2144 indexes.insert(
2145 line_index,
2146 Utf16LineIndex {
2147 utf16_len: utf16_column,
2148 byte_len: line.len(),
2149 checkpoints,
2150 },
2151 );
2152 }
2153 indexes
2154}
2155
2156fn named_function_starts_from_clean_parse(
2157 source: &str,
2158 path: &std::path::Path,
2159) -> rustc_hash::FxHashMap<usize, usize> {
2160 let source_type = match path.extension().and_then(|extension| extension.to_str()) {
2161 Some("gts") => oxc_span::SourceType::ts(),
2162 Some("gjs") => oxc_span::SourceType::mjs(),
2163 _ => oxc_span::SourceType::from_path(path).unwrap_or_default(),
2164 };
2165 if let Some(starts) = collect_named_function_starts(source, source_type) {
2166 return starts;
2167 }
2168 if source_type.is_jsx() {
2169 return rustc_hash::FxHashMap::default();
2170 }
2171 let jsx_source_type = if source_type.is_typescript() {
2172 oxc_span::SourceType::tsx()
2173 } else {
2174 oxc_span::SourceType::jsx()
2175 };
2176 collect_named_function_starts(source, jsx_source_type).unwrap_or_default()
2177}
2178
2179fn collect_named_function_starts(
2180 source: &str,
2181 source_type: oxc_span::SourceType,
2182) -> Option<rustc_hash::FxHashMap<usize, usize>> {
2183 fallow_extract::parse_bounded_or_default(source, source_type, |parsed| {
2184 if parsed.fatal_error || !parsed.diagnostics.is_empty() {
2185 return None;
2186 }
2187 let mut starts = rustc_hash::FxHashMap::default();
2188 let mut collector = NamedFunctionSyntaxCollector {
2189 starts: &mut starts,
2190 };
2191 oxc_ast_visit::Visit::visit_program(&mut collector, &parsed.program);
2192 Some(starts)
2193 })
2194}
2195
2196struct NamedFunctionSyntaxCollector<'a> {
2197 starts: &'a mut rustc_hash::FxHashMap<usize, usize>,
2198}
2199
2200impl<'ast> oxc_ast_visit::Visit<'ast> for NamedFunctionSyntaxCollector<'_> {
2201 fn visit_function(
2202 &mut self,
2203 function: &oxc_ast::ast::Function<'ast>,
2204 flags: oxc_syntax::scope::ScopeFlags,
2205 ) {
2206 if let Some(identifier) = &function.id
2207 && let (Ok(identifier_start), Ok(syntax_start)) = (
2208 usize::try_from(identifier.span.start),
2209 usize::try_from(function.span.start),
2210 )
2211 {
2212 self.starts.insert(identifier_start, syntax_start);
2213 }
2214 oxc_ast_visit::walk::walk_function(self, function, flags);
2215 }
2216}
2217
2218fn normalized_istanbul_position(
2219 line: u32,
2220 column: u32,
2221 source_index: Option<&IstanbulSourceIndex<'_>>,
2222) -> Option<IstanbulPosition> {
2223 match source_index {
2224 Some(index) => index.byte_position(line, column),
2225 None => Some(IstanbulPosition::new(line, column)),
2226 }
2227}
2228
2229fn named_function_syntax_alias(
2235 fn_entry: &oxc_coverage_instrument::FnEntry,
2236 source_index: Option<&IstanbulSourceIndex<'_>>,
2237) -> Option<IstanbulAlias> {
2238 if is_anonymous_istanbul_name(&fn_entry.name) {
2239 return None;
2240 }
2241 Some(IstanbulAlias {
2242 position: source_index?.named_function_start(fn_entry)?,
2243 primary: true,
2244 })
2245}
2246
2247fn effective_istanbul_fn_line(fn_entry: &oxc_coverage_instrument::FnEntry) -> u32 {
2248 if fn_entry.line > 0 {
2249 fn_entry.line
2250 } else {
2251 fn_entry.decl.start.line
2252 }
2253}
2254
2255#[derive(Default)]
2257struct StatementTally {
2258 covered: u32,
2259 total: u32,
2260}
2261
2262fn istanbul_range_contains(
2268 outer: &oxc_coverage_instrument::Location,
2269 inner: &oxc_coverage_instrument::Location,
2270) -> bool {
2271 let after_start = inner.start.line > outer.start.line
2272 || (inner.start.line == outer.start.line && inner.start.column >= outer.start.column);
2273 let before_end = inner.end.line < outer.end.line
2274 || (inner.end.line == outer.end.line && inner.end.column <= outer.end.column);
2275 after_start && before_end
2276}
2277
2278fn tally_statements_by_owner(
2298 file_cov: &oxc_coverage_instrument::FileCoverage,
2299) -> rustc_hash::FxHashMap<&str, StatementTally> {
2300 let mut owners: rustc_hash::FxHashMap<&str, StatementTally> = rustc_hash::FxHashMap::default();
2301
2302 for (stmt_id, stmt_loc) in &file_cov.statement_map {
2303 let mut owner: Option<(&str, &oxc_coverage_instrument::Location)> = None;
2304
2305 for (fn_id, fn_entry) in &file_cov.fn_map {
2306 if !istanbul_range_contains(&fn_entry.loc, stmt_loc) {
2307 continue;
2308 }
2309 let inner_than_current = owner.is_none_or(|(_, best)| {
2310 let candidate = (
2311 (fn_entry.loc.start.line, fn_entry.loc.start.column),
2312 std::cmp::Reverse((fn_entry.loc.end.line, fn_entry.loc.end.column)),
2313 );
2314 let incumbent = (
2315 (best.start.line, best.start.column),
2316 std::cmp::Reverse((best.end.line, best.end.column)),
2317 );
2318 candidate > incumbent
2319 });
2320 if inner_than_current {
2321 owner = Some((fn_id.as_str(), &fn_entry.loc));
2322 }
2323 }
2324
2325 let Some((fn_id, _)) = owner else {
2326 continue;
2327 };
2328 let tally = owners.entry(fn_id).or_default();
2329 tally.total += 1;
2330 if file_cov.s.get(stmt_id).copied().unwrap_or(0) > 0 {
2331 tally.covered += 1;
2332 }
2333 }
2334
2335 owners
2336}
2337
2338fn compute_function_statement_coverage(
2347 file_cov: &oxc_coverage_instrument::FileCoverage,
2348 fn_id: &str,
2349 owned: Option<&StatementTally>,
2350) -> f64 {
2351 match owned {
2352 Some(tally) if tally.total > 0 => f64::from(tally.covered) / f64::from(tally.total) * 100.0,
2353 _ => {
2354 let hit = file_cov.f.get(fn_id).copied().unwrap_or(0);
2355 if hit > 0 { 100.0 } else { 0.0 }
2356 }
2357 }
2358}
2359
2360fn count_unused_exports_by_path(
2365 unused_exports: &[crate::results::UnusedExportFinding],
2366) -> rustc_hash::FxHashMap<&std::path::Path, usize> {
2367 let mut map: rustc_hash::FxHashMap<&std::path::Path, usize> = rustc_hash::FxHashMap::default();
2368 for exp in unused_exports {
2369 *map.entry(exp.export.path.as_path()).or_default() += 1;
2370 }
2371 map
2372}
2373
2374fn compute_maintainability_index(
2394 complexity_density: f64,
2395 dead_code_ratio: f64,
2396 fan_out: usize,
2397 lines: u32,
2398) -> f64 {
2399 let dampening = (f64::from(lines) / fallow_output::MI_DENSITY_MIN_LINES).min(1.0);
2400 let fan_out_penalty = ((fan_out as f64).ln_1p() * 4.0).min(15.0);
2401 #[expect(
2402 clippy::suboptimal_flops,
2403 reason = "formula matches documented specification"
2404 )]
2405 let score = 100.0
2406 - (complexity_density * 30.0 * dampening)
2407 - (dead_code_ratio * 20.0)
2408 - fan_out_penalty;
2409 score.clamp(0.0, 100.0)
2410}
2411
2412fn file_score_structural_concern(score: &FileHealthScore) -> f64 {
2413 (100.0 - score.maintainability_index).clamp(0.0, 100.0)
2414}
2415
2416#[must_use]
2422pub fn file_score_fully_crap_exempt(score: &FileHealthScore, max_crap_threshold: f64) -> bool {
2423 let signal = file_score_crap_signal(score, max_crap_threshold);
2424 max_crap_threshold <= 0.0
2425 || (score.crap_above_threshold == 0
2426 && if signal.suppression_aware {
2427 signal.maximum >= CRAP_THRESHOLD
2428 } else {
2429 score.crap_exempted > 0
2430 })
2431}
2432
2433pub struct FileScoreCrapSignal {
2435 pub maximum: f64,
2437 pub threshold: f64,
2439 suppression_aware: bool,
2440}
2441
2442impl FileScoreCrapSignal {
2443 pub const fn metric(&self) -> &'static str {
2445 if self.suppression_aware {
2446 "crap_unsuppressed_max"
2447 } else {
2448 "crap_max"
2449 }
2450 }
2451}
2452
2453pub fn file_score_crap_signal(score: &FileHealthScore, global: f64) -> FileScoreCrapSignal {
2456 match (
2457 score.crap_unsuppressed_max,
2458 score.crap_unsuppressed_effective_threshold,
2459 ) {
2460 (Some(maximum), Some(threshold)) => FileScoreCrapSignal {
2461 maximum,
2462 threshold,
2463 suppression_aware: true,
2464 },
2465 _ => FileScoreCrapSignal {
2466 maximum: score.crap_max,
2467 threshold: score.crap_effective_threshold.unwrap_or(global),
2468 suppression_aware: false,
2469 },
2470 }
2471}
2472
2473fn file_score_crap_concern(score: &FileHealthScore, max_crap_threshold: f64) -> f64 {
2480 if file_score_fully_crap_exempt(score, max_crap_threshold) {
2481 return 0.0;
2482 }
2483 let signal = file_score_crap_signal(score, max_crap_threshold);
2484 let crap_max = signal.maximum;
2485 let t = signal.threshold;
2486 let half = t / 2.0;
2487 let saturation = t * 10.0 / 3.0;
2488 if crap_max <= 0.0 {
2489 0.0
2490 } else if crap_max < half {
2491 (crap_max / half) * 45.0
2492 } else if crap_max < t {
2493 ((crap_max - half) / half).mul_add(30.0, 45.0)
2494 } else if crap_max < saturation {
2495 ((crap_max - t) / (saturation - t)).mul_add(25.0, 75.0)
2496 } else {
2497 100.0
2498 }
2499}
2500
2501fn file_score_triage_concern(score: &FileHealthScore, max_crap_threshold: f64) -> f64 {
2502 file_score_structural_concern(score).max(file_score_crap_concern(score, max_crap_threshold))
2503}
2504
2505#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2511pub enum FileScoreConcern {
2512 Structural,
2514 Risk,
2516}
2517
2518impl FileScoreConcern {
2519 pub const fn label(self) -> &'static str {
2521 match self {
2522 Self::Structural => "structure",
2523 Self::Risk => "risk",
2524 }
2525 }
2526}
2527
2528pub fn file_score_concern_axis(
2537 score: &FileHealthScore,
2538 max_crap_threshold: f64,
2539) -> FileScoreConcern {
2540 let crap_concern = file_score_crap_concern(score, max_crap_threshold);
2541 if crap_concern <= 0.0 {
2542 FileScoreConcern::Structural
2543 } else if crap_concern >= file_score_structural_concern(score) {
2544 FileScoreConcern::Risk
2545 } else {
2546 FileScoreConcern::Structural
2547 }
2548}
2549
2550fn compare_file_score_triage(
2551 a: &FileHealthScore,
2552 b: &FileHealthScore,
2553 max_crap_threshold: f64,
2554) -> std::cmp::Ordering {
2555 file_score_triage_concern(b, max_crap_threshold)
2556 .total_cmp(&file_score_triage_concern(a, max_crap_threshold))
2557 .then_with(|| {
2558 file_score_crap_signal(b, max_crap_threshold)
2559 .maximum
2560 .total_cmp(&file_score_crap_signal(a, max_crap_threshold).maximum)
2561 })
2562 .then_with(|| a.maintainability_index.total_cmp(&b.maintainability_index))
2563 .then_with(|| a.path.cmp(&b.path))
2564}
2565
2566#[derive(Clone, Copy)]
2569pub(super) struct FileScoreComputeInput<'a> {
2570 pub(super) modules: &'a [crate::source::ModuleInfo],
2571 pub(super) file_paths:
2572 &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
2573 pub(super) changed_files: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
2574 pub(super) istanbul_coverage: Option<&'a IstanbulCoverage>,
2575 pub(super) root: &'a std::path::Path,
2576 pub(super) crap_thresholds: CrapScoreThresholds<'a>,
2577 pub(super) with_static_links: bool,
2580 pub(super) test_reach: Option<&'a super::test_reach::TestReachGraph>,
2583}
2584
2585pub(super) fn compute_file_scores(
2591 input: FileScoreComputeInput<'_>,
2592 analysis_output: crate::results::DeadCodeAnalysisArtifacts,
2593) -> Result<FileScoreOutput, String> {
2594 let FileScoreComputeInput {
2595 modules,
2596 file_paths,
2597 changed_files,
2598 istanbul_coverage,
2599 root,
2600 crap_thresholds,
2601 with_static_links,
2602 test_reach,
2603 } = input;
2604 let retained_graph = analysis_output.graph.ok_or("graph not available")?;
2605 let test_coverage = test_reach.map_or_else(
2606 || retained_graph.static_test_coverage(),
2607 super::test_reach::TestReachGraph::static_test_coverage,
2608 );
2609 let graph = retained_graph.as_graph();
2610 let results = &analysis_output.results;
2611
2612 let circular_files = super::cycle_files::collect_circular_files(results);
2613 let top_complex_fns = collect_top_complex_fns(modules, file_paths);
2614 let cycle_members = super::cycle_files::collect_cycle_members(results);
2615 let direct_callers = collect_direct_callers(graph, file_paths);
2616 let unused_export_names = collect_unused_export_names(results);
2617
2618 let unused_files: rustc_hash::FxHashSet<&std::path::Path> = results
2619 .unused_files
2620 .iter()
2621 .map(|f| f.file.path.as_path())
2622 .collect();
2623
2624 let unused_exports_by_path = count_unused_exports_by_path(&results.unused_exports);
2625
2626 let FileScoreCoverageSetup {
2627 module_by_id,
2628 coverage,
2629 } = prepare_file_score_coverage_setup(modules, file_paths, results, graph, test_coverage, root);
2630
2631 let template_inherit =
2632 build_template_inherit_contexts(graph, test_coverage, &module_by_id, file_paths);
2633
2634 let mut acc = accumulate_file_scores(
2635 unused_export_names,
2636 &FileScoreLoopCtx {
2637 graph,
2638 test_coverage,
2639 file_paths,
2640 module_by_id: &module_by_id,
2641 unused_files: &unused_files,
2642 unused_exports_by_path: &unused_exports_by_path,
2643 template_inherit: &template_inherit,
2644 istanbul_coverage,
2645 root,
2646 crap_thresholds,
2647 },
2648 );
2649 acc.scores = finalize_file_score_list(
2650 acc.scores,
2651 changed_files,
2652 crap_thresholds.resolver.global.crap,
2653 );
2654
2655 Ok(build_file_score_output(FileScoreOutputParts {
2656 graph,
2657 with_static_links,
2658 file_paths,
2659 results,
2660 scores: acc.scores,
2661 coverage,
2662 circular_files,
2663 top_complex_fns,
2664 crap_target_fns: acc.crap_target_fns,
2665 entry_points: acc.entry_points,
2666 value_export_counts: acc.value_export_counts,
2667 unused_export_names: acc.unused_export_names,
2668 cycle_members,
2669 direct_callers,
2670 istanbul_matched: acc.istanbul_matched,
2671 istanbul_total: acc.istanbul_total,
2672 istanbul_files_joined: acc.istanbul_files_joined,
2673 istanbul_files_total: acc.istanbul_files_total,
2674 coverage_input_format: istanbul_coverage.map(IstanbulCoverage::format),
2675 per_function_crap: acc.per_function_crap,
2676 template_inherit,
2677 }))
2678}
2679
2680struct FileScoreLoopCtx<'a> {
2682 graph: &'a fallow_graph::graph::ModuleGraph,
2683 test_coverage: StaticTestCoverage<'a>,
2684 file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
2685 module_by_id: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
2686 unused_files: &'a rustc_hash::FxHashSet<&'a std::path::Path>,
2687 unused_exports_by_path: &'a rustc_hash::FxHashMap<&'a std::path::Path, usize>,
2688 template_inherit: &'a rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
2689 istanbul_coverage: Option<&'a IstanbulCoverage>,
2690 root: &'a std::path::Path,
2693 crap_thresholds: CrapScoreThresholds<'a>,
2694}
2695
2696struct FileScoreAccumulator {
2698 scores: Vec<FileHealthScore>,
2699 entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
2700 value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
2701 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2702 crap_target_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
2703 per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
2704 istanbul_matched: usize,
2705 istanbul_files_joined: usize,
2706 istanbul_files_total: usize,
2707 istanbul_total: usize,
2708}
2709
2710impl FileScoreAccumulator {
2711 fn with_capacity(modules: usize) -> Self {
2713 FileScoreAccumulator {
2714 scores: Vec::with_capacity(modules),
2715 entry_points: rustc_hash::FxHashSet::default(),
2716 value_export_counts: rustc_hash::FxHashMap::default(),
2717 unused_export_names: rustc_hash::FxHashMap::default(),
2718 crap_target_fns: rustc_hash::FxHashMap::default(),
2719 per_function_crap: rustc_hash::FxHashMap::default(),
2720 istanbul_matched: 0,
2721 istanbul_total: 0,
2722 istanbul_files_joined: 0,
2723 istanbul_files_total: 0,
2724 }
2725 }
2726}
2727
2728fn accumulate_file_scores(
2731 unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2732 ctx: &FileScoreLoopCtx<'_>,
2733) -> FileScoreAccumulator {
2734 let mut acc = FileScoreAccumulator {
2735 unused_export_names,
2736 istanbul_files_total: ctx
2737 .istanbul_coverage
2738 .map_or(0, IstanbulCoverage::file_count),
2739 ..FileScoreAccumulator::with_capacity(ctx.graph.module_count())
2740 };
2741 for node in ctx.graph.modules() {
2742 let Some(path) = ctx.file_paths.get(&node.file_id) else {
2743 continue;
2744 };
2745 record_entry_point(&mut acc.entry_points, node, path);
2746 let score = compute_one_file_score(&mut acc, ctx, node, path);
2747 acc.scores.push(score);
2748 }
2749 acc
2750}
2751
2752fn finalize_file_score_list(
2755 mut scores: Vec<FileHealthScore>,
2756 changed_files: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
2757 max_crap_threshold: f64,
2758) -> Vec<FileHealthScore> {
2759 if let Some(changed) = changed_files {
2760 scores.retain(|s| changed.contains(&s.path));
2761 }
2762 scores.retain(|s| s.function_count > 0);
2763 scores.sort_by(|a, b| compare_file_score_triage(a, b, max_crap_threshold));
2764 scores
2765}
2766
2767fn compute_one_file_score(
2769 acc: &mut FileScoreAccumulator,
2770 ctx: &FileScoreLoopCtx<'_>,
2771 node: &fallow_graph::graph::ModuleNode,
2772 path: &std::path::Path,
2773) -> FileHealthScore {
2774 let fan_in = ctx
2775 .graph
2776 .reverse_deps
2777 .get(node.file_id.0 as usize)
2778 .map_or(0, Vec::len);
2779 let fan_out = node.edge_range.len();
2780
2781 let (total_cyclomatic, total_cognitive, function_count, lines) = ctx
2782 .module_by_id
2783 .get(&node.file_id)
2784 .map_or((0, 0, 0, 0), |module| aggregate_complexity(module));
2785
2786 let value_exports = node.exports.iter().filter(|e| !e.is_type_only).count();
2787 let path_owned = path.to_path_buf();
2788 acc.value_export_counts
2789 .insert(path_owned.clone(), value_exports);
2790 record_unused_file_export_names(
2791 path_owned.as_path(),
2792 &node.exports,
2793 ctx.unused_files,
2794 &mut acc.unused_export_names,
2795 );
2796
2797 let (dead_code_ratio_rounded, complexity_density_rounded, maintainability_index_rounded) =
2798 compute_file_score_metrics(node, &path_owned, ctx, total_cyclomatic, lines, fan_out);
2799
2800 let relative = path_owned.strip_prefix(ctx.root).unwrap_or(&path_owned);
2801 let suppressions = ctx
2802 .module_by_id
2803 .get(&node.file_id)
2804 .map_or(&[][..], |module| module.suppressions.as_slice());
2805 let ceilings = CrapCeilingLookup::new(ctx.crap_thresholds, relative, suppressions);
2806 let crap = compute_file_score_crap(node, ctx, &path_owned, &ceilings);
2807 acc.istanbul_matched += crap.istanbul_matched;
2808 acc.istanbul_total += crap.istanbul_total;
2809 acc.istanbul_files_joined += usize::from(crap.coverage_file_joined);
2810 record_per_function_crap(&mut acc.per_function_crap, &path_owned, crap.per_function);
2811 let mut eligible_functions = crap.signals.eligible_functions;
2812 if !eligible_functions.is_empty() {
2813 eligible_functions.sort_by_key(|function| std::cmp::Reverse(function.2));
2814 eligible_functions.truncate(MAX_FUNCTION_EVIDENCE);
2815 acc.crap_target_fns
2816 .insert(path_owned.clone(), eligible_functions);
2817 }
2818
2819 let global_crap = ctx.crap_thresholds.resolver.global.crap;
2824 let crap_effective_threshold = crap
2825 .signals
2826 .min_ceiling
2827 .filter(|ceiling| (*ceiling - global_crap).abs() > f64::EPSILON);
2828
2829 FileHealthScore {
2830 path: path_owned,
2831 fan_in,
2832 fan_out,
2833 dead_code_ratio: dead_code_ratio_rounded,
2834 complexity_density: complexity_density_rounded,
2835 maintainability_index: maintainability_index_rounded,
2836 total_cyclomatic,
2837 total_cognitive,
2838 function_count,
2839 lines,
2840 crap_max: crap.max,
2841 crap_above_threshold: crap.signals.above,
2842 crap_exempted: crap.signals.exempted,
2843 crap_suppressed: crap.signals.suppressed,
2844 crap_unsuppressed_max: (crap.signals.suppressed > 0)
2845 .then_some(crap.signals.unsuppressed_max),
2846 crap_unsuppressed_effective_threshold: (crap.signals.suppressed > 0)
2847 .then_some(crap.signals.unsuppressed_min_ceiling.unwrap_or(global_crap)),
2848 crap_effective_threshold,
2849 }
2850}
2851
2852fn compute_file_score_metrics(
2855 node: &fallow_graph::graph::ModuleNode,
2856 path: &std::path::Path,
2857 ctx: &FileScoreLoopCtx<'_>,
2858 total_cyclomatic: u32,
2859 lines: u32,
2860 fan_out: usize,
2861) -> (f64, f64, f64) {
2862 let dead_code_ratio = compute_dead_code_ratio(
2863 path,
2864 &node.exports,
2865 ctx.unused_files,
2866 ctx.unused_exports_by_path,
2867 );
2868 let complexity_density = compute_complexity_density(total_cyclomatic, lines);
2869
2870 let dead_code_ratio_rounded = (dead_code_ratio * 100.0).round() / 100.0;
2871 let complexity_density_rounded = (complexity_density * 100.0).round() / 100.0;
2872
2873 let maintainability_index = compute_maintainability_index(
2874 complexity_density_rounded,
2875 dead_code_ratio_rounded,
2876 fan_out,
2877 lines,
2878 );
2879 (
2880 dead_code_ratio_rounded,
2881 complexity_density_rounded,
2882 (maintainability_index * 10.0).round() / 10.0,
2883 )
2884}
2885
2886fn build_file_score_output(parts: FileScoreOutputParts<'_>) -> FileScoreOutput {
2887 let total_exports: usize = parts.graph.modules().iter().map(|m| m.exports.len()).sum();
2888 let unused_deps = parts.results.unused_dependencies.len()
2889 + parts.results.unused_dev_dependencies.len()
2890 + parts.results.unused_optional_dependencies.len();
2891 let analysis_snapshot =
2892 build_analysis_counts_snapshot(parts.graph, parts.file_paths, parts.results, unused_deps);
2893 let analysis_counts =
2894 build_file_score_analysis_counts(parts.results, total_exports, unused_deps);
2895 let template_inherit_provenance =
2896 build_template_inherit_provenance(parts.template_inherit, parts.file_paths);
2897
2898 FileScoreOutput {
2899 scores: parts.scores,
2900 coverage: parts.coverage,
2901 circular_files: parts.circular_files,
2902 top_complex_fns: parts.top_complex_fns,
2903 crap_target_fns: parts.crap_target_fns,
2904 entry_points: parts.entry_points,
2905 value_export_counts: parts.value_export_counts,
2906 unused_export_names: parts.unused_export_names,
2907 cycle_members: parts.cycle_members,
2908 direct_callers: parts.direct_callers,
2909 analysis_counts,
2910 prop_drilling_chains: parts.results.prop_drilling_chains.clone(),
2911 render_fan_in: parts.results.render_fan_in.clone(),
2912 analysis_snapshot,
2913 istanbul_matched: parts.istanbul_matched,
2914 istanbul_total: parts.istanbul_total,
2915 istanbul_files_joined: parts.istanbul_files_joined,
2916 istanbul_files_total: parts.istanbul_files_total,
2917 coverage_input_format: parts.coverage_input_format,
2918 per_function_crap: parts.per_function_crap,
2919 template_inherit_provenance,
2920 static_links: parts
2921 .with_static_links
2922 .then(|| crate::change_coupling::StaticLinkIndex::from_graph(parts.graph)),
2923 shallow_directories: None,
2924 }
2925}
2926
2927fn build_file_score_analysis_counts(
2928 results: &crate::results::AnalysisResults,
2929 total_exports: usize,
2930 unused_deps: usize,
2931) -> crate::vital_signs::AnalysisCounts {
2932 crate::vital_signs::AnalysisCounts {
2933 total_exports,
2934 dead_files: results.unused_files.len(),
2935 dead_exports: results.unused_exports.len() + results.unused_types.len(),
2936 unused_deps,
2937 circular_deps: results.circular_dependencies.len(),
2938 total_deps: 0usize,
2939 }
2940}
2941
2942fn build_template_inherit_provenance(
2943 template_inherit: rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
2944 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
2945) -> rustc_hash::FxHashMap<std::path::PathBuf, std::path::PathBuf> {
2946 template_inherit
2947 .into_iter()
2948 .filter_map(|(file_id, ctx)| {
2949 file_paths
2950 .get(&file_id)
2951 .map(|path| ((**path).clone(), ctx.provenance_owner))
2952 })
2953 .collect()
2954}
2955
2956fn record_entry_point(
2957 entry_points: &mut rustc_hash::FxHashSet<std::path::PathBuf>,
2958 node: &fallow_graph::graph::ModuleNode,
2959 path: &std::path::Path,
2960) {
2961 if node.is_entry_point() {
2962 entry_points.insert(path.to_path_buf());
2963 }
2964}
2965
2966fn record_unused_file_export_names(
2967 path: &std::path::Path,
2968 exports: &[fallow_graph::graph::ExportSymbol],
2969 unused_files: &rustc_hash::FxHashSet<&std::path::Path>,
2970 unused_export_names: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2971) {
2972 if !unused_files.contains(path) || unused_export_names.contains_key(path) {
2973 return;
2974 }
2975
2976 let names: Vec<String> = exports
2977 .iter()
2978 .filter(|export| !export.is_type_only)
2979 .map(|export| export.name.to_string())
2980 .collect();
2981 if !names.is_empty() {
2982 unused_export_names.insert(path.to_path_buf(), names);
2983 }
2984}
2985
2986struct FileScoreCrap {
2987 max: f64,
2988 signals: CrapThresholdSignals,
2989 per_function: Vec<PerFunctionCrap>,
2990 istanbul_matched: usize,
2991 istanbul_total: usize,
2992 coverage_file_joined: bool,
2995}
2996
2997impl FileScoreCrap {
2998 fn empty() -> Self {
2999 Self {
3000 max: 0.0,
3001 signals: CrapThresholdSignals::default(),
3002 per_function: Vec::new(),
3003 istanbul_matched: 0,
3004 istanbul_total: 0,
3005 coverage_file_joined: false,
3006 }
3007 }
3008
3009 fn estimated(result: EstimatedCrapResult) -> Self {
3010 Self {
3011 max: result.max_crap,
3012 signals: result.signals,
3013 per_function: result.per_function,
3014 istanbul_matched: 0,
3015 istanbul_total: 0,
3016 coverage_file_joined: false,
3017 }
3018 }
3019
3020 fn istanbul(result: IstanbulCrapResult, coverage_file_joined: bool) -> Self {
3021 Self {
3022 max: result.max_crap,
3023 signals: result.signals,
3024 per_function: result.per_function,
3025 istanbul_matched: result.matched,
3026 istanbul_total: result.total,
3027 coverage_file_joined,
3028 }
3029 }
3030}
3031
3032fn compute_file_score_crap(
3033 node: &fallow_graph::graph::ModuleNode,
3034 ctx: &FileScoreLoopCtx<'_>,
3035 path: &std::path::Path,
3036 ceilings: &CrapCeilingLookup<'_>,
3037) -> FileScoreCrap {
3038 let Some(module) = ctx.module_by_id.get(&node.file_id).copied() else {
3039 return FileScoreCrap::empty();
3040 };
3041
3042 let is_coverage_suppressed = crate::suppress::is_file_suppressed(
3043 &module.suppressions,
3044 fallow_types::suppress::IssueKind::CoverageGaps,
3045 );
3046 let is_test_reachable = ctx.test_coverage.covers_file(node.file_id) || is_coverage_suppressed;
3047 let resolution = resolve_crap_coverage(
3048 ctx.template_inherit.get(&node.file_id),
3049 ctx.istanbul_coverage,
3050 path,
3051 );
3052 match resolution {
3053 CrapCoverageResolution::TemplateInherited(inherit_ctx) => {
3054 compute_template_inherited_crap(module, inherit_ctx, ceilings)
3055 }
3056 CrapCoverageResolution::Istanbul { file_coverage } => {
3057 compute_istanbul_file_crap(module, file_coverage, is_test_reachable, ceilings)
3058 }
3059 CrapCoverageResolution::StaticEstimated => {
3060 compute_static_file_crap(module, node, ctx.test_coverage, is_test_reachable, ceilings)
3061 }
3062 }
3063}
3064
3065fn compute_template_inherited_crap(
3066 module: &crate::source::ModuleInfo,
3067 inherit_ctx: &TemplateInheritContext,
3068 ceilings: &CrapCeilingLookup<'_>,
3069) -> FileScoreCrap {
3070 FileScoreCrap::estimated(compute_crap_scores_estimated(
3071 &module.complexity,
3072 &inherit_ctx.test_referenced_exports,
3073 inherit_ctx.is_test_reachable,
3074 fallow_output::CoverageSource::EstimatedComponentInherited,
3075 ceilings,
3076 ))
3077}
3078
3079fn compute_istanbul_file_crap(
3080 module: &crate::source::ModuleInfo,
3081 file_coverage: Option<&IstanbulFileCoverage>,
3082 is_test_reachable: bool,
3083 ceilings: &CrapCeilingLookup<'_>,
3084) -> FileScoreCrap {
3085 FileScoreCrap::istanbul(
3086 compute_crap_scores_istanbul(
3087 &module.complexity,
3088 file_coverage,
3089 is_test_reachable,
3090 ceilings,
3091 ),
3092 file_coverage.is_some(),
3093 )
3094}
3095
3096fn compute_static_file_crap(
3097 module: &crate::source::ModuleInfo,
3098 node: &fallow_graph::graph::ModuleNode,
3099 test_coverage: StaticTestCoverage<'_>,
3100 is_test_reachable: bool,
3101 ceilings: &CrapCeilingLookup<'_>,
3102) -> FileScoreCrap {
3103 let test_refs = build_test_referenced_exports(node.file_id, &node.exports, test_coverage);
3104 FileScoreCrap::estimated(compute_crap_scores_estimated(
3105 &module.complexity,
3106 &test_refs,
3107 is_test_reachable,
3108 fallow_output::CoverageSource::Estimated,
3109 ceilings,
3110 ))
3111}
3112
3113fn record_per_function_crap(
3114 per_function_crap: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
3115 path: &std::path::Path,
3116 per_function: Vec<PerFunctionCrap>,
3117) {
3118 if !per_function.is_empty() {
3119 per_function_crap.insert(path.to_path_buf(), per_function);
3120 }
3121}
3122
3123struct FileScoreCoverageSetup<'a> {
3124 module_by_id: rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
3125 coverage: CoverageGapData,
3126}
3127
3128fn prepare_file_score_coverage_setup<'a>(
3129 modules: &'a [crate::source::ModuleInfo],
3130 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3131 results: &crate::results::AnalysisResults,
3132 graph: &fallow_graph::graph::ModuleGraph,
3133 test_coverage: StaticTestCoverage<'_>,
3134 root: &std::path::Path,
3135) -> FileScoreCoverageSetup<'a> {
3136 let module_by_id: rustc_hash::FxHashMap<_, _> =
3137 modules.iter().map(|m| (m.file_id, m)).collect();
3138 let unused_exports: rustc_hash::FxHashSet<(&std::path::Path, String)> = results
3139 .unused_exports
3140 .iter()
3141 .map(|export| {
3142 (
3143 export.export.path.as_path(),
3144 export.export.export_name.clone(),
3145 )
3146 })
3147 .collect();
3148 let coverage = compute_coverage_gaps(
3149 graph,
3150 test_coverage,
3151 file_paths,
3152 &module_by_id,
3153 &unused_exports,
3154 root,
3155 );
3156 FileScoreCoverageSetup {
3157 module_by_id,
3158 coverage,
3159 }
3160}
3161
3162fn collect_top_complex_fns(
3163 modules: &[crate::source::ModuleInfo],
3164 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3165) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>> {
3166 let mut top_complex_fns = rustc_hash::FxHashMap::default();
3167 for module in modules {
3168 if module.complexity.is_empty() {
3169 continue;
3170 }
3171 let Some(path) = file_paths.get(&module.file_id) else {
3172 continue;
3173 };
3174 let mut funcs: Vec<(String, u32, u16)> = module
3179 .complexity
3180 .iter()
3181 .filter(|f| !fallow_types::extract::is_synthetic_module_unit(&f.name))
3182 .map(|f| (f.name.clone(), f.line, f.cognitive))
3183 .collect();
3184 funcs.sort_by_key(|f| std::cmp::Reverse(f.2));
3185 funcs.truncate(MAX_FUNCTION_EVIDENCE);
3186 if funcs.first().is_some_and(|worst| worst.2 > 0) {
3187 top_complex_fns.insert((*path).clone(), funcs);
3188 }
3189 }
3190 top_complex_fns
3191}
3192
3193fn collect_unused_export_names(
3194 results: &crate::results::AnalysisResults,
3195) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> {
3196 let mut unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> =
3197 rustc_hash::FxHashMap::default();
3198 for exp in &results.unused_exports {
3199 unused_export_names
3200 .entry(exp.export.path.clone())
3201 .or_default()
3202 .push(exp.export.export_name.clone());
3203 }
3204 unused_export_names
3205}
3206
3207fn build_analysis_counts_snapshot(
3208 graph: &fallow_graph::graph::ModuleGraph,
3209 file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3210 results: &crate::results::AnalysisResults,
3211 unused_deps: usize,
3212) -> AnalysisCountsSnapshot {
3213 let mut module_export_counts = rustc_hash::FxHashMap::with_capacity_and_hasher(
3214 graph.module_count(),
3215 rustc_hash::FxBuildHasher,
3216 );
3217 for module in graph.modules() {
3218 if let Some(path) = file_paths.get(&module.file_id) {
3219 module_export_counts.insert((*path).clone(), module.exports.len());
3220 }
3221 }
3222
3223 let mut unused_export_paths =
3224 Vec::with_capacity(results.unused_exports.len() + results.unused_types.len());
3225 unused_export_paths.extend(results.unused_exports.iter().map(|e| e.export.path.clone()));
3226 unused_export_paths.extend(results.unused_types.iter().map(|e| e.export.path.clone()));
3227
3228 let mut unused_dep_package_paths = Vec::with_capacity(unused_deps);
3229 unused_dep_package_paths.extend(
3230 results
3231 .unused_dependencies
3232 .iter()
3233 .map(|d| d.dep.path.clone()),
3234 );
3235 unused_dep_package_paths.extend(
3236 results
3237 .unused_dev_dependencies
3238 .iter()
3239 .map(|d| d.dep.path.clone()),
3240 );
3241 unused_dep_package_paths.extend(
3242 results
3243 .unused_optional_dependencies
3244 .iter()
3245 .map(|d| d.dep.path.clone()),
3246 );
3247
3248 AnalysisCountsSnapshot {
3249 unused_file_paths: results
3250 .unused_files
3251 .iter()
3252 .map(|f| f.file.path.clone())
3253 .collect(),
3254 unused_export_paths,
3255 unused_dep_package_paths,
3256 circular_dep_groups: results
3257 .circular_dependencies
3258 .iter()
3259 .map(|c| c.cycle.files.clone())
3260 .collect(),
3261 module_export_counts,
3262 }
3263}
3264
3265#[cfg(test)]
3266#[path = "scoring_private_member_tests.rs"]
3267mod private_member_tests;
3268
3269#[cfg(test)]
3270#[path = "scoring_tests.rs"]
3271mod tests;