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    filter_source_findings(results, &touches_file, &line_in_diff);
42    filter_security_findings(results, &touches_file, &line_in_diff);
43    filter_dependency_findings(results, &line_in_diff);
44    filter_graph_findings(results, &touches_file, &line_in_diff);
45    filter_framework_findings(results, &line_in_diff);
46    results.prop_drilling_chains.retain(|finding| {
47        finding.effective_severity != Some(fallow_types::output_dead_code::EffectiveSeverity::Error)
48            || finding.chain.hops.is_empty()
49            || finding
50                .chain
51                .hops
52                .iter()
53                .any(|hop| line_in_diff(&hop.file, hop.line))
54    });
55}
56
57/// Keep only the clone groups with at least one instance whose line range
58/// overlaps an added line of the diff.
59///
60/// The filter keeps the whole group when one instance overlaps, so a reviewer
61/// sees the full clone family in the context of the change. Clone families,
62/// statistics and the order are rebuilt from the groups that stay, so the
63/// duplication percentage describes the scoped slice.
64pub fn filter_duplication_by_diff(report: &mut DuplicationReport, diff: &DiffIndex, root: &Path) {
65    let instance_overlaps = |instance: &CloneInstance| -> bool {
66        let Some(rel) = diff.key_for(&instance.file, root) else {
67            return true;
68        };
69        let start = u64::try_from(instance.start_line).unwrap_or(u64::MAX);
70        let end = u64::try_from(instance.end_line).unwrap_or(u64::MAX);
71        diff.range_overlaps_added(&rel, start, end)
72    };
73    report
74        .clone_groups
75        .retain(|group| group.instances.iter().any(instance_overlaps));
76    crate::duplicates::refresh_scoped_report(report, root);
77}
78
79fn filter_source_findings(
80    results: &mut AnalysisResults,
81    touches_file: &dyn Fn(&Path) -> bool,
82    line_in_diff: &dyn Fn(&Path, u32) -> bool,
83) {
84    results
85        .unused_files
86        .retain(|finding| touches_file(&finding.file.path));
87    results
88        .unused_exports
89        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
90    results
91        .unused_types
92        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
93    results
94        .private_type_leaks
95        .retain(|finding| line_in_diff(&finding.leak.path, finding.leak.line));
96    results
97        .deprecated_exports_in_use
98        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
99    results
100        .unused_enum_members
101        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
102    results
103        .unused_class_members
104        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
105    results
106        .unused_store_members
107        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
108    results
109        .unused_namespace_members
110        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
111    results
112        .unprovided_injects
113        .retain(|finding| line_in_diff(&finding.inject.path, finding.inject.line));
114    results
115        .unrendered_components
116        .retain(|finding| line_in_diff(&finding.component.path, finding.component.line));
117    results
118        .unused_component_props
119        .retain(|finding| line_in_diff(&finding.prop.path, finding.prop.line));
120    results
121        .absent_component_props
122        .retain(|finding| line_in_diff(&finding.prop.path, finding.prop.line));
123    results
124        .unused_component_emits
125        .retain(|finding| line_in_diff(&finding.emit.path, finding.emit.line));
126    results
127        .unused_component_inputs
128        .retain(|finding| line_in_diff(&finding.input.path, finding.input.line));
129    results
130        .unused_component_outputs
131        .retain(|finding| line_in_diff(&finding.output.path, finding.output.line));
132    results
133        .unused_svelte_events
134        .retain(|finding| line_in_diff(&finding.event.path, finding.event.line));
135    results
136        .unused_effect_layers
137        .retain(|finding| line_in_diff(&finding.layer.path, finding.layer.line));
138    results.duplicate_export_aliases.retain(|finding| {
139        finding
140            .alias
141            .locations
142            .iter()
143            .any(|location| line_in_diff(&finding.alias.path, location.line))
144    });
145    results
146        .unused_tagged_errors
147        .retain(|finding| line_in_diff(&finding.error.path, finding.error.line));
148    results
149        .unproduced_catch_tags
150        .retain(|finding| line_in_diff(&finding.catch_tag.path, finding.catch_tag.line));
151    results
152        .unused_server_actions
153        .retain(|finding| line_in_diff(&finding.action.path, finding.action.line));
154    results
155        .unused_load_data_keys
156        .retain(|finding| line_in_diff(&finding.key.path, finding.key.line));
157    results
158        .unresolved_imports
159        .retain(|finding| line_in_diff(&finding.import.path, finding.import.line));
160}
161
162fn filter_security_findings(
163    results: &mut AnalysisResults,
164    touches_file: &dyn Fn(&Path) -> bool,
165    line_in_diff: &dyn Fn(&Path, u32) -> bool,
166) {
167    results.security_findings.retain(|finding| {
168        line_in_diff(&finding.path, finding.line)
169            || finding.trace.iter().any(|hop| {
170                line_in_diff(&hop.path, hop.line)
171                    || (matches!(hop.role, TraceHopRole::SecretSource) && touches_file(&hop.path))
172            })
173            || finding.reachability.as_ref().is_some_and(|reachability| {
174                // Any hop on an added line keeps the finding for display, whatever
175                // its role. Do not add a role check here: unlike the strict
176                // `--gate new` filter of `fallow security`, the display must show a
177                // finding whose module-level source sits on an added line.
178                reachability
179                    .untrusted_source_trace
180                    .iter()
181                    .any(|hop| line_in_diff(&hop.path, hop.line))
182            })
183    });
184    results
185        .security_unresolved_callee_diagnostics
186        .retain(|finding| line_in_diff(&finding.path, finding.line));
187}
188
189fn filter_dependency_findings(
190    results: &mut AnalysisResults,
191    line_in_diff: &dyn Fn(&Path, u32) -> bool,
192) {
193    for finding in &mut results.unlisted_dependencies {
194        finding
195            .dep
196            .imported_from
197            .retain(|source| line_in_diff(&source.path, source.line));
198    }
199    results
200        .unlisted_dependencies
201        .retain(|finding| !finding.dep.imported_from.is_empty());
202    for finding in &mut results.unlisted_binaries {
203        finding
204            .binary
205            .used_in
206            .retain(|site| line_in_diff(&site.path, site.line));
207    }
208    results
209        .unlisted_binaries
210        .retain(|finding| !finding.binary.used_in.is_empty());
211}
212
213fn filter_graph_findings(
214    results: &mut AnalysisResults,
215    touches_file: &dyn Fn(&Path) -> bool,
216    line_in_diff: &dyn Fn(&Path, u32) -> bool,
217) {
218    results.duplicate_exports.retain(|finding| {
219        finding
220            .export
221            .locations
222            .iter()
223            .any(|location| line_in_diff(&location.path, location.line))
224    });
225    results
226        .circular_dependencies
227        .retain(|cycle| cycle.cycle.files.iter().any(|path| touches_file(path)));
228    results
229        .re_export_cycles
230        .retain(|cycle| cycle.cycle.files.iter().any(|path| touches_file(path)));
231    results.package_cycles.retain(|cycle| {
232        cycle
233            .cycle
234            .edges
235            .iter()
236            .any(|edge| touches_file(&edge.path))
237    });
238    results
239        .boundary_violations
240        .retain(|finding| line_in_diff(&finding.violation.from_path, finding.violation.line));
241    results
242        .stale_suppressions
243        .retain(|finding| line_in_diff(&finding.path, finding.line));
244}
245
246fn filter_framework_findings(
247    results: &mut AnalysisResults,
248    line_in_diff: &dyn Fn(&Path, u32) -> bool,
249) {
250    results
251        .invalid_client_exports
252        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
253    results
254        .mixed_client_server_barrels
255        .retain(|finding| line_in_diff(&finding.barrel.path, finding.barrel.line));
256    results
257        .misplaced_directives
258        .retain(|finding| line_in_diff(&finding.directive_site.path, finding.directive_site.line));
259    results
260        .route_collisions
261        .retain(|finding| line_in_diff(&finding.collision.path, finding.collision.line));
262    results
263        .dynamic_segment_name_conflicts
264        .retain(|finding| line_in_diff(&finding.conflict.path, finding.conflict.line));
265}