Skip to main content

js2zig_core/
analyzer.rs

1//! Dependency analyzer — scan all JS files, build import graph,
2//! and collect analysis results for the transpiler pipeline.
3//!
4//! The entry JS file and its transitive dependencies form a single
5//! project. Non-entry files can be imported by multiple dependents.
6
7use std::collections::{HashMap, HashSet};
8use std::fmt::{self, Write};
9use std::path::Path;
10
11use oxc_allocator::Allocator;
12use oxc_ast::ast::*;
13
14/// Convert a module name (from filename) to a valid Zig identifier suffix.
15/// Non-ASCII characters are converted to Unicode codepoint format `_uXXXX`.
16#[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    // Prevent collision with the Zig orchestrator file `lib.zig`
33    if result == "lib" {
34        result.push_str("_mod");
35    }
36    result
37}
38
39/// Strip .js extension then sanitize for Zig identifier.
40fn sanitize_name(filename: &str) -> String {
41    let stem = filename.strip_suffix(".js").unwrap_or(filename);
42    sanitize_module_name(stem)
43}
44
45/// Analysis result: the entry file + all its transitive dependencies,
46/// with parsed ASTs and import/export metadata.
47pub struct AnalysisResult {
48    /// Sanitized primary root file name (used as Zig project name).
49    pub entry_name: String,
50    /// All .js filenames in this project (including entry, in topological order).
51    pub members: Vec<String>,
52    /// Map: original filename → sanitized Zig module name.
53    pub name_map: HashMap<String, String>,
54    /// Map: original filename → Vec<(imported_name, source_filename)>.
55    /// e.g. "main.js" → [("add","math.js"), ("multiply","math.js"), ("greet","string_utils.js")]
56    pub imported_names: HashMap<String, Vec<(String, String)>>,
57    /// Map: original filename → exported function/var/class names (from AST).
58    pub exported_names: HashMap<String, HashSet<String>>,
59    /// Map: original filename → ALL toplevel function names (from AST, for test projects).
60    pub all_fn_names: HashMap<String, HashSet<String>>,
61    /// Cached source text per file (eliminates repeated I/O in the transpiler pipeline).
62    pub file_sources: HashMap<String, String>,
63    /// Parsed AST programs (one per file).  Allocators are leaked via Box::leak
64    /// so programs carry 'static lifetime — safe for a CLI transpiler where the
65    /// process exits shortly after.  Stored here so the Lowerer can reuse the AST
66    /// without re-parsing the source text.
67    pub parsed_programs: HashMap<String, Program<'static>>,
68}
69
70// Manual Debug: skip parsed_programs (AST is huge, not useful for debug output).
71impl fmt::Debug for AnalysisResult {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("AnalysisResult")
74            .field("entry_name", &self.entry_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
92/// Analyze JS root files and their transitive dependencies, returning
93/// all data needed for transpilation.
94///
95/// `js_files` must be non-empty; the first entry is the primary root whose
96/// sanitized stem becomes the project name. All entries are treated as
97/// starting points for dependency discovery.
98pub fn analyze_project(in_dir: &Path, js_files: &[String]) -> Result<AnalysisResult, String> {
99    assert!(!js_files.is_empty(), "js_files must not be empty");
100
101    let primary_root = &js_files[0];
102
103    // Single DFS pass: read + parse each file ONCE, extract import/export
104    // metadata straight from the AST, and cache both the source text and the
105    // parsed Program for Lowerer reuse (eliminates double-parsing).
106    let mut visited: HashSet<String> = HashSet::new();
107    let mut stack: Vec<String> = js_files.to_vec();
108    // Reverse so the primary root is popped first (we parse it first).
109    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            .map_err(|e| format!("Cannot read '{}': {}", cur, e))?;
126
127        // Parse ONCE: leak source for 'static lifetime, so the Program can be
128        // stored in the HashMap and reused by the Lowerer later.
129        // The oxc Allocator is shared across all files in this session (O(1) leak
130        // instead of O(n) — bumpalo arena is safe for concurrent AST storage,
131        // and the parse phase is single-threaded so the benign race on first
132        // init cannot actually occur in practice).
133        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                // SAFETY: ptr points to a leaked Box<Allocator> that lives for 'static
139                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    // Build the result — all files from all roots merged.
167    let members = transitive_deps_multi(js_files, &imports);
168    let entry_name = sanitized
169        .get(primary_root)
170        .cloned()
171        .unwrap_or_else(|| sanitize_name(primary_root));
172
173    Ok(AnalysisResult {
174        entry_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
185/// Compute transitive dependencies starting from multiple root files.
186/// All roots and their transitive deps are merged into one topological list.
187fn 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    // DFS produces core-first order; reverse for topological (deps-first).
193    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
210/// Convert an import path like './math.js' or './math' to a filename.
211fn 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
220/// AST-extracted metadata for a single JS module file.
221struct 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
228/// Extract import/export metadata from an oxc `Program` AST.
229/// Replaces the old line-scanning `extract_imports` with accurate AST traversal.
230fn 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                // `export function foo() {}` / `export const foo = ...` / `export class Foo {}`
262                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                // `export { foo, bar as baz }`
287                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                // `export default function foo() {}` → "foo"
295                // `export default class Foo {}` → "Foo"
296                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                // Detect `module.exports = { foo, bar, ... }` (CommonJS style)
316                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
339/// Extract exported names from `module.exports = { ... }` expression statement.
340/// Returns `Some(names)` if it's a CommonJS export pattern, `None` otherwise.
341fn 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    // Check left side: `module.exports`
349    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    // Check right side: `{ ... }`
364    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}