Skip to main content

js2rust_bridge/
lib.rs

1// js2rust-bridge: Facade crate for the js2rust_bridge! proc-macro.
2//
3// Users only need to depend on this single crate:
4//
5// ```toml
6// [dependencies]
7// js2rust-bridge = "0.3"
8// [build-dependencies]
9// js2rust-bridge = "0.3"
10// ```
11//
12// The macro transpiles JS to Zig and generates Rust FFI bindings in one step.
13// Call `js2rust_bridge::build()` from your `build.rs` to transpile, compile,
14// and link the Zig static libraries.  The proc-macro detects an up-to-date cache
15// and skips re-transpilation automatically.
16//
17// Both `js2rust_bridge!()` and `build()` read from a single `js2rust.toml`
18// in the crate root — no duplicated configuration.
19
20mod config;
21pub mod native_regex;
22pub mod sdk;
23
24pub use js2rust_bridge_macro::{host_fn, js2rust_bridge};
25
26// Re-export types needed for host function configuration from js2zig-core
27// so users only need `js2rust-bridge` in their `[build-dependencies]`.
28pub use js2zig_core::{HostConfig, HostFunction, HostType};
29
30// Re-export config types for programmatic use.
31pub use config::{HostFnToml, Js2rustConfig, ProjectSection};
32
33use std::path::PathBuf;
34
35/// Build: transpile JS → Zig, compile Zig static library, and emit linker directives.
36///
37/// Reads configuration from `js2rust.toml` in the crate root.  Call this from
38/// your `build.rs` with zero arguments:
39///
40/// ```rust,ignore
41/// fn main() {
42///     js2rust_bridge::build();
43/// }
44/// ```
45///
46/// The group name is derived automatically from the file stem of `project.js_file`.
47pub fn build(force_rebuild: bool) {
48    let config = Js2rustConfig::from_manifest_dir();
49    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
50    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
51
52    let js_file_path = PathBuf::from(&manifest_dir).join(&config.project.js_file);
53    let additional_js_paths: Vec<PathBuf> = config
54        .project
55        .additional_js_files
56        .iter()
57        .map(|p| PathBuf::from(&manifest_dir).join(p))
58        .collect();
59
60    let group_name = config.group_name();
61
62    let host_config = if config.host_functions.is_empty() {
63        None
64    } else {
65        Some(build_host_config(&config))
66    };
67
68    let project_config = js2zig_core::ProjectConfig {
69        name: group_name,
70        js_file: js_file_path,
71        additional_js_files: additional_js_paths,
72        out_dir: cache_dir.clone(),
73        host_config,
74        force_rebuild,
75        run_zig_build: true,
76    };
77
78    match js2zig_core::transpile_project(&project_config) {
79        Ok(_result) => {
80            link_from_cache(&cache_dir);
81        }
82        Err(e) => {
83            panic!("js2rust_bridge::build: transpilation/zig build failed: {e}");
84        }
85    }
86}
87
88/// Fallback: scan `.js2zig-cache/` and emit link directives without running
89/// transpilation or zig build.  Used when the proc-macro already did the work.
90pub fn link() {
91    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
92    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
93    link_from_cache(&cache_dir);
94}
95
96/// Scan `.js2zig-cache/` for compiled static libraries and emit link directives.
97fn link_from_cache(cache_dir: &std::path::Path) {
98    if !cache_dir.exists() {
99        println!(
100            "cargo:warning=js2zig: .js2zig-cache not found. \
101             Run `cargo build` twice on a clean checkout."
102        );
103        return;
104    }
105
106    let mut found = false;
107    if let Ok(entries) = std::fs::read_dir(cache_dir) {
108        for entry in entries.flatten() {
109            let group_dir = entry.path();
110            let lib_dir = group_dir.join("zig-out").join("lib");
111
112            if lib_dir.exists()
113                && let Some(group_name) = entry.file_name().to_str()
114            {
115                if group_name == "host.zig" || group_name == "groups.json" {
116                    continue;
117                }
118                println!("cargo:rustc-link-search=native={}", lib_dir.display());
119                println!("cargo:rustc-link-lib=static={}", group_name);
120                found = true;
121            }
122        }
123    }
124
125    if !found {
126        println!(
127            "cargo:warning=js2zig: no compiled libraries found in {}. \
128             Run `cargo build` twice on a clean checkout.",
129            cache_dir.display()
130        );
131    }
132}
133
134/// Convert `Js2rustConfig.host_functions` to `HostConfig`.
135fn build_host_config(config: &Js2rustConfig) -> HostConfig {
136    let functions: Vec<HostFunction> = config
137        .host_functions
138        .iter()
139        .map(|hf| {
140            let params: Vec<HostType> = hf
141                .params
142                .iter()
143                .map(|t| type_name_to_host_type(t))
144                .collect();
145
146            let return_type = hf.returns.as_deref().and_then(|t| {
147                if t == "void" {
148                    None
149                } else {
150                    Some(type_name_to_host_type(t))
151                }
152            });
153
154            let async_return_fields: Vec<(String, HostType)> = hf
155                .async_returns
156                .iter()
157                .map(|(name, ty)| (name.clone(), type_name_to_host_type(ty)))
158                .collect();
159
160            HostFunction {
161                name: hf.name.clone(),
162                params,
163                return_type,
164                is_async: hf.is_async,
165                async_return_fields,
166            }
167        })
168        .collect();
169
170    HostConfig { functions }
171}
172
173fn type_name_to_host_type(name: &str) -> HostType {
174    match name {
175        "i64" => HostType::I64,
176        "i32" => HostType::I32,
177        "f64" => HostType::F64,
178        "bool" => HostType::Bool,
179        "str" => HostType::Str,
180        "void" => HostType::Void,
181        other => panic!(
182            "js2rust.toml: unknown host type '{}'. Valid types: i64, i32, f64, bool, str, void",
183            other
184        ),
185    }
186}