Skip to main content

js2zig_core/
lib.rs

1// js2zig-core: public API + module declarations.
2
3pub mod analyzer;
4pub mod host;
5pub mod parser;
6pub mod project;
7pub mod sourcemap;
8pub mod testgen;
9pub mod types;
10
11/// Native-type system transpilation (anytype + @TypeOf).
12pub mod native_proto;
13
14// Pipeline module: transpile_project() orchestration.
15pub mod pipeline;
16
17/// ZigIR — structured intermediate representation between AST and Zig source.
18pub mod zigir;
19
20// ── Submodules ──
21pub(crate) mod infer;
22pub(crate) mod jsdoc;
23pub(crate) mod native_builtins;
24#[cfg(test)]
25pub(crate) mod tests;
26
27use std::path::PathBuf;
28
29/// Host function type for FFI binding generation.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum HostType {
32    Void,
33    Bool,
34    I32,
35    I64,
36    F64,
37    Str, // *const c_char
38}
39
40/// Host function description for FFI binding generation.
41#[derive(Debug, Clone)]
42pub struct HostFunction {
43    pub name: String,
44    pub params: Vec<HostType>,
45    pub return_type: Option<HostType>,
46    /// Whether this is an async function (called with `await` from JS).
47    pub is_async: bool,
48    /// For async functions returning a struct: field name and type pairs.
49    /// Empty for sync functions or async functions with simple return types.
50    pub async_return_fields: Vec<(String, HostType)>,
51}
52
53impl HostFunction {
54    /// Derive a PascalCase struct name from the function name.
55    /// e.g. "fetch_user" → "FetchUserResult"
56    pub fn struct_zig_name(&self) -> String {
57        let pascal: String = self
58            .name
59            .split('_')
60            .map(|word| {
61                let mut chars = word.chars();
62                match chars.next() {
63                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
64                    None => String::new(),
65                }
66            })
67            .collect();
68        format!("{}Result", pascal)
69    }
70
71    /// Derive the C ABI extern struct name.
72    /// e.g. "fetch_user" → "HostFetchUserResult"
73    pub fn struct_c_name(&self) -> String {
74        format!("Host{}", self.struct_zig_name())
75    }
76}
77
78impl HostType {
79    /// Convert to the clean Zig type string used in wrapper structs.
80    pub fn to_zig_field_type(self) -> &'static str {
81        match self {
82            HostType::Void => "void",
83            HostType::Bool => "bool",
84            HostType::I32 => "i32",
85            HostType::I64 => "i64",
86            HostType::F64 => "f64",
87            HostType::Str => "[]const u8",
88        }
89    }
90
91    /// Convert to the C ABI type string used in extern structs.
92    pub fn to_c_field_type(self) -> &'static str {
93        match self {
94            HostType::Void => "void",
95            HostType::Bool => "bool",
96            HostType::I32 => "i32",
97            HostType::I64 => "i64",
98            HostType::F64 => "f64",
99            HostType::Str => "[256]u8",
100        }
101    }
102}
103
104/// Host function configuration.
105#[derive(Debug, Clone)]
106pub struct HostConfig {
107    pub functions: Vec<HostFunction>,
108}
109
110/// Multi-file project configuration.
111#[derive(Debug, Clone)]
112pub struct ProjectConfig {
113    /// Project name (also used as Zig library name).
114    pub name: String,
115    /// Core JS source file path (the entry point; its imports are pulled in transitively).
116    pub js_file: PathBuf,
117    /// Additional core JS files (multi-root: all roots + their transitive deps → one group).
118    pub additional_js_files: Vec<PathBuf>,
119    /// Output directory path (typically $OUT_DIR).
120    pub out_dir: PathBuf,
121    /// Host function configuration (optional).
122    pub host_config: Option<HostConfig>,
123    /// Force rebuild (skip incremental cache).
124    pub force_rebuild: bool,
125    /// Whether to run `zig build` after transpilation.
126    pub run_zig_build: bool,
127}
128
129impl Default for ProjectConfig {
130    fn default() -> Self {
131        Self {
132            name: "js2zig_lib".into(),
133            js_file: PathBuf::from("main.js"),
134            additional_js_files: Vec::new(),
135            out_dir: PathBuf::from("out"),
136            host_config: None,
137            force_rebuild: false,
138            run_zig_build: false,
139        }
140    }
141}
142
143/// Result of transpiling a single group.
144#[derive(Debug, Clone)]
145pub struct GroupResult {
146    /// Group name (e.g. "main", "utils").
147    pub name: String,
148    /// Whether this is a test group.
149    pub is_test: bool,
150    /// C ABI export metadata (serialized JSON).
151    pub cabi_exports_json: String,
152    /// Diagnostic messages.
153    pub diagnostics: Vec<String>,
154    /// Generated file paths.
155    pub output_files: Vec<PathBuf>,
156}
157
158/// Result of transpiling a project (all groups).
159#[derive(Debug, Default)]
160pub struct ProjectResult {
161    /// Per-group results.
162    pub groups: Vec<GroupResult>,
163    /// Global diagnostic messages.
164    pub diagnostics: Vec<String>,
165}
166
167// ── Public API ───────────────────────────────────────────────────
168
169/// Multi-file project transpilation: JS core file → Zig project + cabi_exports.json.
170///
171/// The core JS file and its transitive imports form a single group.
172/// Does NOT run `zig build` (unless `config.run_zig_build == true`).
173pub fn transpile_project(config: &ProjectConfig) -> Result<ProjectResult, String> {
174    pipeline::transpile_project(config)
175}
176
177/// Write C ABI metadata for a single group project.
178/// (Kept for backward compatibility; called from `pipeline.rs`.)
179pub fn write_cabi_metadata(
180    out_dir: &std::path::Path,
181    group_name: &str,
182    cabi_exports: &[native_proto::NativeCabiExport],
183    host_fns: &host::HostFnRegistry,
184    include_init: bool,
185) {
186    pipeline::write_cabi_metadata(out_dir, group_name, cabi_exports, host_fns, include_init)
187}