fallow_engine/
import_bindings.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ImportBindingKind {
20 Default,
22 Namespace,
24 Named,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ImportBinding {
31 pub local: String,
33 pub start: u32,
35 pub end: u32,
37 pub kind: ImportBindingKind,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ImportDeclarationBindings {
44 pub start: u32,
46 pub end: u32,
48 pub bindings: Vec<ImportBinding>,
50}
51
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct FileImportBindings {
55 pub declarations: Vec<ImportDeclarationBindings>,
57 pub reference_counts: FxHashMap<String, usize>,
62}
63
64#[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}