1use std::collections::{HashMap, HashSet};
8use std::fmt::{self, Write};
9use std::path::Path;
10
11use oxc_allocator::Allocator;
12use oxc_ast::ast::*;
13
14#[must_use]
17pub fn sanitize_module_name(raw: &str) -> String {
18 let mut result = String::new();
19 for ch in raw.chars() {
20 if ch.is_ascii_alphanumeric() || ch == '_' {
21 result.push(ch);
22 } else {
23 let _ = write!(result, "_u{:04x}", ch as u32);
24 }
25 }
26 if result.is_empty() {
27 result.push_str("_unnamed");
28 }
29 if !result.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
30 result.insert(0, '_');
31 }
32 if result == "lib" {
34 result.push_str("_mod");
35 }
36 result
37}
38
39fn sanitize_name(filename: &str) -> String {
41 let stem = filename.strip_suffix(".js").unwrap_or(filename);
42 sanitize_module_name(stem)
43}
44
45pub struct AnalysisResult {
48 pub core_name: String,
50 pub members: Vec<String>,
52 pub name_map: HashMap<String, String>,
54 pub imported_names: HashMap<String, Vec<(String, String)>>,
57 pub exported_names: HashMap<String, HashSet<String>>,
59 pub all_fn_names: HashMap<String, HashSet<String>>,
61 pub file_sources: HashMap<String, String>,
63 pub parsed_programs: HashMap<String, Program<'static>>,
68}
69
70impl fmt::Debug for AnalysisResult {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 f.debug_struct("AnalysisResult")
74 .field("core_name", &self.core_name)
75 .field("members", &self.members)
76 .field("name_map", &self.name_map)
77 .field("imported_names", &self.imported_names)
78 .field("exported_names", &self.exported_names)
79 .field("all_fn_names", &self.all_fn_names)
80 .field(
81 "file_sources",
82 &format_args!("{} files", self.file_sources.len()),
83 )
84 .field(
85 "parsed_programs",
86 &format_args!("{} programs", self.parsed_programs.len()),
87 )
88 .finish()
89 }
90}
91
92pub fn analyze_project(in_dir: &Path, js_files: &[String]) -> AnalysisResult {
99 assert!(!js_files.is_empty(), "js_files must not be empty");
100
101 let core_file = &js_files[0];
102
103 let mut visited: HashSet<String> = HashSet::new();
107 let mut stack: Vec<String> = js_files.to_vec();
108 stack.reverse();
110
111 let mut imports: HashMap<String, Vec<String>> = HashMap::new();
112 let mut imported_names: HashMap<String, Vec<(String, String)>> = HashMap::new();
113 let mut exported_names: HashMap<String, HashSet<String>> = HashMap::new();
114 let mut all_fn_names: HashMap<String, HashSet<String>> = HashMap::new();
115 let mut file_sources: HashMap<String, String> = HashMap::new();
116 let mut parsed_programs: HashMap<String, Program<'static>> = HashMap::new();
117 let mut sanitized: HashMap<String, String> = HashMap::new();
118
119 while let Some(cur) = stack.pop() {
120 if !visited.insert(cur.clone()) {
121 continue;
122 }
123
124 let src = std::fs::read_to_string(in_dir.join(&cur))
125 .unwrap_or_else(|e| panic!("Cannot read '{}': {}", cur, e));
126
127 let allocator: &'static Allocator = {
134 use std::sync::atomic::{AtomicPtr, Ordering};
135 static ALLOC_PTR: AtomicPtr<Allocator> = AtomicPtr::new(std::ptr::null_mut());
136 let ptr = ALLOC_PTR.load(Ordering::Acquire);
137 if !ptr.is_null() {
138 unsafe { &*ptr }
140 } else {
141 let leaked: &'static mut Allocator = Box::leak(Box::new(Allocator::default()));
142 ALLOC_PTR.store(leaked as *mut Allocator, Ordering::Release);
143 leaked
144 }
145 };
146 let src_static: &'static str = Box::leak(src.clone().into_boxed_str());
147 let program: Program<'static> = crate::parser::parse_with_name(allocator, src_static, &cur);
148
149 let info = analyze_module_ast(&program);
150
151 for dep in &info.imported_files {
152 if !visited.contains(dep.as_str()) {
153 stack.push(dep.clone());
154 }
155 }
156
157 sanitized.insert(cur.clone(), sanitize_name(&cur));
158 imports.insert(cur.clone(), info.imported_files);
159 imported_names.insert(cur.clone(), info.imported_names);
160 exported_names.insert(cur.clone(), info.exported_names);
161 all_fn_names.insert(cur.clone(), info.all_toplevel_fn_names);
162 file_sources.insert(cur.clone(), src);
163 parsed_programs.insert(cur, program);
164 }
165
166 let members = transitive_deps_multi(js_files, &imports);
168 let core_name = sanitized
169 .get(core_file)
170 .cloned()
171 .unwrap_or_else(|| sanitize_name(core_file));
172
173 AnalysisResult {
174 core_name,
175 members,
176 name_map: sanitized,
177 imported_names,
178 exported_names,
179 all_fn_names,
180 file_sources,
181 parsed_programs,
182 }
183}
184
185fn transitive_deps_multi(roots: &[String], imports: &HashMap<String, Vec<String>>) -> Vec<String> {
188 let mut visited: HashSet<String> = HashSet::new();
189 let mut stack: Vec<String> = roots.to_vec();
190 let mut result: Vec<String> = Vec::new();
191
192 while let Some(cur) = stack.pop() {
194 if !visited.insert(cur.clone()) {
195 continue;
196 }
197 result.push(cur.clone());
198 if let Some(deps) = imports.get(&cur) {
199 for dep in deps {
200 if !visited.contains(dep.as_str()) {
201 stack.push(dep.clone());
202 }
203 }
204 }
205 }
206 result.reverse();
207 result
208}
209
210fn path_to_filename(path: &str) -> Option<String> {
212 let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
213 if fname.ends_with(".js") {
214 Some(fname)
215 } else {
216 Some(format!("{}.js", fname))
217 }
218}
219
220struct ModuleInfo {
222 imported_files: Vec<String>,
223 imported_names: Vec<(String, String)>,
224 exported_names: HashSet<String>,
225 all_toplevel_fn_names: HashSet<String>,
226}
227
228fn analyze_module_ast(program: &Program) -> ModuleInfo {
231 let mut imported_files = Vec::new();
232 let mut imported_names = Vec::new();
233 let mut exported_names = HashSet::new();
234 let mut all_toplevel_fn_names = HashSet::new();
235
236 for stmt in &program.body {
237 match stmt {
238 Statement::ImportDeclaration(import) => {
239 let source_str = import.source.value.as_str();
240 if let Some(sf) = path_to_filename(source_str) {
241 imported_files.push(sf.clone());
242 if let Some(specifiers) = &import.specifiers {
243 for spec in specifiers {
244 let name = match spec {
245 ImportDeclarationSpecifier::ImportSpecifier(s) => {
246 s.local.name.as_str().to_string()
247 }
248 ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
249 s.local.name.as_str().to_string()
250 }
251 ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
252 s.local.name.as_str().to_string()
253 }
254 };
255 imported_names.push((name, sf.clone()));
256 }
257 }
258 }
259 }
260 Statement::ExportNamedDeclaration(e) => {
261 if let Some(decl) = &e.declaration {
263 match decl {
264 Declaration::FunctionDeclaration(fd) => {
265 if let Some(id) = &fd.id {
266 let name = id.name.as_str().to_string();
267 exported_names.insert(name.clone());
268 all_toplevel_fn_names.insert(name);
269 }
270 }
271 Declaration::VariableDeclaration(vd) => {
272 for d in &vd.declarations {
273 if let BindingPattern::BindingIdentifier(id) = &d.id {
274 exported_names.insert(id.name.as_str().to_string());
275 }
276 }
277 }
278 Declaration::ClassDeclaration(cd) => {
279 if let Some(id) = &cd.id {
280 exported_names.insert(id.name.as_str().to_string());
281 }
282 }
283 _ => {}
284 }
285 }
286 for spec in &e.specifiers {
288 if let ModuleExportName::IdentifierName(id) = &spec.exported {
289 exported_names.insert(id.name.as_str().to_string());
290 }
291 }
292 }
293 Statement::ExportDefaultDeclaration(e) => {
294 if let Some(name) = match &e.declaration {
297 ExportDefaultDeclarationKind::FunctionDeclaration(fd) => {
298 fd.id.as_ref().map(|id| id.name.as_str().to_string())
299 }
300 ExportDefaultDeclarationKind::ClassDeclaration(cd) => {
301 cd.id.as_ref().map(|id| id.name.as_str().to_string())
302 }
303 _ => None,
304 } {
305 exported_names.insert(name.clone());
306 all_toplevel_fn_names.insert(name);
307 }
308 }
309 Statement::FunctionDeclaration(fd) => {
310 if let Some(id) = &fd.id {
311 all_toplevel_fn_names.insert(id.name.as_str().to_string());
312 }
313 }
314 Statement::ExpressionStatement(es) => {
315 if let Some(names) = extract_module_exports(es) {
317 for name in names {
318 exported_names.insert(name);
319 }
320 }
321 }
322 _ => {}
323 }
324 }
325
326 imported_files.sort();
327 imported_files.dedup();
328 imported_names.sort();
329 imported_names.dedup();
330
331 ModuleInfo {
332 imported_files,
333 imported_names,
334 exported_names,
335 all_toplevel_fn_names,
336 }
337}
338
339fn extract_module_exports(es: &ExpressionStatement) -> Option<Vec<String>> {
342 use oxc_ast::ast::AssignmentTarget;
343
344 let Expression::AssignmentExpression(assign) = &es.expression else {
345 return None;
346 };
347
348 let AssignmentTarget::StaticMemberExpression(lhs) = &assign.left else {
350 return None;
351 };
352
353 let Expression::Identifier(obj) = &lhs.object else {
354 return None;
355 };
356 if obj.name.as_str() != "module" {
357 return None;
358 }
359 if lhs.property.name.as_str() != "exports" {
360 return None;
361 }
362
363 match &assign.right {
365 Expression::ObjectExpression(obj) => {
366 let names: Vec<String> = obj
367 .properties
368 .iter()
369 .filter_map(|p| match p {
370 ObjectPropertyKind::ObjectProperty(op) => match &op.key {
371 PropertyKey::StaticIdentifier(id) => Some(id.name.as_str().to_string()),
372 _ => None,
373 },
374 _ => None,
375 })
376 .collect();
377 if names.is_empty() { None } else { Some(names) }
378 }
379 _ => None,
380 }
381}