Skip to main content

js2zig_core/
analyzer.rs

1//! Dependency analyzer — scan all JS files, build import graph,
2//! and partition files into groups (one core file + its transitive deps).
3//!
4//! A "core file" is a file that is NOT imported by any other file.
5//! Each core file becomes the root of a group. Non-core files can
6//! belong to multiple groups.
7
8use std::collections::{HashMap, HashSet};
9use std::fmt::{self, Write};
10use std::path::Path;
11
12use oxc_allocator::Allocator;
13use oxc_ast::ast::*;
14
15/// Convert a module name (from filename) to a valid Zig identifier suffix.
16/// Non-ASCII characters are converted to Unicode codepoint format `_uXXXX`.
17#[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    // Prevent collision with the Zig orchestrator file `lib.zig`
34    if result == "lib" {
35        result.push_str("_mod");
36    }
37    result
38}
39
40/// Strip .js extension then sanitize for Zig identifier.
41fn sanitize_name(filename: &str) -> String {
42    let stem = filename.strip_suffix(".js").unwrap_or(filename);
43    sanitize_module_name(stem)
44}
45
46/// A file group: one core file + all files transitively imported by it.
47pub struct FileGroup {
48    /// Sanitized core file name (used as Zig project name).
49    pub core_name: String,
50    /// Original .js filename of the core file (e.g. "main.js").
51    pub core_file: String,
52    /// All .js filenames in this group (including core, in topological order).
53    pub members: Vec<String>,
54    /// Map: original filename → sanitzed Zig module name.
55    pub name_map: HashMap<String, String>,
56    /// Map: original filename → Vec<(imported_name, source_filename)>.
57    /// e.g. "main.js" → [("add","math.js"), ("multiply","math.js"), ("greet","string_utils.js")]
58    pub imported_names: HashMap<String, Vec<(String, String)>>,
59    /// Map: original filename → exported function/var/class names (from AST).
60    pub exported_names: HashMap<String, HashSet<String>>,
61    /// Map: original filename → ALL toplevel function names (from AST, for test groups).
62    pub all_fn_names: HashMap<String, HashSet<String>>,
63    /// Cached source text per file (eliminates repeated I/O in the transpiler pipeline).
64    pub file_sources: HashMap<String, String>,
65    /// Parsed AST programs (one per file).  Allocators are leaked via Box::leak
66    /// so programs carry 'static lifetime — safe for a CLI transpiler where the
67    /// process exits shortly after.  Stored here so the Lowerer can reuse the AST
68    /// without re-parsing the source text.
69    pub parsed_programs: HashMap<String, Program<'static>>,
70}
71
72// Manual Debug: skip parsed_programs (AST is huge, not useful for debug output).
73impl 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
95/// Analyze a single core JS file (and optional additional roots) and their
96/// transitive dependencies, merging everything into one group.
97///
98/// Only processes the specified core file(s) and the files they import,
99/// rather than scanning an entire directory.
100///
101/// # Returns
102/// - `groups`: Vec containing a single FileGroup.
103/// - `groups_json`: JSON-serializable summary for `out/groups.json`.
104pub 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    // Single DFS pass: read + parse each file ONCE, extract import/export
112    // metadata straight from the AST, and cache both the source text and the
113    // parsed Program for Lowerer reuse (eliminates double-parsing).
114    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    // Reverse so the primary core_file is popped first (we parse it first).
120    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        // Parse ONCE: leak source for 'static lifetime, so the Program can be
139        // stored in the HashMap and reused by the Lowerer later.
140        // The oxc Allocator is shared across all files in this session (O(1) leak
141        // instead of O(n) — bumpalo arena is safe for concurrent AST storage,
142        // and the parse phase is single-threaded so the benign race on first
143        // init cannot actually occur in practice).
144        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                // SAFETY: ptr points to a leaked Box<Allocator> that lives for 'static
150                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    // Build the single group — all files from all roots merged.
178    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
206/// Compute transitive dependencies starting from multiple root files.
207/// All roots and their transitive deps are merged into one topological list.
208fn 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    // DFS produces core-first order; reverse for topological (deps-first).
214    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
231/// Convert an import path like './math.js' or './math' to a filename.
232fn 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
241/// AST-extracted metadata for a single JS module file.
242struct 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
249/// Extract import/export metadata from an oxc `Program` AST.
250/// Replaces the old line-scanning `extract_imports` with accurate AST traversal.
251fn 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                // `export function foo() {}` / `export const foo = ...` / `export class Foo {}`
283                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                // `export { foo, bar as baz }`
308                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                // `export default function foo() {}` → "foo"
316                // `export default class Foo {}` → "Foo"
317                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                // Detect `module.exports = { foo, bar, ... }` (CommonJS style)
337                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
360/// Extract exported names from `module.exports = { ... }` expression statement.
361/// Returns `Some(names)` if it's a CommonJS export pattern, `None` otherwise.
362fn 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    // Check left side: `module.exports`
370    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    // Check right side: `{ ... }`
385    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
404/// Convert groups to JSON-serializable map.
405fn 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}