Skip to main content

fallow_engine/
cross_reference.rs

1//! Cross-reference helpers exposed through the engine boundary.
2
3use std::path::PathBuf;
4
5use rustc_hash::FxHashSet;
6use serde::Serialize;
7
8use crate::duplicates::{CloneInstance, DuplicationReport};
9use crate::results::AnalysisResults;
10
11/// A combined finding where a clone instance overlaps with a dead-code issue.
12#[derive(Debug, Clone, Serialize)]
13pub struct CombinedFinding {
14    /// The clone instance that is also unused.
15    pub clone_instance: CloneInstance,
16    /// What kind of dead code overlaps with this clone.
17    pub dead_code_kind: DeadCodeKind,
18    /// Clone group index for associating with the parent group.
19    pub group_index: usize,
20}
21
22/// The type of dead code that overlaps with a clone instance.
23#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
24pub enum DeadCodeKind {
25    /// The entire file containing the clone is unused.
26    UnusedFile,
27    /// A specific unused export overlaps with the clone's line range.
28    UnusedExport {
29        /// Name of the overlapping unused export.
30        export_name: String,
31    },
32    /// A specific unused type overlaps with the clone's line range.
33    UnusedType {
34        /// Name of the overlapping unused type.
35        type_name: String,
36    },
37}
38
39/// Result of cross-referencing duplication with dead-code analysis.
40#[derive(Debug, Clone, Serialize)]
41pub struct CrossReferenceResult {
42    /// Clone instances that are also dead code.
43    pub combined_findings: Vec<CombinedFinding>,
44    /// Number of clone instances in unused files.
45    pub clones_in_unused_files: usize,
46    /// Number of clone instances overlapping unused exports.
47    pub clones_with_unused_exports: usize,
48}
49
50impl CrossReferenceResult {
51    /// Total number of combined findings.
52    #[must_use]
53    pub const fn total(&self) -> usize {
54        self.combined_findings.len()
55    }
56
57    /// Whether any combined findings exist.
58    #[must_use]
59    pub const fn has_findings(&self) -> bool {
60        !self.combined_findings.is_empty()
61    }
62
63    /// Get clone groups that have at least one combined finding.
64    #[cfg(test)]
65    fn affected_group_indices(&self) -> FxHashSet<usize> {
66        self.combined_findings
67            .iter()
68            .map(|finding| finding.group_index)
69            .collect()
70    }
71}
72
73/// Cross-reference duplication findings with dead-code analysis results.
74#[must_use]
75pub fn cross_reference(
76    duplication: &DuplicationReport,
77    dead_code: &AnalysisResults,
78) -> CrossReferenceResult {
79    let unused_files: FxHashSet<&PathBuf> = dead_code
80        .unused_files
81        .iter()
82        .map(|finding| &finding.file.path)
83        .collect();
84
85    let mut combined_findings = Vec::new();
86    let mut clones_in_unused_files = 0usize;
87    let mut clones_with_unused_exports = 0usize;
88
89    for (group_index, group) in duplication.clone_groups.iter().enumerate() {
90        for instance in &group.instances {
91            if unused_files.contains(&instance.file) {
92                combined_findings.push(CombinedFinding {
93                    clone_instance: instance.clone(),
94                    dead_code_kind: DeadCodeKind::UnusedFile,
95                    group_index,
96                });
97                clones_in_unused_files += 1;
98                continue;
99            }
100
101            if let Some(finding) = find_overlapping_unused_export(instance, group_index, dead_code)
102            {
103                clones_with_unused_exports += 1;
104                combined_findings.push(finding);
105            }
106        }
107    }
108
109    CrossReferenceResult {
110        combined_findings,
111        clones_in_unused_files,
112        clones_with_unused_exports,
113    }
114}
115
116fn find_overlapping_unused_export(
117    instance: &CloneInstance,
118    group_index: usize,
119    dead_code: &AnalysisResults,
120) -> Option<CombinedFinding> {
121    for export in &dead_code.unused_exports {
122        if export.export.path == instance.file
123            && (export.export.line as usize) >= instance.start_line
124            && (export.export.line as usize) <= instance.end_line
125        {
126            return Some(CombinedFinding {
127                clone_instance: instance.clone(),
128                dead_code_kind: DeadCodeKind::UnusedExport {
129                    export_name: export.export.export_name.clone(),
130                },
131                group_index,
132            });
133        }
134    }
135
136    for type_export in &dead_code.unused_types {
137        if type_export.export.path == instance.file
138            && (type_export.export.line as usize) >= instance.start_line
139            && (type_export.export.line as usize) <= instance.end_line
140        {
141            return Some(CombinedFinding {
142                clone_instance: instance.clone(),
143                dead_code_kind: DeadCodeKind::UnusedType {
144                    type_name: type_export.export.export_name.clone(),
145                },
146                group_index,
147            });
148        }
149    }
150
151    None
152}
153
154#[cfg(test)]
155mod tests {
156    use std::path::PathBuf;
157
158    use super::*;
159    use crate::duplicates::{CloneGroup, DuplicationStats};
160    use fallow_types::{
161        output_dead_code::{UnusedExportFinding, UnusedFileFinding, UnusedTypeFinding},
162        results::{UnusedExport, UnusedFile},
163    };
164
165    fn clone_instance(file: &str, start_line: usize, end_line: usize) -> CloneInstance {
166        CloneInstance {
167            is_symlink: false,
168            file: PathBuf::from(file),
169            start_line,
170            end_line,
171            start_col: 0,
172            end_col: 0,
173            fragment: String::new(),
174        }
175    }
176
177    fn duplicate_report(instances: Vec<CloneInstance>) -> DuplicationReport {
178        DuplicationReport {
179            clone_groups: vec![CloneGroup {
180                instances,
181                token_count: 50,
182                line_count: 10,
183                similarity: None,
184            }],
185            clone_families: Vec::new(),
186            mirrored_directories: Vec::new(),
187            range_marker_problems: Vec::new(),
188            stats: DuplicationStats::default(),
189        }
190    }
191
192    #[test]
193    fn cross_reference_result_methods_use_engine_owned_findings() {
194        let result = CrossReferenceResult {
195            combined_findings: vec![
196                CombinedFinding {
197                    clone_instance: clone_instance("src/a.ts", 1, 3),
198                    dead_code_kind: DeadCodeKind::UnusedFile,
199                    group_index: 2,
200                },
201                CombinedFinding {
202                    clone_instance: clone_instance("src/b.ts", 4, 8),
203                    dead_code_kind: DeadCodeKind::UnusedExport {
204                        export_name: "unused".to_string(),
205                    },
206                    group_index: 4,
207                },
208            ],
209            clones_in_unused_files: 1,
210            clones_with_unused_exports: 1,
211        };
212
213        assert_eq!(result.total(), 2);
214        assert!(result.has_findings());
215        assert!(result.affected_group_indices().contains(&2));
216        assert!(result.affected_group_indices().contains(&4));
217    }
218
219    #[test]
220    fn cross_reference_prioritizes_unused_file_overlap() {
221        let duplication = duplicate_report(vec![
222            clone_instance("src/a.ts", 1, 3),
223            clone_instance("src/b.ts", 4, 8),
224        ]);
225        let mut dead_code = AnalysisResults::default();
226        dead_code
227            .unused_files
228            .push(UnusedFileFinding::with_actions(UnusedFile {
229                path: PathBuf::from("src/a.ts"),
230            }));
231
232        let result = cross_reference(&duplication, &dead_code);
233
234        assert_eq!(result.clones_in_unused_files, 1);
235        assert_eq!(result.clones_with_unused_exports, 0);
236        assert!(matches!(
237            result.combined_findings[0].dead_code_kind,
238            DeadCodeKind::UnusedFile
239        ));
240    }
241
242    #[test]
243    fn cross_reference_detects_unused_export_and_type_overlap() {
244        let duplication = duplicate_report(vec![
245            clone_instance("src/a.ts", 10, 20),
246            clone_instance("src/b.ts", 30, 40),
247        ]);
248        let mut dead_code = AnalysisResults::default();
249        dead_code
250            .unused_exports
251            .push(UnusedExportFinding::with_actions(UnusedExport {
252                path: PathBuf::from("src/a.ts"),
253                export_name: "deadValue".to_string(),
254                line: 12,
255                col: 0,
256                span_start: 0,
257                is_re_export: false,
258                is_type_only: false,
259                deprecated: false,
260                deprecated_reason: None,
261            }));
262        dead_code
263            .unused_types
264            .push(UnusedTypeFinding::with_actions(UnusedExport {
265                path: PathBuf::from("src/b.ts"),
266                export_name: "DeadType".to_string(),
267                line: 35,
268                col: 0,
269                span_start: 0,
270                is_re_export: false,
271                is_type_only: true,
272                deprecated: false,
273                deprecated_reason: None,
274            }));
275
276        let result = cross_reference(&duplication, &dead_code);
277
278        assert_eq!(result.clones_in_unused_files, 0);
279        assert_eq!(result.clones_with_unused_exports, 2);
280        assert!(matches!(
281            result.combined_findings[0].dead_code_kind,
282            DeadCodeKind::UnusedExport { ref export_name } if export_name == "deadValue"
283        ));
284        assert!(matches!(
285            result.combined_findings[1].dead_code_kind,
286            DeadCodeKind::UnusedType { ref type_name } if type_name == "DeadType"
287        ));
288    }
289}