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 codegen pass).
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 codegen 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 codegen 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 allocator + source for 'static lifetime, so the
139        // Program can be stored in the HashMap and reused by codegen later.
140        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    // Build the single group — all files from all roots merged.
162    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
190/// Compute transitive dependencies starting from multiple root files.
191/// All roots and their transitive deps are merged into one topological list.
192fn 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    // DFS produces core-first order; reverse for topological (deps-first).
198    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
215/// Convert an import path like './math.js' or './math' to a filename.
216fn 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
225/// AST-extracted metadata for a single JS module file.
226struct 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
233/// Extract import/export metadata from an oxc `Program` AST.
234/// Replaces the old line-scanning `extract_imports` with accurate AST traversal.
235fn 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                // `export function foo() {}` / `export const foo = ...` / `export class Foo {}`
267                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                // `export { foo, bar as baz }`
292                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                // `export default function foo() {}` → "foo"
300                // `export default class Foo {}` → "Foo"
301                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
336/// Convert groups to JSON-serializable map.
337fn 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}