fallow-core 3.49.0

Internal detector backend for fallow-engine and fallow-api
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
use crate::discover::FileId;
use crate::graph::ModuleGraph;
use crate::results::UnusedFile;
use crate::suppress::{IssueKind, SuppressionContext};

use super::predicates::{is_config_file, is_html_file};

/// The reported unused files only. Tests read this shape.
#[cfg(test)]
fn find_unused_files(
    graph: &ModuleGraph,
    suppressions: &SuppressionContext<'_>,
) -> Vec<UnusedFile> {
    find_unused_file_scan(graph, suppressions).files
}

/// The unused files of one run, with and without inline suppressions.
pub struct UnusedFileScan {
    /// The files that the report lists.
    pub files: Vec<UnusedFile>,
    /// The unused files whose finding an inline `fallow-ignore-file
    /// unused-file` comment suppressed. The cascade filter treats them as
    /// reported, so a suppression comment never adds a finding.
    pub suppressed: Vec<std::path::PathBuf>,
}

/// Find files that are not reachable from any entry point.
///
/// TypeScript declaration files (`.d.ts`, `.d.mts`, `.d.cts`) are entry points
/// unless they are orphan module declaration files (see
/// `discover::find_orphan_module_declaration_files`), so only an orphan that
/// nothing reachable imports is reported here.
///
/// Configuration files (e.g., `babel.config.js`, `.eslintrc.js`, `knip.config.ts`)
/// are also excluded because they are consumed by tools, not via imports.
///
/// HTML files are excluded because they are entry-point-like: nothing imports
/// an HTML file, so "unused" is meaningless. They serve as app shells in
/// Vite/Parcel-style projects and their referenced assets are tracked via edges.
///
/// Barrel files (index.ts that only re-export) are excluded when their re-export
/// sources are reachable , they serve an organizational purpose even if consumers
/// import directly from the source files rather than through the barrel.
///
/// The scan also keeps the files that an inline suppression removed from the
/// report, for the cascade filter.
pub fn find_unused_file_scan(
    graph: &ModuleGraph,
    suppressions: &SuppressionContext<'_>,
) -> UnusedFileScan {
    let (suppressed, reported): (Vec<_>, Vec<_>) = graph
        .modules()
        .iter()
        .filter(|m| !m.is_reachable() && !m.is_entry_point())
        .filter(|m| !is_config_file(&m.path))
        .filter(|m| !is_html_file(&m.path))
        .filter(|m| !is_barrel_with_reachable_sources(m, graph))
        .filter(|m| !has_reachable_importer(m.file_id, graph))
        .filter(|m| !has_reachable_export_reference(m.file_id, graph))
        .filter(|m| m.path.exists())
        .partition(|m| suppressions.is_file_suppressed(m.file_id, IssueKind::UnusedFile));
    UnusedFileScan {
        files: reported
            .into_iter()
            .map(|m| UnusedFile {
                path: m.path.clone(),
            })
            .collect(),
        suppressed: suppressed.into_iter().map(|m| m.path.clone()).collect(),
    }
}

/// Check if any reachable module has an edge to this file.
fn has_reachable_importer(file_id: FileId, graph: &ModuleGraph) -> bool {
    let idx = file_id.0 as usize;
    if idx >= graph.reverse_deps.len() {
        return false;
    }
    graph.reverse_deps[idx].iter().any(|&dep_id| {
        let dep_idx = dep_id.0 as usize;
        dep_idx < graph.module_count() && graph.modules()[dep_idx].is_reachable()
    })
}

/// Check if any export on this file is referenced by a reachable module.
fn has_reachable_export_reference(file_id: FileId, graph: &ModuleGraph) -> bool {
    graph.module(file_id).is_some_and(|module| {
        module.exports.iter().any(|export| {
            export.references.iter().any(|reference| {
                graph
                    .modules()
                    .get(reference.from_file.0 as usize)
                    .is_some_and(|m| m.is_reachable())
            })
        })
    })
}

/// Check if a module is a barrel file (only re-exports) whose sources are reachable.
///
/// A barrel file like `index.ts` that only contains `export { Foo } from './source'`
/// lines serves an organizational purpose. If the source modules are reachable,
/// the barrel file should not be reported as unused , consumers may have bypassed
/// it with direct imports, but the barrel still provides valid re-exports.
fn is_barrel_with_reachable_sources(
    module: &crate::graph::ModuleNode,
    graph: &crate::graph::ModuleGraph,
) -> bool {
    if module.re_exports.is_empty() {
        return false;
    }

    let has_local_exports = module
        .exports
        .iter()
        .any(|e| e.span.start != 0 || e.span.end != 0);
    if has_local_exports || module.has_cjs_exports() {
        return false;
    }

    module.re_exports.iter().any(|re| {
        let source_idx = re.source_file.0 as usize;
        graph
            .modules()
            .get(source_idx)
            .is_some_and(|m| m.is_reachable())
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::discover::{DiscoveredFile, EntryPoint, EntryPointSource};
    use crate::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
    use crate::graph::ModuleGraph;
    use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
    use crate::suppress::Suppression;
    use oxc_span::Span;
    use rustc_hash::{FxHashMap, FxHashSet};
    use std::path::PathBuf;

    #[expect(
        clippy::cast_possible_truncation,
        reason = "test file counts are trivially small"
    )]
    fn build_graph(file_specs: &[(&str, bool)]) -> ModuleGraph {
        let files: Vec<DiscoveredFile> = file_specs
            .iter()
            .enumerate()
            .map(|(i, (path, _))| DiscoveredFile {
                id: FileId(i as u32),
                path: PathBuf::from(path),
                size_bytes: 0,
            })
            .collect();

        let entry_points: Vec<EntryPoint> = file_specs
            .iter()
            .filter(|(_, is_entry)| *is_entry)
            .map(|(path, _)| EntryPoint {
                path: PathBuf::from(path),
                source: EntryPointSource::ManualEntry,
            })
            .collect();

        let resolved_modules: Vec<ResolvedModule> = files
            .iter()
            .map(|f| ResolvedModule {
                file_id: f.id,
                path: f.path.clone(),
                exports: vec![].into(),
                re_exports: vec![],
                resolved_imports: vec![],
                resolved_dynamic_imports: vec![],
                resolved_dynamic_patterns: vec![],
                member_accesses: vec![].into(),
                semantic_facts: std::sync::Arc::default(),
                whole_object_uses: std::sync::Arc::default(),
                has_cjs_exports: false,
                has_angular_component_template_url: false,
                unused_import_bindings: FxHashSet::default(),
                type_referenced_import_bindings: vec![],
                value_referenced_import_bindings: vec![],
                namespace_object_aliases: vec![],
                exported_factory_returns: std::sync::Arc::default(),
                exported_factory_return_object_shapes: std::sync::Arc::default(),
                type_member_types: std::sync::Arc::default(),
                missing_export_targets: vec![],
            })
            .collect();

        ModuleGraph::build(&resolved_modules, &entry_points, &files)
    }

    #[expect(
        clippy::cast_possible_truncation,
        reason = "test file counts are trivially small"
    )]
    fn build_graph_with_reference(file_specs: &[(&str, bool)], from: u32) -> ModuleGraph {
        let files: Vec<DiscoveredFile> = file_specs
            .iter()
            .enumerate()
            .map(|(index, (path, _))| DiscoveredFile {
                id: FileId(index as u32),
                path: PathBuf::from(path),
                size_bytes: 0,
            })
            .collect();
        let entry_points: Vec<EntryPoint> = file_specs
            .iter()
            .filter(|(_, is_entry)| *is_entry)
            .map(|(path, _)| EntryPoint {
                path: PathBuf::from(path),
                source: EntryPointSource::ManualEntry,
            })
            .collect();
        let mut resolved_modules: Vec<ResolvedModule> = files
            .iter()
            .map(|file| ResolvedModule {
                file_id: file.id,
                path: file.path.clone(),
                ..Default::default()
            })
            .collect();
        resolved_modules[1].exports = vec![ExportInfo {
            name: ExportName::Named("helper".to_string()),
            local_name: None,
            is_type_only: false,
            is_side_effect_used: false,
            visibility: VisibilityTag::None,
            expected_unused_reason: None,
            span: Span::new(0, 10),
            members: vec![],
            super_class: None,
            deprecated: false,
            deprecated_reason: None,
        }]
        .into();
        resolved_modules[from as usize]
            .resolved_imports
            .push(ResolvedImport {
                info: ImportInfo {
                    source: "./helper".to_string(),
                    imported_name: ImportedName::Named("helper".to_string()),
                    local_name: "helper".to_string(),
                    is_type_only: false,
                    is_type_only_star: false,
                    from_style: false,
                    span: Span::new(0, 10),
                    source_span: Span::default(),
                },
                target: ResolveResult::InternalModule(FileId(1)),
            });

        ModuleGraph::build(&resolved_modules, &entry_points, &files)
    }

    #[test]
    fn has_reachable_importer_out_of_bounds_file_id() {
        let graph = build_graph(&[("/src/entry.ts", true)]);
        assert!(!has_reachable_importer(FileId(999), &graph));
    }

    #[test]
    fn has_reachable_importer_empty_reverse_deps() {
        let graph = build_graph(&[("/src/entry.ts", true), ("/src/orphan.ts", false)]);
        assert!(!has_reachable_importer(FileId(1), &graph));
    }

    #[test]
    fn has_reachable_importer_with_unreachable_importer() {
        let graph = build_graph(&[
            ("/src/entry.ts", true),
            ("/src/a.ts", false),
            ("/src/b.ts", false),
        ]);
        assert!(!has_reachable_importer(FileId(1), &graph));
    }

    #[test]
    fn has_reachable_export_reference_ignores_unreachable_references() {
        let graph = build_graph_with_reference(
            &[
                ("/src/entry.ts", true),
                ("/src/helper.ts", false),
                ("/src/setup.ts", false),
            ],
            2,
        );

        assert!(
            !has_reachable_export_reference(FileId(1), &graph),
            "reference from unreachable module should not save file"
        );
    }

    #[test]
    fn has_reachable_export_reference_detects_reachable_references() {
        let graph =
            build_graph_with_reference(&[("/src/entry.ts", true), ("/src/helper.ts", false)], 0);

        assert!(
            has_reachable_export_reference(FileId(1), &graph),
            "reference from reachable module should keep file alive"
        );
    }

    #[test]
    fn find_unused_files_empty_graph() {
        let graph = build_graph(&[]);
        let result = find_unused_files(&graph, &SuppressionContext::empty());
        assert!(result.is_empty());
    }

    #[test]
    fn find_unused_files_entry_point_never_flagged() {
        let graph = build_graph(&[("/src/entry.ts", true)]);
        let result = find_unused_files(&graph, &SuppressionContext::empty());
        assert!(result.is_empty(), "entry point should never be flagged");
    }

    #[test]
    fn find_unused_files_skips_declaration_files() {
        let graph = build_graph(&[("/src/entry.ts", true), ("/src/types/global.d.ts", false)]);
        let result = find_unused_files(&graph, &SuppressionContext::empty());
        assert!(
            !result
                .iter()
                .any(|f| f.path.to_string_lossy().contains(".d.ts")),
            "declaration files should be skipped"
        );
    }

    #[test]
    fn find_unused_files_skips_config_files() {
        let graph = build_graph(&[("/src/entry.ts", true), ("/jest.config.ts", false)]);
        let result = find_unused_files(&graph, &SuppressionContext::empty());
        assert!(
            !result
                .iter()
                .any(|f| f.path.to_string_lossy().contains("jest.config")),
            "config files should be skipped"
        );
    }

    #[test]
    fn find_unused_files_skips_suppressed_files() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let orphan_path = dir.path().join("orphan.ts");
        std::fs::write(&orphan_path, "export const unused = 1;").expect("write temp file");

        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: dir.path().join("entry.ts"),
                size_bytes: 0,
            },
            DiscoveredFile {
                id: FileId(1),
                path: orphan_path,
                size_bytes: 0,
            },
        ];
        let entry_points = vec![EntryPoint {
            path: dir.path().join("entry.ts"),
            source: EntryPointSource::ManualEntry,
        }];
        let resolved_modules: Vec<ResolvedModule> = files
            .iter()
            .map(|f| ResolvedModule {
                file_id: f.id,
                path: f.path.clone(),
                exports: vec![].into(),
                re_exports: vec![],
                resolved_imports: vec![],
                resolved_dynamic_imports: vec![],
                resolved_dynamic_patterns: vec![],
                member_accesses: vec![].into(),
                semantic_facts: std::sync::Arc::default(),
                whole_object_uses: std::sync::Arc::default(),
                has_cjs_exports: false,
                has_angular_component_template_url: false,
                unused_import_bindings: FxHashSet::default(),
                type_referenced_import_bindings: vec![],
                value_referenced_import_bindings: vec![],
                namespace_object_aliases: vec![],
                exported_factory_returns: std::sync::Arc::default(),
                exported_factory_return_object_shapes: std::sync::Arc::default(),
                type_member_types: std::sync::Arc::default(),
                missing_export_targets: vec![],
            })
            .collect();
        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);

        let supps = vec![Suppression::issue(0, 1, IssueKind::UnusedFile)];
        let supps_slice: &[Suppression] = &supps;
        let mut supp_map: FxHashMap<FileId, &[Suppression]> = FxHashMap::default();
        supp_map.insert(FileId(1), supps_slice);
        let suppressions = SuppressionContext::from_map(supp_map);

        let scan = find_unused_file_scan(&graph, &suppressions);
        assert!(
            scan.files.is_empty(),
            "suppressed file should not be flagged"
        );
        // The suppressed file stays known to the cascade filter, so the
        // suppression comment does not make the findings in it visible again.
        assert_eq!(scan.suppressed, vec![dir.path().join("orphan.ts")]);
    }

    #[test]
    fn find_unused_files_skips_nonexistent_files() {
        let graph = build_graph(&[("/src/entry.ts", true), ("/nonexistent/phantom.ts", false)]);
        let result = find_unused_files(&graph, &SuppressionContext::empty());
        assert!(
            !result
                .iter()
                .any(|f| f.path.to_string_lossy().contains("phantom")),
            "non-existent files should be filtered out"
        );
    }
}

#[cfg(test)]
mod barrel_tests {
    use super::is_barrel_with_reachable_sources;
    use crate::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
    use crate::extract::VisibilityTag;
    use crate::graph::{ExportSymbol, ModuleGraph, ReExportEdge};
    use crate::resolve::ResolvedModule;

    #[expect(
        clippy::cast_possible_truncation,
        reason = "test file counts are trivially small"
    )]
    fn build_graph(file_specs: &[(&str, bool)]) -> ModuleGraph {
        let files: Vec<DiscoveredFile> = file_specs
            .iter()
            .enumerate()
            .map(|(i, (path, _))| DiscoveredFile {
                id: FileId(i as u32),
                path: std::path::PathBuf::from(path),
                size_bytes: 0,
            })
            .collect();

        let entry_points: Vec<EntryPoint> = file_specs
            .iter()
            .filter(|(_, is_entry)| *is_entry)
            .map(|(path, _)| EntryPoint {
                path: std::path::PathBuf::from(path),
                source: EntryPointSource::ManualEntry,
            })
            .collect();

        let resolved_modules: Vec<ResolvedModule> = files
            .iter()
            .map(|f| ResolvedModule {
                file_id: f.id,
                path: f.path.clone(),
                exports: vec![].into(),
                re_exports: vec![],
                resolved_imports: vec![],
                resolved_dynamic_imports: vec![],
                resolved_dynamic_patterns: vec![],
                member_accesses: vec![].into(),
                semantic_facts: std::sync::Arc::default(),
                whole_object_uses: std::sync::Arc::default(),
                has_cjs_exports: false,
                has_angular_component_template_url: false,
                unused_import_bindings: rustc_hash::FxHashSet::default(),
                type_referenced_import_bindings: vec![],
                value_referenced_import_bindings: vec![],
                namespace_object_aliases: vec![],
                exported_factory_returns: std::sync::Arc::default(),
                exported_factory_return_object_shapes: std::sync::Arc::default(),
                type_member_types: std::sync::Arc::default(),
                missing_export_targets: vec![],
            })
            .collect();

        ModuleGraph::build(&resolved_modules, &entry_points, &files)
    }

    /// Module with no re-exports is not a barrel.
    #[test]
    fn barrel_no_re_exports_returns_false() {
        let graph = build_graph(&[("/src/entry.ts", true), ("/src/utils.ts", false)]);
        let module = &graph.modules()[1];
        assert!(!is_barrel_with_reachable_sources(module, &graph));
    }

    /// Module with re-exports but also local exports is not a pure barrel.
    #[test]
    fn barrel_with_local_exports_returns_false() {
        let mut graph = build_graph(&[
            ("/src/entry.ts", true),
            ("/src/index.ts", false),
            ("/src/utils.ts", false),
        ]);
        graph.modules_mut()[2].set_reachable(true);
        graph.modules_mut()[1].re_exports = vec![ReExportEdge {
            source_file: FileId(2),
            imported_name: "helper".to_string(),
            exported_name: "helper".to_string(),
            is_type_only: false,
            span: oxc_span::Span::default(),
        }];
        graph.modules_mut()[1].exports = vec![ExportSymbol {
            name: crate::extract::ExportName::Named("localFn".to_string()),
            is_type_only: false,
            is_side_effect_used: false,
            visibility: VisibilityTag::None,
            expected_unused_reason: None,
            span: oxc_span::Span::new(10, 50),
            references: vec![],
            reference_paths: Vec::new(),
            members: vec![],
            deprecated: false,
            deprecated_reason: None,
        }];
        assert!(!is_barrel_with_reachable_sources(
            &graph.modules()[1],
            &graph
        ));
    }

    /// Module with re-exports and CJS exports is not a pure barrel.
    #[test]
    fn barrel_with_cjs_exports_returns_false() {
        let mut graph = build_graph(&[
            ("/src/entry.ts", true),
            ("/src/index.ts", false),
            ("/src/utils.ts", false),
        ]);
        graph.modules_mut()[2].set_reachable(true);
        graph.modules_mut()[1].re_exports = vec![ReExportEdge {
            source_file: FileId(2),
            imported_name: "helper".to_string(),
            exported_name: "helper".to_string(),
            is_type_only: false,
            span: oxc_span::Span::default(),
        }];
        graph.modules_mut()[1].set_cjs_exports(true);
        assert!(!is_barrel_with_reachable_sources(
            &graph.modules()[1],
            &graph
        ));
    }

    /// Pure barrel with reachable source returns true.
    #[test]
    fn barrel_pure_with_reachable_source_returns_true() {
        let mut graph = build_graph(&[
            ("/src/entry.ts", true),
            ("/src/index.ts", false),
            ("/src/utils.ts", false),
        ]);
        graph.modules_mut()[2].set_reachable(true);
        graph.modules_mut()[1].re_exports = vec![ReExportEdge {
            source_file: FileId(2),
            imported_name: "helper".to_string(),
            exported_name: "helper".to_string(),
            is_type_only: false,
            span: oxc_span::Span::default(),
        }];
        graph.modules_mut()[1].exports = vec![ExportSymbol {
            name: crate::extract::ExportName::Named("helper".to_string()),
            is_type_only: false,
            is_side_effect_used: false,
            visibility: VisibilityTag::None,
            expected_unused_reason: None,
            span: oxc_span::Span::new(0, 0),
            references: vec![],
            reference_paths: Vec::new(),
            members: vec![],
            deprecated: false,
            deprecated_reason: None,
        }];
        assert!(is_barrel_with_reachable_sources(
            &graph.modules()[1],
            &graph
        ));
    }

    /// Pure barrel where all sources are unreachable returns false.
    #[test]
    fn barrel_all_sources_unreachable_returns_false() {
        let mut graph = build_graph(&[
            ("/src/entry.ts", true),
            ("/src/index.ts", false),
            ("/src/utils.ts", false),
        ]);
        graph.modules_mut()[1].re_exports = vec![ReExportEdge {
            source_file: FileId(2),
            imported_name: "helper".to_string(),
            exported_name: "helper".to_string(),
            is_type_only: false,
            span: oxc_span::Span::default(),
        }];
        assert!(!is_barrel_with_reachable_sources(
            &graph.modules()[1],
            &graph
        ));
    }

    /// Barrel with out-of-bounds source FileId doesn't panic, returns false.
    #[test]
    fn barrel_out_of_bounds_source_returns_false() {
        let mut graph = build_graph(&[("/src/entry.ts", true), ("/src/index.ts", false)]);
        graph.modules_mut()[1].re_exports = vec![ReExportEdge {
            source_file: FileId(999), // out of bounds
            imported_name: "helper".to_string(),
            exported_name: "helper".to_string(),
            is_type_only: false,
            span: oxc_span::Span::default(),
        }];
        assert!(!is_barrel_with_reachable_sources(
            &graph.modules()[1],
            &graph
        ));
    }
}