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 testgen;
8pub mod toml_config;
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// C ABI wrapper generation and metadata.
18pub mod cabi;
19
20/// ZigIR — structured intermediate representation between AST and Zig source.
21pub mod zigir;
22
23// ── Submodules ──
24pub(crate) mod infer;
25pub(crate) mod jsdoc;
26pub(crate) mod native_builtins;
27#[cfg(test)]
28pub(crate) mod tests;
29
30use std::path::PathBuf;
31
32/// Host function type for FFI binding generation.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum HostType {
35 Void,
36 Bool,
37 I32,
38 I64,
39 F64,
40 Str, // *const c_char
41}
42
43/// Host function description for FFI binding generation.
44#[derive(Debug, Clone)]
45pub struct HostFunction {
46 pub name: String,
47 pub params: Vec<HostType>,
48 pub return_type: Option<HostType>,
49 /// Whether this is an async function (called with `await` from JS).
50 pub is_async: bool,
51 /// For async functions returning a struct: field name and type pairs.
52 /// Empty for sync functions or async functions with simple return types.
53 pub async_return_fields: Vec<(String, HostType)>,
54}
55
56impl HostFunction {
57 /// Derive a PascalCase struct name from the function name.
58 /// e.g. "fetch_user" → "FetchUserResult"
59 pub fn struct_zig_name(&self) -> String {
60 format!("{}Result", toml_config::pascal_case(&self.name))
61 }
62
63 /// Derive the C ABI extern struct name.
64 /// e.g. "fetch_user" → "HostFetchUserResult"
65 pub fn struct_c_name(&self) -> String {
66 format!("Host{}", self.struct_zig_name())
67 }
68}
69
70impl HostType {
71 /// Convert to the clean Zig type string used in wrapper structs.
72 pub fn to_zig_field_type(self) -> &'static str {
73 match self {
74 HostType::Void => "void",
75 HostType::Bool => "bool",
76 HostType::I32 => "i32",
77 HostType::I64 => "i64",
78 HostType::F64 => "f64",
79 HostType::Str => "[]const u8",
80 }
81 }
82
83 /// Convert to the C ABI type string used in extern structs.
84 pub fn to_c_field_type(self) -> &'static str {
85 match self {
86 HostType::Void => "void",
87 HostType::Bool => "bool",
88 HostType::I32 => "i32",
89 HostType::I64 => "i64",
90 HostType::F64 => "f64",
91 HostType::Str => "[256]u8",
92 }
93 }
94}
95
96/// Host function configuration.
97#[derive(Debug, Clone)]
98pub struct HostConfig {
99 pub functions: Vec<HostFunction>,
100}
101
102/// Build behavior configuration.
103#[derive(Debug, Clone, Default)]
104pub struct BuildConfig {
105 /// Force rebuild (skip incremental cache).
106 pub force_rebuild: bool,
107 /// Whether to run `zig build` after transpilation.
108 pub run_zig_build: bool,
109 /// Zig optimization level passed as `-Doptimize=...` to `zig build`.
110 ///
111 /// Valid values: `"Debug"`, `"ReleaseSafe"`, `"ReleaseFast"`, `"ReleaseSmall"`.
112 /// If `None`, the caller should infer from the Cargo profile automatically.
113 pub zig_optimize: Option<String>,
114 /// When true, the caller is a Cargo build script (`build.rs`).
115 /// This controls progress output only (project headers, cache status,
116 /// "Generated:" paths, "zig build: OK", etc.) which Cargo filters
117 /// and prefixes with `[package]`.
118 ///
119 /// Diagnostic output (errors, warnings, @compileError messages) is
120 /// always shown regardless of this flag, so users see actionable
121 /// information even in proc-macro context.
122 ///
123 /// When false (proc-macro context), only diagnostics are emitted;
124 /// progress noise is suppressed because proc-macro stdout leaks
125 /// directly to the terminal unfiltered.
126 pub is_build_script: bool,
127}
128
129/// Multi-file project configuration.
130#[derive(Debug, Clone)]
131pub struct ProjectConfig {
132 /// Absolute path to the directory containing JS source files (e.g. `.../js_src/`).
133 pub js_dir: PathBuf,
134 /// JS entry file names (relative to `js_dir`).
135 /// The first entry is the primary root; additional entries are extra roots
136 /// whose exports become C ABI-exportable.
137 pub js_files: Vec<String>,
138 /// Output directory path (typically $OUT_DIR).
139 pub out_dir: PathBuf,
140 /// Host function configuration (optional).
141 pub host_config: Option<HostConfig>,
142 /// Build behavior configuration.
143 pub build: BuildConfig,
144}
145
146impl Default for ProjectConfig {
147 fn default() -> Self {
148 Self {
149 js_dir: PathBuf::from("."),
150 js_files: vec!["main.js".to_string()],
151 out_dir: PathBuf::from("out"),
152 host_config: None,
153 build: BuildConfig::default(),
154 }
155 }
156}
157
158/// Result of transpiling a project.
159#[derive(Debug, Default)]
160pub struct ProjectResult {
161 /// Sanitized project name (derived from entry file stem).
162 pub project_name: String,
163 /// Whether this is a test project (entry file starts with "test_").
164 pub is_test: bool,
165 /// C ABI export metadata (serialized JSON).
166 pub cabi_exports_json: String,
167 /// Diagnostic messages.
168 pub diagnostics: Vec<String>,
169}
170
171// ── Public API ───────────────────────────────────────────────────
172
173/// Multi-file project transpilation: JS entry file → Zig project + cabi_exports.json.
174///
175/// The entry JS file and its transitive imports form a single project.
176/// Does NOT run `zig build` (unless `config.build.run_zig_build == true`).
177///
178/// `js_dir` is the absolute path to the directory containing JS source files.
179/// `js_files` are filenames relative to `js_dir`; the first entry is the
180/// primary entry point whose stem becomes the project name.
181pub fn transpile_project(config: &ProjectConfig) -> Result<ProjectResult, String> {
182 pipeline::transpile_project(config)
183}
184
185pub use cabi::write_cabi_metadata;