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 = Box::leak(Box::new(Allocator::default()));
141 let src_static: &'static str = Box::leak(src.clone().into_boxed_str());
142 let program: Program<'static> = crate::parser::parse(allocator, src_static);
143
144 let info = analyze_module_ast(&program);
145
146 for dep in &info.imported_files {
147 if !visited.contains(dep.as_str()) {
148 stack.push(dep.clone());
149 }
150 }
151
152 sanitzed.insert(cur.clone(), sanitize_name(&cur));
153 imports.insert(cur.clone(), info.imported_files);
154 imported_names.insert(cur.clone(), info.imported_names);
155 exported_names.insert(cur.clone(), info.exported_names);
156 all_fn_names.insert(cur.clone(), info.all_toplevel_fn_names);
157 file_sources.insert(cur.clone(), src);
158 parsed_programs.insert(cur, program);
159 }
160
161 let all_roots: Vec<String> = std::iter::once(core_file.to_string())
163 .chain(additional_core_files.iter().cloned())
164 .collect();
165 let members = transitive_deps_multi(&all_roots, &imports);
166 let core_name = sanitzed
167 .get(core_file)
168 .cloned()
169 .unwrap_or_else(|| sanitize_name(core_file));
170
171 let group = FileGroup {
172 core_name: core_name.clone(),
173 core_file: core_file.to_string(),
174 members,
175 name_map: sanitzed,
176 imported_names,
177 exported_names,
178 all_fn_names,
179 file_sources,
180 parsed_programs,
181 };
182
183 let groups = vec![group];
184 let groups_json = serde_json::to_string_pretty(&groups_to_json(&groups))
185 .expect("Failed to serialize groups.json");
186
187 (groups, groups_json)
188}
189
190fn transitive_deps_multi(roots: &[String], imports: &HashMap<String, Vec<String>>) -> Vec<String> {
193 let mut visited: HashSet<String> = HashSet::new();
194 let mut stack: Vec<String> = roots.to_vec();
195 let mut result: Vec<String> = Vec::new();
196
197 while let Some(cur) = stack.pop() {
199 if !visited.insert(cur.clone()) {
200 continue;
201 }
202 result.push(cur.clone());
203 if let Some(deps) = imports.get(&cur) {
204 for dep in deps {
205 if !visited.contains(dep.as_str()) {
206 stack.push(dep.clone());
207 }
208 }
209 }
210 }
211 result.reverse();
212 result
213}
214
215fn path_to_filename(path: &str) -> Option<String> {
217 let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
218 if fname.ends_with(".js") {
219 Some(fname)
220 } else {
221 Some(format!("{}.js", fname))
222 }
223}
224
225struct ModuleInfo {
227 imported_files: Vec<String>,
228 imported_names: Vec<(String, String)>,
229 exported_names: HashSet<String>,
230 all_toplevel_fn_names: HashSet<String>,
231}
232
233fn analyze_module_ast(program: &Program) -> ModuleInfo {
236 let mut imported_files = Vec::new();
237 let mut imported_names = Vec::new();
238 let mut exported_names = HashSet::new();
239 let mut all_toplevel_fn_names = HashSet::new();
240
241 for stmt in &program.body {
242 match stmt {
243 Statement::ImportDeclaration(import) => {
244 let source_str = import.source.value.as_str();
245 if let Some(sf) = path_to_filename(source_str) {
246 imported_files.push(sf.clone());
247 if let Some(specifiers) = &import.specifiers {
248 for spec in specifiers {
249 let name = match spec {
250 ImportDeclarationSpecifier::ImportSpecifier(s) => {
251 s.local.name.as_str().to_string()
252 }
253 ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
254 s.local.name.as_str().to_string()
255 }
256 ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
257 s.local.name.as_str().to_string()
258 }
259 };
260 imported_names.push((name, sf.clone()));
261 }
262 }
263 }
264 }
265 Statement::ExportNamedDeclaration(e) => {
266 if let Some(decl) = &e.declaration {
268 match decl {
269 Declaration::FunctionDeclaration(fd) => {
270 if let Some(id) = &fd.id {
271 let name = id.name.as_str().to_string();
272 exported_names.insert(name.clone());
273 all_toplevel_fn_names.insert(name);
274 }
275 }
276 Declaration::VariableDeclaration(vd) => {
277 for d in &vd.declarations {
278 if let BindingPattern::BindingIdentifier(id) = &d.id {
279 exported_names.insert(id.name.as_str().to_string());
280 }
281 }
282 }
283 Declaration::ClassDeclaration(cd) => {
284 if let Some(id) = &cd.id {
285 exported_names.insert(id.name.as_str().to_string());
286 }
287 }
288 _ => {}
289 }
290 }
291 for spec in &e.specifiers {
293 if let ModuleExportName::IdentifierName(id) = &spec.exported {
294 exported_names.insert(id.name.as_str().to_string());
295 }
296 }
297 }
298 Statement::ExportDefaultDeclaration(e) => {
299 if let Some(name) = match &e.declaration {
302 ExportDefaultDeclarationKind::FunctionDeclaration(fd) => {
303 fd.id.as_ref().map(|id| id.name.as_str().to_string())
304 }
305 ExportDefaultDeclarationKind::ClassDeclaration(cd) => {
306 cd.id.as_ref().map(|id| id.name.as_str().to_string())
307 }
308 _ => None,
309 } {
310 exported_names.insert(name.clone());
311 all_toplevel_fn_names.insert(name);
312 }
313 }
314 Statement::FunctionDeclaration(fd) => {
315 if let Some(id) = &fd.id {
316 all_toplevel_fn_names.insert(id.name.as_str().to_string());
317 }
318 }
319 _ => {}
320 }
321 }
322
323 imported_files.sort();
324 imported_files.dedup();
325 imported_names.sort();
326 imported_names.dedup();
327
328 ModuleInfo {
329 imported_files,
330 imported_names,
331 exported_names,
332 all_toplevel_fn_names,
333 }
334}
335
336fn groups_to_json(groups: &[FileGroup]) -> serde_json::Value {
338 let entries: Vec<serde_json::Value> = groups
339 .iter()
340 .map(|g| {
341 serde_json::json!({
342 "name": g.core_name,
343 "core_file": g.core_file,
344 "member_count": g.members.len(),
345 "members": g.members,
346 })
347 })
348 .collect();
349 serde_json::Value::Array(entries)
350}