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 all JS files in `in_dir` and return file groups.
147///
148/// # Returns
149/// - `groups`: Vec of FileGroup, one per core file.
150/// - `groups_json`: JSON-serializable summary for `out/groups.json`.
151pub fn analyze_groups(in_dir: &str) -> (Vec<FileGroup>, String) {
152    let in_path = Path::new(in_dir);
153
154    // 1. Discover all .js files.
155    let js_files: Vec<String> = std::fs::read_dir(in_path)
156        .unwrap_or_else(|e| panic!("Cannot read in_dir '{}': {}", in_dir, e))
157        .filter_map(|entry| {
158            let entry = entry.ok()?;
159            let path = entry.path();
160            if path.extension()? == "js" {
161                Some(path.file_name()?.to_string_lossy().to_string())
162            } else {
163                None
164            }
165        })
166        .collect();
167
168    // 2. Parse each file → extract imports, exports, and imported names.
169    let mut imports: HashMap<String, Vec<String>> = HashMap::new();
170    let mut imported_names: HashMap<String, Vec<(String, String)>> = HashMap::new();
171    let mut sanitzed: HashMap<String, String> = HashMap::new();
172
173    for file in &js_files {
174        let src = std::fs::read_to_string(in_path.join(file))
175            .unwrap_or_else(|e| panic!("Cannot read '{}': {}", file, e));
176        let (file_imports, _exports, _decls, file_imported_names) = extract_imports(&src, file);
177        imports.insert(file.clone(), file_imports);
178        imported_names.insert(file.clone(), file_imported_names);
179        sanitzed.insert(file.clone(), sanitize_name(file));
180    }
181
182    // 3. Build reverse dependency map: who imports F?
183    let mut imported_by: HashMap<String, Vec<String>> = HashMap::new();
184    for (importer, deps) in &imports {
185        for dep in deps {
186            imported_by
187                .entry(dep.clone())
188                .or_default()
189                .push(importer.clone());
190        }
191    }
192
193    // 4. Core files = files NOT imported by any other file.
194    let core_files: Vec<String> = js_files
195        .iter()
196        .filter(|f| {
197            imported_by
198                .get(*f)
199                .is_none_or(|importers| importers.is_empty())
200        })
201        .cloned()
202        .collect();
203
204    // 5. For each core file, compute transitive closure.
205    let mut groups: Vec<FileGroup> = Vec::new();
206    for core in &core_files {
207        let members = transitive_deps(core, &imports);
208        let core_name = sanitzed.get(core).cloned().unwrap_or_else(|| {
209            sanitize_name(core)
210        });
211        let name_map = sanitzed.clone();
212
213        groups.push(FileGroup {
214            core_name: core_name.clone(),
215            core_file: core.clone(),
216            members,
217            name_map,
218            imported_names: imported_names.clone(),
219        });
220    }
221
222    // 6. Serialize groups.json.
223    let groups_json = serde_json::to_string_pretty(&groups_to_json(&groups))
224        .expect("Failed to serialize groups.json");
225
226    (groups, groups_json)
227}
228
229/// Compute transitive dependencies of `file` (including itself).
230fn transitive_deps(
231    file: &str,
232    imports: &HashMap<String, Vec<String>>,
233) -> Vec<String> {
234    let mut visited: HashSet<String> = HashSet::new();
235    let mut stack: Vec<String> = vec![file.to_string()];
236    let mut result: Vec<String> = Vec::new();
237
238    // DFS produces core-first order; reverse for topological (deps-first).
239    while let Some(cur) = stack.pop() {
240        if !visited.insert(cur.clone()) {
241            continue;
242        }
243        result.push(cur.clone());
244        if let Some(deps) = imports.get(&cur) {
245            for dep in deps {
246                if !visited.contains(dep.as_str()) {
247                    stack.push(dep.clone());
248                }
249            }
250        }
251    }
252    result.reverse();
253    result
254}
255
256/// Return type for extract_imports.
257type ImportMeta = (Vec<String>, Vec<String>, Vec<String>, Vec<(String, String)>);
258
259/// Extract `import { ... } from '...'` statements from JS source.
260///
261/// Returns (imported_files, exported_names, top_level_declarations, imported_names).
262///
263/// `imported_names`: Vec<(imported_name, source_filename)> — e.g. [("add","math.js"), ("multiply","math.js")]
264fn extract_imports(
265    src: &str,
266    _filename: &str,
267) -> ImportMeta {
268    // Use a simple regex-free approach: scan lines for "import" keyword.
269    let mut imported_files: Vec<String> = Vec::new();
270    let mut exported_names: Vec<String> = Vec::new();
271    let mut declarations: Vec<String> = Vec::new();
272    let mut imported_names: Vec<(String, String)> = Vec::new();
273
274    for line in src.lines() {
275        let trimmed = line.trim();
276
277        // import { foo, bar } from './math.js';
278        if trimmed.starts_with("import ")
279            && let Some(from_idx) = trimmed.find(" from ") {
280                // Extract the path
281                let specifier = &trimmed[from_idx + 6..];
282                let specifier = specifier.trim();
283                let path_str = if let Some(stripped) = specifier.strip_prefix('\'') {
284                    stripped.find('\'').map(|end| &stripped[..end])
285                } else if let Some(stripped) = specifier.strip_prefix('"') {
286                    stripped.find('"').map(|end| &stripped[..end])
287                } else {
288                    None
289                };
290
291                let source_filename = path_str
292                    .and_then(path_to_filename);
293
294                if let Some(ref sf) = source_filename {
295                    imported_files.push(sf.clone());
296                }
297
298                // Extract imported names from between `import ` and ` from `
299                let import_clause = &trimmed["import ".len()..from_idx].trim();
300                if let Some(brace_open) = import_clause.find('{')
301                    && let Some(brace_close) = import_clause[brace_open..].find('}')
302                {
303                    let names_str = &import_clause[brace_open + 1..brace_open + brace_close];
304                    for name in names_str.split(',') {
305                        let name = name.trim();
306                        if !name.is_empty()
307                            && let Some(ref sf) = source_filename
308                        {
309                            imported_names.push((name.to_string(), sf.clone()));
310                        }
311                    }
312                }
313            }
314
315        // export function foo() {}  or  export const foo = ...
316        if let Some(rest) = trimmed.strip_prefix("export ") {
317            if let Some(after) = rest.strip_prefix("function ") {
318                if let Some(name_end) = after.find('(') {
319                    exported_names.push(after[..name_end].trim().to_string());
320                }
321            } else if rest.starts_with("const ") || rest.starts_with("let ") || rest.starts_with("var ") {
322                // export const foo = ... → extract "foo"
323                let after = &rest[6..];
324                if let Some(eq) = after.find('=') {
325                    let name = after[..eq].trim();
326                    exported_names.push(name.to_string());
327                }
328            } else if let Some(after) = rest.strip_prefix("class ") {
329                if let Some(name_end) = after.find([' ', '{']) {
330                    exported_names.push(after[..name_end].trim().to_string());
331                }
332            } else if rest.starts_with("async function ")
333                && let Some(name_end) = rest[16..].find('(') {
334                    exported_names.push(rest[16..16 + name_end].trim().to_string());
335                }
336        }
337
338        // Top-level declarations (for conflict detection).
339        if trimmed.starts_with("function ") && !trimmed.starts_with("//")
340            && let Some(name_end) = trimmed[9..].find('(') {
341                declarations.push(trimmed[9..9 + name_end].trim().to_string());
342            }
343        if (trimmed.starts_with("const ") || trimmed.starts_with("let ") || trimmed.starts_with("var "))
344            && !trimmed.contains("export ")
345        {
346            let prefix = if trimmed.starts_with("const ") { 6 } else { 4 };
347            let after = &trimmed[prefix..];
348            if let Some(eq) = after.find('=') {
349                let name = after[..eq].trim();
350                declarations.push(name.to_string());
351            }
352        }
353    }
354
355    // Deduplicate.
356    imported_files.sort();
357    imported_files.dedup();
358    imported_names.sort();
359    imported_names.dedup();
360
361    (imported_files, exported_names, declarations, imported_names)
362}
363
364/// Convert an import path like './math.js' or './math' to a filename.
365fn path_to_filename(path: &str) -> Option<String> {
366    let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
367    if fname.ends_with(".js") {
368        Some(fname)
369    } else {
370        Some(format!("{}.js", fname))
371    }
372}
373
374/// Convert groups to JSON-serializable map.
375fn groups_to_json(groups: &[FileGroup]) -> serde_json::Value {
376    let entries: Vec<serde_json::Value> = groups
377        .iter()
378        .map(|g| {
379            serde_json::json!({
380                "name": g.core_name,
381                "core_file": g.core_file,
382                "member_count": g.members.len(),
383                "members": g.members,
384            })
385        })
386        .collect();
387    serde_json::Value::Array(entries)
388}