Skip to main content

fallow_engine/
diff_scope.rs

1//! Diff line filters shared by every surface that accepts a unified diff.
2//!
3//! The CLI (`--diff-file`, `--diff-stdin` and the CI diff) and the programmatic
4//! API (`analysis.diffFile`) narrow a report to the lines a change added. Both
5//! call the functions in this module, so a finding cannot pass the filter on
6//! one surface and fail it on another.
7
8use std::path::Path;
9
10use fallow_output::DiffIndex;
11use fallow_types::duplicates::{CloneInstance, DuplicationReport};
12use fallow_types::results::{AnalysisResults, TraceHopRole};
13
14/// Drop the dead-code findings whose source line is not on an added line of
15/// the diff.
16///
17/// Range-shaped findings (clone instances, complexity hotspots) have their own
18/// filters. This filter governs the per-file findings on [`AnalysisResults`].
19///
20/// **Project-level findings bypass the filter.** A change that deletes the
21/// last consumer of a package causes the `unused-dependency` finding, even
22/// when the diff does not touch `package.json`. The same holds for catalog
23/// entries, dependency overrides, type-only dependencies and test-only
24/// dependencies. The line filter reduces noise for source-anchored findings.
25/// CI must still fail on the project-level findings that the change caused.
26///
27/// [`DiffIndex::key_for`] gives the diff key of a finding path, relative to the
28/// base of the diff and not to `root`. When a path has no key (a different
29/// drive, or a path outside the base), the finding stays: a path that the
30/// filter cannot judge is better shown than hidden.
31pub fn filter_dead_code_by_diff(results: &mut AnalysisResults, diff: &DiffIndex, root: &Path) {
32    let touches_file = |path: &Path| -> bool {
33        diff.key_for(path, root)
34            .is_none_or(|rel| diff.touches_file(&rel))
35    };
36    let line_in_diff = |path: &Path, line: u32| -> bool {
37        diff.key_for(path, root)
38            .is_none_or(|rel| diff.line_is_added(&rel, u64::from(line)))
39    };
40
41    if let Some(inventory) = &mut results.shared_state {
42        inventory.retain_sites(|site| line_in_diff(&site.path, site.line as u32));
43    }
44    filter_source_findings(results, &touches_file, &line_in_diff);
45    filter_security_findings(results, &touches_file, &line_in_diff);
46    filter_dependency_findings(results, &line_in_diff);
47    filter_graph_findings(results, &touches_file, &line_in_diff);
48    filter_framework_findings(results, &line_in_diff);
49    results.prop_drilling_chains.retain(|finding| {
50        finding.effective_severity != Some(fallow_types::output_dead_code::EffectiveSeverity::Error)
51            || finding.chain.hops.is_empty()
52            || finding
53                .chain
54                .hops
55                .iter()
56                .any(|hop| line_in_diff(&hop.file, hop.line))
57    });
58}
59
60/// Keep only the clone groups with at least one instance whose line range
61/// overlaps an added line of the diff.
62///
63/// The filter keeps the whole group when one instance overlaps, so a reviewer
64/// sees the full clone family in the context of the change. Clone families,
65/// statistics and the order are rebuilt from the groups that stay, so the
66/// duplication percentage describes the scoped slice.
67pub fn filter_duplication_by_diff(report: &mut DuplicationReport, diff: &DiffIndex, root: &Path) {
68    let instance_overlaps = |instance: &CloneInstance| -> bool {
69        let Some(rel) = diff.key_for(&instance.file, root) else {
70            return true;
71        };
72        let start = u64::try_from(instance.start_line).unwrap_or(u64::MAX);
73        let end = u64::try_from(instance.end_line).unwrap_or(u64::MAX);
74        diff.range_overlaps_added(&rel, start, end)
75    };
76    report
77        .clone_groups
78        .retain(|group| group.instances.iter().any(instance_overlaps));
79    report.range_marker_problems.retain(|finding| {
80        diff.key_for(&finding.path, root).is_none_or(|rel| {
81            diff.range_overlaps_added(
82                &rel,
83                u64::from(finding.problem.line),
84                u64::from(finding.problem.line),
85            )
86        })
87    });
88    crate::duplicates::refresh_scoped_report(report, root);
89}
90
91fn filter_source_findings(
92    results: &mut AnalysisResults,
93    touches_file: &dyn Fn(&Path) -> bool,
94    line_in_diff: &dyn Fn(&Path, u32) -> bool,
95) {
96    results
97        .unused_files
98        .retain(|finding| touches_file(&finding.file.path));
99    results
100        .unused_exports
101        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
102    results
103        .unused_types
104        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
105    results
106        .private_type_leaks
107        .retain(|finding| line_in_diff(&finding.leak.path, finding.leak.line));
108    results
109        .deprecated_exports_in_use
110        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
111    results
112        .unused_enum_members
113        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
114    results
115        .unused_class_members
116        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
117    results
118        .unused_store_members
119        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
120    results
121        .unused_namespace_members
122        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
123    results
124        .unused_protected_class_members
125        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
126    results
127        .unprovided_injects
128        .retain(|finding| line_in_diff(&finding.inject.path, finding.inject.line));
129    results
130        .unrendered_components
131        .retain(|finding| line_in_diff(&finding.component.path, finding.component.line));
132    results
133        .unused_component_props
134        .retain(|finding| line_in_diff(&finding.prop.path, finding.prop.line));
135    results
136        .absent_component_props
137        .retain(|finding| line_in_diff(&finding.prop.path, finding.prop.line));
138    results
139        .constant_parameters
140        .retain(|finding| line_in_diff(&finding.parameter.path, finding.parameter.line));
141    results
142        .unused_component_emits
143        .retain(|finding| line_in_diff(&finding.emit.path, finding.emit.line));
144    results
145        .unused_component_inputs
146        .retain(|finding| line_in_diff(&finding.input.path, finding.input.line));
147    results
148        .unused_component_outputs
149        .retain(|finding| line_in_diff(&finding.output.path, finding.output.line));
150    results
151        .unused_svelte_events
152        .retain(|finding| line_in_diff(&finding.event.path, finding.event.line));
153    results
154        .unused_effect_layers
155        .retain(|finding| line_in_diff(&finding.layer.path, finding.layer.line));
156    results.duplicate_export_aliases.retain(|finding| {
157        finding
158            .alias
159            .locations
160            .iter()
161            .any(|location| line_in_diff(&finding.alias.path, location.line))
162    });
163    results
164        .unused_tagged_errors
165        .retain(|finding| line_in_diff(&finding.error.path, finding.error.line));
166    results
167        .unproduced_catch_tags
168        .retain(|finding| line_in_diff(&finding.catch_tag.path, finding.catch_tag.line));
169    results
170        .unused_server_actions
171        .retain(|finding| line_in_diff(&finding.action.path, finding.action.line));
172    results
173        .unused_load_data_keys
174        .retain(|finding| line_in_diff(&finding.key.path, finding.key.line));
175    results
176        .unresolved_imports
177        .retain(|finding| line_in_diff(&finding.import.path, finding.import.line));
178}
179
180fn filter_security_findings(
181    results: &mut AnalysisResults,
182    touches_file: &dyn Fn(&Path) -> bool,
183    line_in_diff: &dyn Fn(&Path, u32) -> bool,
184) {
185    results.security_findings.retain(|finding| {
186        line_in_diff(&finding.path, finding.line)
187            || finding.trace.iter().any(|hop| {
188                line_in_diff(&hop.path, hop.line)
189                    || (matches!(hop.role, TraceHopRole::SecretSource) && touches_file(&hop.path))
190            })
191            || finding.reachability.as_ref().is_some_and(|reachability| {
192                // Any hop on an added line keeps the finding for display, whatever
193                // its role. Do not add a role check here: unlike the strict
194                // `--gate new` filter of `fallow security`, the display must show a
195                // finding whose module-level source sits on an added line.
196                reachability
197                    .untrusted_source_trace
198                    .iter()
199                    .any(|hop| line_in_diff(&hop.path, hop.line))
200            })
201    });
202    results
203        .security_unresolved_callee_diagnostics
204        .retain(|finding| line_in_diff(&finding.path, finding.line));
205}
206
207fn filter_dependency_findings(
208    results: &mut AnalysisResults,
209    line_in_diff: &dyn Fn(&Path, u32) -> bool,
210) {
211    for finding in &mut results.unlisted_dependencies {
212        finding
213            .dep
214            .imported_from
215            .retain(|source| line_in_diff(&source.path, source.line));
216    }
217    results
218        .unlisted_dependencies
219        .retain(|finding| !finding.dep.imported_from.is_empty());
220    for finding in &mut results.unlisted_binaries {
221        finding
222            .binary
223            .used_in
224            .retain(|site| line_in_diff(&site.path, site.line));
225    }
226    results
227        .unlisted_binaries
228        .retain(|finding| !finding.binary.used_in.is_empty());
229}
230
231fn filter_graph_findings(
232    results: &mut AnalysisResults,
233    touches_file: &dyn Fn(&Path) -> bool,
234    line_in_diff: &dyn Fn(&Path, u32) -> bool,
235) {
236    results.duplicate_exports.retain(|finding| {
237        finding
238            .export
239            .locations
240            .iter()
241            .any(|location| line_in_diff(&location.path, location.line))
242    });
243    results
244        .circular_dependencies
245        .retain(|cycle| cycle.cycle.files.iter().any(|path| touches_file(path)));
246    results
247        .re_export_cycles
248        .retain(|cycle| cycle.cycle.files.iter().any(|path| touches_file(path)));
249    results.package_cycles.retain(|cycle| {
250        cycle
251            .cycle
252            .edges
253            .iter()
254            .any(|edge| touches_file(&edge.path))
255    });
256    results
257        .boundary_violations
258        .retain(|finding| line_in_diff(&finding.violation.from_path, finding.violation.line));
259    results
260        .stale_suppressions
261        .retain(|finding| line_in_diff(&finding.path, finding.line));
262}
263
264fn filter_framework_findings(
265    results: &mut AnalysisResults,
266    line_in_diff: &dyn Fn(&Path, u32) -> bool,
267) {
268    results
269        .invalid_client_exports
270        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
271    results
272        .mixed_client_server_barrels
273        .retain(|finding| line_in_diff(&finding.barrel.path, finding.barrel.line));
274    results
275        .misplaced_directives
276        .retain(|finding| line_in_diff(&finding.directive_site.path, finding.directive_site.line));
277    results
278        .route_collisions
279        .retain(|finding| line_in_diff(&finding.collision.path, finding.collision.line));
280    results
281        .dynamic_segment_name_conflicts
282        .retain(|finding| line_in_diff(&finding.conflict.path, finding.conflict.line));
283}