Skip to main content

js2zig_core/
lib.rs

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