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