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::path::Path;
10
11/// Convert a module name (from filename) to a valid Zig identifier suffix.
12/// Non-ASCII characters are converted to Unicode codepoint format `_uXXXX`.
13pub fn sanitize_module_name(raw: &str) -> String {
14    let mut result = String::new();
15    for ch in raw.chars() {
16        if ch.is_ascii_alphanumeric() || ch == '_' {
17            result.push(ch);
18        } else {
19            result.push_str(&format!("_u{:04x}", ch as u32));
20        }
21    }
22    if result.is_empty() {
23        result.push_str("_unnamed");
24    }
25    if !result.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
26        result.insert(0, '_');
27    }
28    result
29}
30
31/// Strip `import` and `export` statements from JS source,
32/// and collect all exported function/var/class names.
33///
34/// Returns `(cleaned_source, exports_set)`.
35pub fn strip_imports_extract_exports(src: &str) -> (String, HashSet<String>) {
36    let mut result = String::with_capacity(src.len());
37    let mut exports = HashSet::new();
38
39    for line in src.lines() {
40        let trimmed = line.trim();
41
42        // Skip import statements entirely
43        if trimmed.starts_with("import ") {
44            continue;
45        }
46
47        // export function foo() → keep "function foo()", record "foo"
48        if let Some(rest) = trimmed.strip_prefix("export ") {
49            if let Some(after) = rest.strip_prefix("function ") {
50                if let Some(paren) = after.find('(') {
51                    exports.insert(after[..paren].trim().to_string());
52                }
53                // Keep the line without "export " prefix
54                result.push_str(rest);
55            } else if let Some(after) = rest.strip_prefix("async function ") {
56                if let Some(paren) = after.find('(') {
57                    exports.insert(after[..paren].trim().to_string());
58                }
59                result.push_str(rest);
60            } else if rest.starts_with("const ") || rest.starts_with("let ") || rest.starts_with("var ") {
61                let kw_len = if rest.starts_with("const ") { 6 } else { 4 };
62                if let Some(eq) = rest[kw_len..].find('=') {
63                    let name = rest[kw_len..kw_len + eq].trim();
64                    exports.insert(name.to_string());
65                }
66                result.push_str(rest);
67            } else if let Some(after_class) = rest.strip_prefix("class ") {
68                if let Some(br) = after_class.find([' ', '{']) {
69                    exports.insert(after_class[..br].trim().to_string());
70                }
71                result.push_str(rest);
72            } else if let Some(after_default) = rest.strip_prefix("default ") {
73                // export default function/class → unwrap, extract name
74                if let Some(after_fn) = after_default.strip_prefix("function ") {
75                    if let Some(paren) = after_fn.find('(') {
76                        let name = after_fn[..paren].trim();
77                        if !name.is_empty() {
78                            exports.insert(name.to_string());
79                        }
80                    }
81                } else if let Some(after_class) = after_default.strip_prefix("class ")
82                    && let Some(br) = after_class.find([' ', '{'])
83                {
84                    exports.insert(after_class[..br].trim().to_string());
85                }
86                result.push_str(after_default);
87            } else if rest.starts_with('{') {
88                // export { name1, name2, ... } — extract names, skip the whole line
89                if let Some(braces) = rest.strip_prefix('{')
90                    .and_then(|s| s.strip_suffix('}'))
91                    .or_else(|| rest.strip_prefix('{').and_then(|s| {
92                        // Multi-line export { ... } — try to find closing brace
93                        s.find('}').map(|i| &s[..i])
94                    }))
95                {
96                    for name in braces.split(',') {
97                        let name = name.trim();
98                        // Also handle `foo as bar` → export "bar" (the exported name)
99                        if let Some(alias) = name.strip_prefix("as ") {
100                            let alias = alias.trim();
101                            if !alias.is_empty() {
102                                exports.insert(alias.to_string());
103                            }
104                        } else if !name.is_empty() && !name.starts_with("as ") {
105                            exports.insert(name.to_string());
106                        }
107                    }
108                }
109                continue;
110            } else {
111                // export * or other unknown syntax — skip the whole line
112                continue;
113            }
114            result.push('\n');
115        } else {
116            result.push_str(line);
117            result.push('\n');
118        }
119    }
120
121    (result, exports)
122}
123
124/// Strip .js extension then sanitize for Zig identifier.
125fn sanitize_name(filename: &str) -> String {
126    let stem = filename.strip_suffix(".js").unwrap_or(filename);
127    sanitize_module_name(stem)
128}
129
130/// A file group: one core file + all files transitively imported by it.
131#[derive(Debug, Clone)]
132pub struct FileGroup {
133    /// Sanitized core file name (used as Zig project name).
134    pub core_name: String,
135    /// Original .js filename of the core file (e.g. "main.js").
136    pub core_file: String,
137    /// All .js filenames in this group (including core, in topological order).
138    pub members: Vec<String>,
139    /// Map: original filename → sanitzed Zig module name.
140    pub name_map: HashMap<String, String>,
141    /// Map: original filename → Vec<(imported_name, source_filename)>.
142    /// e.g. "main.js" → [("add","math.js"), ("multiply","math.js"), ("greet","string_utils.js")]
143    pub imported_names: HashMap<String, Vec<(String, String)>>,
144}
145
146/// Analyze a single core JS file and its transitive dependencies.
147///
148/// Only processes the specified core file and the files it imports,
149/// rather than scanning an entire directory.
150///
151/// # Returns
152/// - `groups`: Vec containing a single FileGroup.
153/// - `groups_json`: JSON-serializable summary for `out/groups.json`.
154pub fn analyze_single_group(in_dir: &str, core_file: &str) -> (Vec<FileGroup>, String) {
155    let in_path = Path::new(in_dir);
156
157    // 1. BFS/DFS from core_file to collect all transitively imported files.
158    let mut visited: HashSet<String> = HashSet::new();
159    let mut stack: Vec<String> = vec![core_file.to_string()];
160    let mut js_files: Vec<String> = Vec::new();
161
162    while let Some(cur) = stack.pop() {
163        if !visited.insert(cur.clone()) {
164            continue;
165        }
166        js_files.push(cur.clone());
167
168        let src = std::fs::read_to_string(in_path.join(&cur))
169            .unwrap_or_else(|e| panic!("Cannot read '{}': {}", cur, e));
170        let (file_imports, _exports, _decls, _file_imported_names) = extract_imports(&src, &cur);
171        for dep in &file_imports {
172            if !visited.contains(dep.as_str()) {
173                stack.push(dep.clone());
174            }
175        }
176    }
177
178    // 2. Parse each discovered file for imports + imported names.
179    let mut imports: HashMap<String, Vec<String>> = HashMap::new();
180    let mut imported_names: HashMap<String, Vec<(String, String)>> = HashMap::new();
181    let mut sanitzed: HashMap<String, String> = HashMap::new();
182
183    for file in &js_files {
184        let src = std::fs::read_to_string(in_path.join(file))
185            .unwrap_or_else(|e| panic!("Cannot read '{}': {}", file, e));
186        let (file_imports, _exports, _decls, file_imported_names) = extract_imports(&src, file);
187        imports.insert(file.clone(), file_imports);
188        imported_names.insert(file.clone(), file_imported_names);
189        sanitzed.insert(file.clone(), sanitize_name(file));
190    }
191
192    // 3. Build the single group.
193    let members = transitive_deps(core_file, &imports);
194    let core_name = sanitzed.get(core_file).cloned().unwrap_or_else(|| {
195        sanitize_name(core_file)
196    });
197
198    let group = FileGroup {
199        core_name: core_name.clone(),
200        core_file: core_file.to_string(),
201        members,
202        name_map: sanitzed,
203        imported_names,
204    };
205
206    let groups = vec![group];
207    let groups_json = serde_json::to_string_pretty(&groups_to_json(&groups))
208        .expect("Failed to serialize groups.json");
209
210    (groups, groups_json)
211}
212
213/// Compute transitive dependencies of `file` (including itself).
214fn transitive_deps(
215    file: &str,
216    imports: &HashMap<String, Vec<String>>,
217) -> Vec<String> {
218    let mut visited: HashSet<String> = HashSet::new();
219    let mut stack: Vec<String> = vec![file.to_string()];
220    let mut result: Vec<String> = Vec::new();
221
222    // DFS produces core-first order; reverse for topological (deps-first).
223    while let Some(cur) = stack.pop() {
224        if !visited.insert(cur.clone()) {
225            continue;
226        }
227        result.push(cur.clone());
228        if let Some(deps) = imports.get(&cur) {
229            for dep in deps {
230                if !visited.contains(dep.as_str()) {
231                    stack.push(dep.clone());
232                }
233            }
234        }
235    }
236    result.reverse();
237    result
238}
239
240/// Return type for extract_imports.
241type ImportMeta = (Vec<String>, Vec<String>, Vec<String>, Vec<(String, String)>);
242
243/// Extract `import { ... } from '...'` statements from JS source.
244///
245/// Returns (imported_files, exported_names, top_level_declarations, imported_names).
246///
247/// `imported_names`: Vec<(imported_name, source_filename)> — e.g. [("add","math.js"), ("multiply","math.js")]
248fn extract_imports(
249    src: &str,
250    _filename: &str,
251) -> ImportMeta {
252    // Use a simple regex-free approach: scan lines for "import" keyword.
253    let mut imported_files: Vec<String> = Vec::new();
254    let mut exported_names: Vec<String> = Vec::new();
255    let mut declarations: Vec<String> = Vec::new();
256    let mut imported_names: Vec<(String, String)> = Vec::new();
257
258    for line in src.lines() {
259        let trimmed = line.trim();
260
261        // import { foo, bar } from './math.js';
262        if trimmed.starts_with("import ")
263            && let Some(from_idx) = trimmed.find(" from ") {
264                // Extract the path
265                let specifier = &trimmed[from_idx + 6..];
266                let specifier = specifier.trim();
267                let path_str = if let Some(stripped) = specifier.strip_prefix('\'') {
268                    stripped.find('\'').map(|end| &stripped[..end])
269                } else if let Some(stripped) = specifier.strip_prefix('"') {
270                    stripped.find('"').map(|end| &stripped[..end])
271                } else {
272                    None
273                };
274
275                let source_filename = path_str
276                    .and_then(path_to_filename);
277
278                if let Some(ref sf) = source_filename {
279                    imported_files.push(sf.clone());
280                }
281
282                // Extract imported names from between `import ` and ` from `
283                let import_clause = &trimmed["import ".len()..from_idx].trim();
284                if let Some(brace_open) = import_clause.find('{')
285                    && let Some(brace_close) = import_clause[brace_open..].find('}')
286                {
287                    let names_str = &import_clause[brace_open + 1..brace_open + brace_close];
288                    for name in names_str.split(',') {
289                        let name = name.trim();
290                        if !name.is_empty()
291                            && let Some(ref sf) = source_filename
292                        {
293                            imported_names.push((name.to_string(), sf.clone()));
294                        }
295                    }
296                }
297            }
298
299        // export function foo() {}  or  export const foo = ...
300        if let Some(rest) = trimmed.strip_prefix("export ") {
301            if let Some(after) = rest.strip_prefix("function ") {
302                if let Some(name_end) = after.find('(') {
303                    exported_names.push(after[..name_end].trim().to_string());
304                }
305            } else if rest.starts_with("const ") || rest.starts_with("let ") || rest.starts_with("var ") {
306                // export const foo = ... → extract "foo"
307                let after = &rest[6..];
308                if let Some(eq) = after.find('=') {
309                    let name = after[..eq].trim();
310                    exported_names.push(name.to_string());
311                }
312            } else if let Some(after) = rest.strip_prefix("class ") {
313                if let Some(name_end) = after.find([' ', '{']) {
314                    exported_names.push(after[..name_end].trim().to_string());
315                }
316            } else if rest.starts_with("async function ")
317                && let Some(name_end) = rest[16..].find('(') {
318                    exported_names.push(rest[16..16 + name_end].trim().to_string());
319                }
320        }
321
322        // Top-level declarations (for conflict detection).
323        if trimmed.starts_with("function ") && !trimmed.starts_with("//")
324            && let Some(name_end) = trimmed[9..].find('(') {
325                declarations.push(trimmed[9..9 + name_end].trim().to_string());
326            }
327        if (trimmed.starts_with("const ") || trimmed.starts_with("let ") || trimmed.starts_with("var "))
328            && !trimmed.contains("export ")
329        {
330            let prefix = if trimmed.starts_with("const ") { 6 } else { 4 };
331            let after = &trimmed[prefix..];
332            if let Some(eq) = after.find('=') {
333                let name = after[..eq].trim();
334                declarations.push(name.to_string());
335            }
336        }
337    }
338
339    // Deduplicate.
340    imported_files.sort();
341    imported_files.dedup();
342    imported_names.sort();
343    imported_names.dedup();
344
345    (imported_files, exported_names, declarations, imported_names)
346}
347
348/// Convert an import path like './math.js' or './math' to a filename.
349fn path_to_filename(path: &str) -> Option<String> {
350    let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
351    if fname.ends_with(".js") {
352        Some(fname)
353    } else {
354        Some(format!("{}.js", fname))
355    }
356}
357
358/// Convert groups to JSON-serializable map.
359fn groups_to_json(groups: &[FileGroup]) -> serde_json::Value {
360    let entries: Vec<serde_json::Value> = groups
361        .iter()
362        .map(|g| {
363            serde_json::json!({
364                "name": g.core_name,
365                "core_file": g.core_file,
366                "member_count": g.members.len(),
367                "members": g.members,
368            })
369        })
370        .collect();
371    serde_json::Value::Array(entries)
372}