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    crate::duplicates::refresh_scoped_report(report, root);
80}
81
82fn filter_source_findings(
83    results: &mut AnalysisResults,
84    touches_file: &dyn Fn(&Path) -> bool,
85    line_in_diff: &dyn Fn(&Path, u32) -> bool,
86) {
87    results
88        .unused_files
89        .retain(|finding| touches_file(&finding.file.path));
90    results
91        .unused_exports
92        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
93    results
94        .unused_types
95        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
96    results
97        .private_type_leaks
98        .retain(|finding| line_in_diff(&finding.leak.path, finding.leak.line));
99    results
100        .deprecated_exports_in_use
101        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
102    results
103        .unused_enum_members
104        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
105    results
106        .unused_class_members
107        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
108    results
109        .unused_store_members
110        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
111    results
112        .unused_namespace_members
113        .retain(|finding| line_in_diff(&finding.member.path, finding.member.line));
114    results
115        .unprovided_injects
116        .retain(|finding| line_in_diff(&finding.inject.path, finding.inject.line));
117    results
118        .unrendered_components
119        .retain(|finding| line_in_diff(&finding.component.path, finding.component.line));
120    results
121        .unused_component_props
122        .retain(|finding| line_in_diff(&finding.prop.path, finding.prop.line));
123    results
124        .absent_component_props
125        .retain(|finding| line_in_diff(&finding.prop.path, finding.prop.line));
126    results
127        .constant_parameters
128        .retain(|finding| line_in_diff(&finding.parameter.path, finding.parameter.line));
129    results
130        .unused_component_emits
131        .retain(|finding| line_in_diff(&finding.emit.path, finding.emit.line));
132    results
133        .unused_component_inputs
134        .retain(|finding| line_in_diff(&finding.input.path, finding.input.line));
135    results
136        .unused_component_outputs
137        .retain(|finding| line_in_diff(&finding.output.path, finding.output.line));
138    results
139        .unused_svelte_events
140        .retain(|finding| line_in_diff(&finding.event.path, finding.event.line));
141    results
142        .unused_effect_layers
143        .retain(|finding| line_in_diff(&finding.layer.path, finding.layer.line));
144    results.duplicate_export_aliases.retain(|finding| {
145        finding
146            .alias
147            .locations
148            .iter()
149            .any(|location| line_in_diff(&finding.alias.path, location.line))
150    });
151    results
152        .unused_tagged_errors
153        .retain(|finding| line_in_diff(&finding.error.path, finding.error.line));
154    results
155        .unproduced_catch_tags
156        .retain(|finding| line_in_diff(&finding.catch_tag.path, finding.catch_tag.line));
157    results
158        .unused_server_actions
159        .retain(|finding| line_in_diff(&finding.action.path, finding.action.line));
160    results
161        .unused_load_data_keys
162        .retain(|finding| line_in_diff(&finding.key.path, finding.key.line));
163    results
164        .unresolved_imports
165        .retain(|finding| line_in_diff(&finding.import.path, finding.import.line));
166}
167
168fn filter_security_findings(
169    results: &mut AnalysisResults,
170    touches_file: &dyn Fn(&Path) -> bool,
171    line_in_diff: &dyn Fn(&Path, u32) -> bool,
172) {
173    results.security_findings.retain(|finding| {
174        line_in_diff(&finding.path, finding.line)
175            || finding.trace.iter().any(|hop| {
176                line_in_diff(&hop.path, hop.line)
177                    || (matches!(hop.role, TraceHopRole::SecretSource) && touches_file(&hop.path))
178            })
179            || finding.reachability.as_ref().is_some_and(|reachability| {
180                // Any hop on an added line keeps the finding for display, whatever
181                // its role. Do not add a role check here: unlike the strict
182                // `--gate new` filter of `fallow security`, the display must show a
183                // finding whose module-level source sits on an added line.
184                reachability
185                    .untrusted_source_trace
186                    .iter()
187                    .any(|hop| line_in_diff(&hop.path, hop.line))
188            })
189    });
190    results
191        .security_unresolved_callee_diagnostics
192        .retain(|finding| line_in_diff(&finding.path, finding.line));
193}
194
195fn filter_dependency_findings(
196    results: &mut AnalysisResults,
197    line_in_diff: &dyn Fn(&Path, u32) -> bool,
198) {
199    for finding in &mut results.unlisted_dependencies {
200        finding
201            .dep
202            .imported_from
203            .retain(|source| line_in_diff(&source.path, source.line));
204    }
205    results
206        .unlisted_dependencies
207        .retain(|finding| !finding.dep.imported_from.is_empty());
208    for finding in &mut results.unlisted_binaries {
209        finding
210            .binary
211            .used_in
212            .retain(|site| line_in_diff(&site.path, site.line));
213    }
214    results
215        .unlisted_binaries
216        .retain(|finding| !finding.binary.used_in.is_empty());
217}
218
219fn filter_graph_findings(
220    results: &mut AnalysisResults,
221    touches_file: &dyn Fn(&Path) -> bool,
222    line_in_diff: &dyn Fn(&Path, u32) -> bool,
223) {
224    results.duplicate_exports.retain(|finding| {
225        finding
226            .export
227            .locations
228            .iter()
229            .any(|location| line_in_diff(&location.path, location.line))
230    });
231    results
232        .circular_dependencies
233        .retain(|cycle| cycle.cycle.files.iter().any(|path| touches_file(path)));
234    results
235        .re_export_cycles
236        .retain(|cycle| cycle.cycle.files.iter().any(|path| touches_file(path)));
237    results.package_cycles.retain(|cycle| {
238        cycle
239            .cycle
240            .edges
241            .iter()
242            .any(|edge| touches_file(&edge.path))
243    });
244    results
245        .boundary_violations
246        .retain(|finding| line_in_diff(&finding.violation.from_path, finding.violation.line));
247    results
248        .stale_suppressions
249        .retain(|finding| line_in_diff(&finding.path, finding.line));
250}
251
252fn filter_framework_findings(
253    results: &mut AnalysisResults,
254    line_in_diff: &dyn Fn(&Path, u32) -> bool,
255) {
256    results
257        .invalid_client_exports
258        .retain(|finding| line_in_diff(&finding.export.path, finding.export.line));
259    results
260        .mixed_client_server_barrels
261        .retain(|finding| line_in_diff(&finding.barrel.path, finding.barrel.line));
262    results
263        .misplaced_directives
264        .retain(|finding| line_in_diff(&finding.directive_site.path, finding.directive_site.line));
265    results
266        .route_collisions
267        .retain(|finding| line_in_diff(&finding.collision.path, finding.collision.line));
268    results
269        .dynamic_segment_name_conflicts
270        .retain(|finding| line_in_diff(&finding.conflict.path, finding.conflict.line));
271}