Skip to main content

fallow_engine/
import_bindings.rs

1//! The import declarations of a file, and how often the code refers to each
2//! imported name.
3//!
4//! `fallow fix` removes a name from an `export { ... }` list. When that name
5//! came from an import that nothing else in the file uses, the fix must also
6//! remove the import. A kept import still counts as a consumer for the type
7//! checker, but not for the analysis, so the next fix run would remove the
8//! `export` that the import needs.
9
10use std::path::Path;
11
12use oxc_ast::ast::{IdentifierReference, ImportDeclarationSpecifier, Program, Statement};
13use oxc_ast_visit::Visit;
14use oxc_span::SourceType;
15use rustc_hash::FxHashMap;
16
17/// The form of one binding of an import declaration.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ImportBindingKind {
20    /// `import a from 'x'`
21    Default,
22    /// `import * as a from 'x'`
23    Namespace,
24    /// `import { a } from 'x'`, `import { b as a } from 'x'`
25    Named,
26}
27
28/// One local binding of an import declaration.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ImportBinding {
31    /// The local name.
32    pub local: String,
33    /// The byte offset of the first token of the specifier.
34    pub start: u32,
35    /// The byte offset after the last token of the specifier.
36    pub end: u32,
37    /// The form of the binding.
38    pub kind: ImportBindingKind,
39}
40
41/// One top-level import declaration with at least one binding.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ImportDeclarationBindings {
44    /// The byte offset of the `import` keyword.
45    pub start: u32,
46    /// The byte offset after the end of the declaration.
47    pub end: u32,
48    /// The bindings, in source order.
49    pub bindings: Vec<ImportBinding>,
50}
51
52/// The import declarations of a file and the references to their names.
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct FileImportBindings {
55    /// The import declarations with bindings, in source order.
56    pub declarations: Vec<ImportDeclarationBindings>,
57    /// For each imported local name, the number of identifier references
58    /// with that name in the file. A specifier of an `export { ... }` list
59    /// without a `from` clause is a reference. The count matches by name, so
60    /// a shadowing declaration can only make the count higher.
61    pub reference_counts: FxHashMap<String, usize>,
62}
63
64/// The import bindings of the JavaScript or TypeScript file at `path`.
65///
66/// Returns `None` for a Vue, Svelte, Astro or other file type, and when the
67/// file does not parse cleanly.
68#[must_use]
69pub fn import_bindings(path: &Path, source: &str) -> Option<FileImportBindings> {
70    if fallow_extract::is_sfc_file(path)
71        || path
72            .extension()
73            .is_some_and(|extension| extension == "astro")
74    {
75        return None;
76    }
77    let source_type = SourceType::from_path(path).ok()?;
78    fallow_extract::parse_bounded(source, || {
79        let allocator = oxc_allocator::Allocator::default();
80        let parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
81        if parsed.fatal_error || parsed.diagnostics.has_errors() {
82            return None;
83        }
84        Some(collect(&parsed.program))
85    })
86    .flatten()
87}
88
89fn collect(program: &Program<'_>) -> FileImportBindings {
90    let declarations: Vec<ImportDeclarationBindings> = program
91        .body
92        .iter()
93        .filter_map(|statement| {
94            let Statement::ImportDeclaration(import) = statement else {
95                return None;
96            };
97            let bindings: Vec<ImportBinding> = import
98                .specifiers
99                .as_ref()?
100                .iter()
101                .map(|specifier| {
102                    let (local, span, kind) = match specifier {
103                        ImportDeclarationSpecifier::ImportSpecifier(it) => {
104                            (&it.local, it.span, ImportBindingKind::Named)
105                        }
106                        ImportDeclarationSpecifier::ImportDefaultSpecifier(it) => {
107                            (&it.local, it.span, ImportBindingKind::Default)
108                        }
109                        ImportDeclarationSpecifier::ImportNamespaceSpecifier(it) => {
110                            (&it.local, it.span, ImportBindingKind::Namespace)
111                        }
112                    };
113                    ImportBinding {
114                        local: local.name.to_string(),
115                        start: span.start,
116                        end: span.end,
117                        kind,
118                    }
119                })
120                .collect();
121            (!bindings.is_empty()).then_some(ImportDeclarationBindings {
122                start: import.span.start,
123                end: import.span.end,
124                bindings,
125            })
126        })
127        .collect();
128    let mut reference_counts: FxHashMap<String, usize> = declarations
129        .iter()
130        .flat_map(|declaration| &declaration.bindings)
131        .map(|binding| (binding.local.clone(), 0))
132        .collect();
133    if !reference_counts.is_empty() {
134        let mut counter = ReferenceCounter {
135            counts: &mut reference_counts,
136        };
137        counter.visit_program(program);
138    }
139    FileImportBindings {
140        declarations,
141        reference_counts,
142    }
143}
144
145struct ReferenceCounter<'c> {
146    counts: &'c mut FxHashMap<String, usize>,
147}
148
149impl<'a> Visit<'a> for ReferenceCounter<'_> {
150    fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) {
151        if let Some(count) = self.counts.get_mut(it.name.as_str()) {
152            *count += 1;
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    fn bindings(source: &str) -> FileImportBindings {
162        import_bindings(Path::new("barrel.ts"), source).unwrap()
163    }
164
165    #[test]
166    fn counts_export_list_specifiers_as_references() {
167        let source = "import { a } from './a';\nimport { used } from './used';\nused();\nexport { a, used };\n";
168        let found = bindings(source);
169        assert_eq!(found.reference_counts["a"], 1);
170        assert_eq!(found.reference_counts["used"], 2);
171        assert_eq!(found.declarations.len(), 2);
172        let first = &found.declarations[0];
173        assert_eq!(
174            &source[first.start as usize..first.end as usize],
175            "import { a } from './a';"
176        );
177        assert_eq!(first.bindings[0].kind, ImportBindingKind::Named);
178    }
179
180    #[test]
181    fn counts_type_and_jsx_references() {
182        let source = "import Box, * as ns from './box';\nimport { type T } from './t';\nconst x: T = 1;\nconst y = <Box />;\nexport { x, y };\n";
183        let found = import_bindings(Path::new("view.tsx"), source).unwrap();
184        assert_eq!(found.reference_counts["T"], 1);
185        assert_eq!(found.reference_counts["Box"], 1);
186        assert_eq!(found.reference_counts["ns"], 0);
187        let kinds: Vec<_> = found.declarations[0]
188            .bindings
189            .iter()
190            .map(|binding| binding.kind)
191            .collect();
192        assert_eq!(
193            kinds,
194            vec![ImportBindingKind::Default, ImportBindingKind::Namespace]
195        );
196    }
197
198    #[test]
199    fn skips_side_effect_imports() {
200        assert!(bindings("import './polyfill';\n").declarations.is_empty());
201    }
202
203    #[test]
204    fn gives_none_for_a_component_file_or_a_parse_error() {
205        assert_eq!(
206            import_bindings(
207                Path::new("a.vue"),
208                "<script>import { a } from './a';</script>"
209            ),
210            None
211        );
212        assert_eq!(import_bindings(Path::new("a.ts"), "import { from;"), None);
213    }
214}