1use std::collections::{HashMap, HashSet};
9use std::fmt::{self, Write};
10use std::path::Path;
11
12use oxc_allocator::Allocator;
13use oxc_ast::ast::*;
14
15#[must_use]
18pub fn sanitize_module_name(raw: &str) -> String {
19 let mut result = String::new();
20 for ch in raw.chars() {
21 if ch.is_ascii_alphanumeric() || ch == '_' {
22 result.push(ch);
23 } else {
24 let _ = write!(result, "_u{:04x}", ch as u32);
25 }
26 }
27 if result.is_empty() {
28 result.push_str("_unnamed");
29 }
30 if !result.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
31 result.insert(0, '_');
32 }
33 if result == "lib" {
35 result.push_str("_mod");
36 }
37 result
38}
39
40fn sanitize_name(filename: &str) -> String {
42 let stem = filename.strip_suffix(".js").unwrap_or(filename);
43 sanitize_module_name(stem)
44}
45
46pub struct FileGroup {
48 pub core_name: String,
50 pub core_file: String,
52 pub members: Vec<String>,
54 pub name_map: HashMap<String, String>,
56 pub imported_names: HashMap<String, Vec<(String, String)>>,
59 pub exported_names: HashMap<String, HashSet<String>>,
61 pub all_fn_names: HashMap<String, HashSet<String>>,
63 pub file_sources: HashMap<String, String>,
65 pub parsed_programs: HashMap<String, Program<'static>>,
70}
71
72impl fmt::Debug for FileGroup {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.debug_struct("FileGroup")
76 .field("core_name", &self.core_name)
77 .field("core_file", &self.core_file)
78 .field("members", &self.members)
79 .field("name_map", &self.name_map)
80 .field("imported_names", &self.imported_names)
81 .field("exported_names", &self.exported_names)
82 .field("all_fn_names", &self.all_fn_names)
83 .field(
84 "file_sources",
85 &format_args!("{} files", self.file_sources.len()),
86 )
87 .field(
88 "parsed_programs",
89 &format_args!("{} programs", self.parsed_programs.len()),
90 )
91 .finish()
92 }
93}
94
95pub fn analyze_single_group(
105 in_dir: &str,
106 core_file: &str,
107 additional_core_files: &[String],
108) -> (Vec<FileGroup>, String) {
109 let in_path = Path::new(in_dir);
110
111 let mut visited: HashSet<String> = HashSet::new();
115 let mut stack: Vec<String> = vec![core_file.to_string()];
116 for addl_file in additional_core_files {
117 stack.push(addl_file.clone());
118 }
119 stack.reverse();
121
122 let mut imports: HashMap<String, Vec<String>> = HashMap::new();
123 let mut imported_names: HashMap<String, Vec<(String, String)>> = HashMap::new();
124 let mut exported_names: HashMap<String, HashSet<String>> = HashMap::new();
125 let mut all_fn_names: HashMap<String, HashSet<String>> = HashMap::new();
126 let mut file_sources: HashMap<String, String> = HashMap::new();
127 let mut parsed_programs: HashMap<String, Program<'static>> = HashMap::new();
128 let mut sanitzed: HashMap<String, String> = HashMap::new();
129
130 while let Some(cur) = stack.pop() {
131 if !visited.insert(cur.clone()) {
132 continue;
133 }
134
135 let src = std::fs::read_to_string(in_path.join(&cur))
136 .unwrap_or_else(|e| panic!("Cannot read '{}': {}", cur, e));
137
138 let allocator: &'static Allocator = {
145 use std::sync::atomic::{AtomicPtr, Ordering};
146 static ALLOC_PTR: AtomicPtr<Allocator> = AtomicPtr::new(std::ptr::null_mut());
147 let ptr = ALLOC_PTR.load(Ordering::Acquire);
148 if !ptr.is_null() {
149 unsafe { &*ptr }
151 } else {
152 let leaked: &'static mut Allocator = Box::leak(Box::new(Allocator::default()));
153 ALLOC_PTR.store(leaked as *mut Allocator, Ordering::Release);
154 leaked
155 }
156 };
157 let src_static: &'static str = Box::leak(src.clone().into_boxed_str());
158 let program: Program<'static> = crate::parser::parse_with_name(allocator, src_static, &cur);
159
160 let info = analyze_module_ast(&program);
161
162 for dep in &info.imported_files {
163 if !visited.contains(dep.as_str()) {
164 stack.push(dep.clone());
165 }
166 }
167
168 sanitzed.insert(cur.clone(), sanitize_name(&cur));
169 imports.insert(cur.clone(), info.imported_files);
170 imported_names.insert(cur.clone(), info.imported_names);
171 exported_names.insert(cur.clone(), info.exported_names);
172 all_fn_names.insert(cur.clone(), info.all_toplevel_fn_names);
173 file_sources.insert(cur.clone(), src);
174 parsed_programs.insert(cur, program);
175 }
176
177 let all_roots: Vec<String> = std::iter::once(core_file.to_string())
179 .chain(additional_core_files.iter().cloned())
180 .collect();
181 let members = transitive_deps_multi(&all_roots, &imports);
182 let core_name = sanitzed
183 .get(core_file)
184 .cloned()
185 .unwrap_or_else(|| sanitize_name(core_file));
186
187 let group = FileGroup {
188 core_name: core_name.clone(),
189 core_file: core_file.to_string(),
190 members,
191 name_map: sanitzed,
192 imported_names,
193 exported_names,
194 all_fn_names,
195 file_sources,
196 parsed_programs,
197 };
198
199 let groups = vec![group];
200 let groups_json = serde_json::to_string_pretty(&groups_to_json(&groups))
201 .expect("Failed to serialize groups.json");
202
203 (groups, groups_json)
204}
205
206fn transitive_deps_multi(roots: &[String], imports: &HashMap<String, Vec<String>>) -> Vec<String> {
209 let mut visited: HashSet<String> = HashSet::new();
210 let mut stack: Vec<String> = roots.to_vec();
211 let mut result: Vec<String> = Vec::new();
212
213 while let Some(cur) = stack.pop() {
215 if !visited.insert(cur.clone()) {
216 continue;
217 }
218 result.push(cur.clone());
219 if let Some(deps) = imports.get(&cur) {
220 for dep in deps {
221 if !visited.contains(dep.as_str()) {
222 stack.push(dep.clone());
223 }
224 }
225 }
226 }
227 result.reverse();
228 result
229}
230
231fn path_to_filename(path: &str) -> Option<String> {
233 let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
234 if fname.ends_with(".js") {
235 Some(fname)
236 } else {
237 Some(format!("{}.js", fname))
238 }
239}
240
241struct ModuleInfo {
243 imported_files: Vec<String>,
244 imported_names: Vec<(String, String)>,
245 exported_names: HashSet<String>,
246 all_toplevel_fn_names: HashSet<String>,
247}
248
249fn analyze_module_ast(program: &Program) -> ModuleInfo {
252 let mut imported_files = Vec::new();
253 let mut imported_names = Vec::new();
254 let mut exported_names = HashSet::new();
255 let mut all_toplevel_fn_names = HashSet::new();
256
257 for stmt in &program.body {
258 match stmt {
259 Statement::ImportDeclaration(import) => {
260 let source_str = import.source.value.as_str();
261 if let Some(sf) = path_to_filename(source_str) {
262 imported_files.push(sf.clone());
263 if let Some(specifiers) = &import.specifiers {
264 for spec in specifiers {
265 let name = match spec {
266 ImportDeclarationSpecifier::ImportSpecifier(s) => {
267 s.local.name.as_str().to_string()
268 }
269 ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
270 s.local.name.as_str().to_string()
271 }
272 ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
273 s.local.name.as_str().to_string()
274 }
275 };
276 imported_names.push((name, sf.clone()));
277 }
278 }
279 }
280 }
281 Statement::ExportNamedDeclaration(e) => {
282 if let Some(decl) = &e.declaration {
284 match decl {
285 Declaration::FunctionDeclaration(fd) => {
286 if let Some(id) = &fd.id {
287 let name = id.name.as_str().to_string();
288 exported_names.insert(name.clone());
289 all_toplevel_fn_names.insert(name);
290 }
291 }
292 Declaration::VariableDeclaration(vd) => {
293 for d in &vd.declarations {
294 if let BindingPattern::BindingIdentifier(id) = &d.id {
295 exported_names.insert(id.name.as_str().to_string());
296 }
297 }
298 }
299 Declaration::ClassDeclaration(cd) => {
300 if let Some(id) = &cd.id {
301 exported_names.insert(id.name.as_str().to_string());
302 }
303 }
304 _ => {}
305 }
306 }
307 for spec in &e.specifiers {
309 if let ModuleExportName::IdentifierName(id) = &spec.exported {
310 exported_names.insert(id.name.as_str().to_string());
311 }
312 }
313 }
314 Statement::ExportDefaultDeclaration(e) => {
315 if let Some(name) = match &e.declaration {
318 ExportDefaultDeclarationKind::FunctionDeclaration(fd) => {
319 fd.id.as_ref().map(|id| id.name.as_str().to_string())
320 }
321 ExportDefaultDeclarationKind::ClassDeclaration(cd) => {
322 cd.id.as_ref().map(|id| id.name.as_str().to_string())
323 }
324 _ => None,
325 } {
326 exported_names.insert(name.clone());
327 all_toplevel_fn_names.insert(name);
328 }
329 }
330 Statement::FunctionDeclaration(fd) => {
331 if let Some(id) = &fd.id {
332 all_toplevel_fn_names.insert(id.name.as_str().to_string());
333 }
334 }
335 Statement::ExpressionStatement(es) => {
336 if let Some(names) = extract_module_exports(es) {
338 for name in names {
339 exported_names.insert(name);
340 }
341 }
342 }
343 _ => {}
344 }
345 }
346
347 imported_files.sort();
348 imported_files.dedup();
349 imported_names.sort();
350 imported_names.dedup();
351
352 ModuleInfo {
353 imported_files,
354 imported_names,
355 exported_names,
356 all_toplevel_fn_names,
357 }
358}
359
360fn extract_module_exports(es: &ExpressionStatement) -> Option<Vec<String>> {
363 use oxc_ast::ast::AssignmentTarget;
364
365 let Expression::AssignmentExpression(assign) = &es.expression else {
366 return None;
367 };
368
369 let AssignmentTarget::StaticMemberExpression(lhs) = &assign.left else {
371 return None;
372 };
373
374 let Expression::Identifier(obj) = &lhs.object else {
375 return None;
376 };
377 if obj.name.as_str() != "module" {
378 return None;
379 }
380 if lhs.property.name.as_str() != "exports" {
381 return None;
382 }
383
384 match &assign.right {
386 Expression::ObjectExpression(obj) => {
387 let names: Vec<String> = obj
388 .properties
389 .iter()
390 .filter_map(|p| match p {
391 ObjectPropertyKind::ObjectProperty(op) => match &op.key {
392 PropertyKey::StaticIdentifier(id) => Some(id.name.as_str().to_string()),
393 _ => None,
394 },
395 _ => None,
396 })
397 .collect();
398 if names.is_empty() { None } else { Some(names) }
399 }
400 _ => None,
401 }
402}
403
404fn groups_to_json(groups: &[FileGroup]) -> serde_json::Value {
406 let entries: Vec<serde_json::Value> = groups
407 .iter()
408 .map(|g| {
409 serde_json::json!({
410 "name": g.core_name,
411 "core_file": g.core_file,
412 "member_count": g.members.len(),
413 "members": g.members,
414 })
415 })
416 .collect();
417 serde_json::Value::Array(entries)
418}