use proc_macro::{TokenStream, TokenTree};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
const MANIFEST_SCHEMA_VERSION: i64 = 1;
const DEFAULT_CONFIG: &str = "js2rust.toml";
#[proc_macro]
pub fn bridge(input: TokenStream) -> TokenStream {
let manifest_dir = PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()),
);
let expanded = match run_bridge(input, &manifest_dir) {
Ok(code) => code,
Err(msg) => format!("compile_error!({:?});", msg),
};
expanded
.parse::<TokenStream>()
.expect("bridge! emitted invalid Rust code — this is a macro bug")
}
fn run_bridge(input: TokenStream, manifest_dir: &Path) -> Result<String, String> {
let config_rel = parse_args(input)?;
let (_config_abs, output_dir) = resolve_paths(manifest_dir, &config_rel)?;
let summary = validate_output(&output_dir)?;
debug_assert!(
summary.handler_count > 0,
"bridge!: manifest.json declares 0 handlers — did the codegen run find the corpus?"
);
emit_bridge(manifest_dir, &output_dir)
}
fn parse_args(input: TokenStream) -> Result<String, String> {
const USAGE: &str = "supported syntax: bridge! { config: \"js2rust.toml\" } (config optional)";
let mut config: Option<String> = None;
let mut it = input.into_iter().peekable();
while let Some(tok) = it.next() {
match tok {
TokenTree::Punct(p) if p.as_char() == ',' => continue,
TokenTree::Ident(id) => {
if id.to_string() != "config" {
return Err(format!("bridge!: unknown key `{id}` — {USAGE}"));
}
match (it.next(), it.next()) {
(Some(TokenTree::Punct(c)), Some(TokenTree::Literal(lit)))
if c.as_char() == ':' =>
{
if config.is_some() {
return Err(format!("bridge!: duplicate key `config` — {USAGE}"));
}
config = Some(parse_str_literal(&lit.to_string())?);
}
_ => return Err(format!("bridge!: expected `: \"<path>\"` after `config` — {USAGE}")),
}
}
other => {
return Err(format!("bridge!: unexpected token `{other}` — {USAGE}"));
}
}
}
Ok(config.unwrap_or_else(|| DEFAULT_CONFIG.to_string()))
}
fn parse_str_literal(raw: &str) -> Result<String, String> {
let Some(inner) = raw.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else {
return Err(format!(
"bridge!: config value must be a plain string literal, got `{raw}`"
));
};
Ok(inner.replace("\\\\", "\u{0}").replace("\\\"", "\"").replace('\u{0}', "\\"))
}
pub(crate) fn resolve_paths(
manifest_dir: &Path,
config_rel: &str,
) -> Result<(PathBuf, PathBuf), String> {
let config_abs = manifest_dir.join(config_rel);
if !config_abs.is_file() {
return Err(format!(
"js2rust config not found: {} (CARGO_MANIFEST_DIR + {config_rel})",
config_abs.display()
));
}
let text = std::fs::read_to_string(&config_abs)
.map_err(|e| format!("read {}: {e}", config_abs.display()))?;
let tbl: toml::Table = toml::from_str(&text)
.map_err(|e| format!("parse {}: {e}", config_abs.display()))?;
let out_dir = tbl
.get("output")
.and_then(|o| o.get("dir"))
.and_then(|d| d.as_str())
.unwrap_or("output")
.to_string();
let base_dir = config_abs.parent().unwrap_or(manifest_dir);
let output_abs = base_dir.join(&out_dir);
Ok((config_abs, output_abs))
}
#[derive(Debug)]
pub(crate) struct ManifestSummary {
pub handler_count: usize,
}
pub(crate) fn validate_output(output_dir: &Path) -> Result<ManifestSummary, String> {
let gen_rs = output_dir.join("gen.rs");
if !gen_rs.is_file() {
return Err(format!(
"codegen output not found: {} — run the codegen step first \
(e.g. `cargo run --bin codegen` in the js2rust example project, \
or `js2rust codegen --config <cfg>`)",
gen_rs.display()
));
}
let manifest_path = output_dir.join("manifest.json");
if !manifest_path.is_file() {
return Err(format!(
"manifest.json not found: {} — the bridge! contract (schema v{}) \
is written by the offline codegen; regenerate the output",
manifest_path.display(),
MANIFEST_SCHEMA_VERSION
));
}
let text = std::fs::read_to_string(&manifest_path)
.map_err(|e| format!("read {}: {e}", manifest_path.display()))?;
let v: serde_json::Value = serde_json::from_str(&text)
.map_err(|e| format!("parse {}: {e}", manifest_path.display()))?;
let version = v
.get("version")
.and_then(|x| x.as_i64())
.ok_or_else(|| "manifest.json: missing `version`".to_string())?;
if version != MANIFEST_SCHEMA_VERSION {
return Err(format!(
"manifest schema version {version} is not supported by this \
bridge macro (expects {MANIFEST_SCHEMA_VERSION}) — update \
js2rust-bridge-macro or regenerate with a matching js2rust"
));
}
let handlers = v
.get("handlers")
.and_then(|x| x.as_array())
.ok_or_else(|| "manifest.json: missing `handlers` array".to_string())?;
let mut seen: HashSet<&str> = HashSet::new();
for h in handlers {
let name = h
.get("handler")
.and_then(|x| x.as_str())
.ok_or_else(|| "manifest.json: handler entry missing `handler`".to_string())?;
if !seen.insert(name) {
return Err(format!("manifest.json: duplicate handler `{name}`"));
}
}
Ok(ManifestSummary { handler_count: handlers.len() })
}
pub(crate) fn emit_bridge(manifest_dir: &Path, output_dir: &Path) -> Result<String, String> {
let (gen_path, manifest_path) = if let Some(rel) = relative_posix(manifest_dir, output_dir) {
(
format!(
"concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{}/gen.rs\")",
rel
),
format!(
"concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{}/manifest.json\")",
rel
),
)
} else {
(
format!("\"{}\"", to_posix(&output_dir.join("gen.rs"))),
format!("\"{}\"", to_posix(&output_dir.join("manifest.json"))),
)
};
Ok(format!(
"pub mod gen {{ include!({gen_path}); }}\n\
const _: &[u8] = include_bytes!({manifest_path});\n"
))
}
fn relative_posix(manifest_dir: &Path, output_dir: &Path) -> Option<String> {
let base: Vec<_> = manifest_dir.components().collect();
let target: Vec<_> = output_dir.components().collect();
if base.is_empty() || target.is_empty() || base[0] != target[0] {
return None; }
let mut i = 0;
while i + 1 < base.len() && i + 1 < target.len() && base[i + 1] == target[i + 1] {
i += 1;
}
let mut parts: Vec<String> = Vec::new();
for _ in (i + 1)..base.len() {
parts.push("..".to_string());
}
for c in &target[i + 1..] {
parts.push(c.as_os_str().to_string_lossy().to_string());
}
Some(parts.join("/"))
}
fn to_posix(p: &Path) -> String {
p.to_string_lossy().replace('\\', "/")
}
#[proc_macro_attribute]
pub fn func(attr: TokenStream, item: TokenStream) -> TokenStream {
translate_attr("func", attr, item)
}
#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
translate_attr("route", attr, item)
}
fn translate_attr(kind_hint: &str, attr: TokenStream, item: TokenStream) -> TokenStream {
let manifest_dir = PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()),
);
let expanded = match run_translate_attr(kind_hint, attr, item, &manifest_dir) {
Ok(code) => code,
Err(msg) => format!("compile_error!({:?});", msg),
};
expanded
.parse::<TokenStream>()
.expect("#[func]/#[route] emitted invalid Rust code — this is a macro bug")
}
struct FuncArgs {
config: String,
source: String,
scope: Option<String>,
}
fn parse_func_args(kind_hint: &str, attr: TokenStream) -> Result<FuncArgs, String> {
const USAGE: &str = "supported syntax: #[func(config = \"js2rust.toml\", source = \"func/x.js\", scope = \"gen\"))]";
let mut config: Option<String> = None;
let mut source: Option<String> = None;
let mut scope: Option<String> = None;
let mut it = attr.into_iter().peekable();
while let Some(tok) = it.next() {
match tok {
TokenTree::Punct(p) if p.as_char() == ',' => continue,
TokenTree::Ident(id) => {
let key = id.to_string();
match (it.next(), it.next()) {
(Some(TokenTree::Punct(eq)), Some(TokenTree::Literal(lit)))
if eq.as_char() == '=' =>
{
let value = parse_str_literal(&lit.to_string())?;
match key.as_str() {
"config" if config.is_none() => config = Some(value),
"source" if source.is_none() => source = Some(value),
"scope" if scope.is_none() => scope = Some(value),
_ => return Err(format!("#[{kind_hint}]: unknown or duplicate key `{key}` — {USAGE}")),
}
}
_ => return Err(format!("#[{kind_hint}]: expected `= \"<value>\"` after `{key}` — {USAGE}")),
}
}
other => return Err(format!("#[{kind_hint}]: unexpected token `{other}` — {USAGE}")),
}
}
let source = source.ok_or_else(|| format!("#[{kind_hint}]: `source` is required — {USAGE}"))?;
Ok(FuncArgs {
config: config.unwrap_or_else(|| DEFAULT_CONFIG.to_string()),
source,
scope,
})
}
fn run_translate_attr(
kind_hint: &str,
attr: TokenStream,
item: TokenStream,
manifest_dir: &Path,
) -> Result<String, String> {
use syn::ItemFn;
let args = parse_func_args(kind_hint, attr)?;
let stub: ItemFn = syn::parse2(item.into())
.map_err(|e| format!("#[{kind_hint}]: annotated item must be a fn: {e}"))?;
let fn_name = stub.sig.ident.to_string();
let config_abs = manifest_dir.join(&args.config);
if !config_abs.is_file() {
return Err(format!(
"#[{kind_hint}]: js2rust config not found: {} (CARGO_MANIFEST_DIR + {})",
config_abs.display(),
args.config
));
}
let cfg = js2rust::TranslateConfig::load(&config_abs)
.map_err(|e| format!("#[{kind_hint}]: load {}: {e}", config_abs.display()))?;
let base_dir = config_abs
.parent()
.unwrap_or(manifest_dir)
.to_path_buf();
let outcome = js2rust::translate_single_file(&cfg, &base_dir, &args.source)
.map_err(|e| format!("#[{kind_hint}]: {e}"))?;
let source_abs = base_dir.join(&cfg.corpus.root).join(&args.source);
let schema_abs = base_dir.join(&cfg.schema.path);
let mut sentinels = sentinel_manifest_dir(manifest_dir, &source_abs, "SOURCE");
sentinels.push_str(&sentinel_manifest_dir(manifest_dir, &config_abs, "CONFIG"));
sentinels.push_str(&sentinel_manifest_dir(manifest_dir, &schema_abs, "SCHEMA"));
let scope_import = match &args.scope {
Some(s) => format!(
"#[allow(unused_imports, unused_qualifications)]\n pub use super::{s}::*;\n"
),
None => String::new(),
};
let mod_name = format!("{fn_name}_js2rust_bridge");
match outcome {
js2rust::SingleFileOutcome::Rust { mut handler_code, kind } => {
let translator_fn = js2rust::handler_fn_name(&args.source);
if !handler_code.contains(&translator_fn) {
return Err(format!(
"#[{kind_hint}]: translator output does not declare `{translator_fn}` — macro/version mismatch"
));
}
handler_code = handler_code.replace(&translator_fn, &fn_name);
let fn_header = format!("async fn {fn_name}");
if !handler_code.contains(&fn_header) {
return Err(format!(
"#[{kind_hint}]: translator output fn header `{fn_header}` not found"
));
}
handler_code = handler_code.replace(&fn_header, &format!("pub async fn {fn_name}"));
let _ = kind; Ok(format!(
"mod {mod_name} {{\n{scope_import}{sentinels}{handler_code}}}\n\
pub use {mod_name}::{fn_name};\n"
))
}
js2rust::SingleFileOutcome::Rhai { script, host_deps, kind, route_arity } => {
let (signature, call) = match kind {
js2rust::rhai_translator::FileKind::Func => (
format!("pub async fn {fn_name}(req: &str, host: &dyn Host) -> Result<serde_json::Value, String>"),
"// Safety: `host` outlives this call; the engine is local and dropped\n\
// before the function returns, so the 'static borrow never escapes.\n\
let __host_static: &'static dyn Host = unsafe { std::mem::transmute(host) };\n\
::js2rust::rhai_translator::rt::run_rhai_func(&__PRELUDE, __SCRIPT, req, __host_static, __REG).await"
.to_string(),
),
js2rust::rhai_translator::FileKind::Route => (
format!("pub async fn {fn_name}(code: &str, extra: &str, host: &dyn Host) -> Result<Route, String>"),
"// Safety: `host` outlives this call; the engine is local and dropped\n\
// before the function returns, so the 'static borrow never escapes.\n\
let __host_static: &'static dyn Host = unsafe { std::mem::transmute(host) };\n\
let __value = ::js2rust::rhai_translator::rt::run_rhai_route(&__PRELUDE, __SCRIPT, {route_arity}, code, extra, __host_static, __REG).await?;\n\
serde_json::from_value::<Route>(__value).map_err(|e| format!(\"Route deserialize: {e}\"))"
.to_string(),
),
};
let prelude_expr = match &cfg.prelude.project_file {
Some(overlay) => format!(
"format!(\"{{}}\\n{{}}\", ::js2rust::rhai_translator::PRELUDE_CORE, include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{}\")))",
overlay_posix(manifest_dir, &base_dir.join(overlay))
),
None => "::js2rust::rhai_translator::PRELUDE_CORE.to_string()".to_string(),
};
let host_fns = js2rust::host_table::effective_host_fns(&cfg.host);
let reg_body = js2rust::host_table::gen_register_fns(&host_deps, " ", host_fns);
let reg_fn = format!(
"fn __REG(engine: &mut rhai::Engine, host: &'static dyn Host) {{\n\
\x20 use rhai::Dynamic;\n\
\x20 use ::js2rust::rhai_translator::host_bridge::RhaiHostBridge;\n\
\x20 use ::js2rust::rhai_translator::host_bridge::{{dyn_to_json, dyn_to_str, json_to_dyn}};\n\
\x20 let bridge = RhaiHostBridge::new(host);\n\
{reg_body}\
}}\n"
);
Ok(format!(
"mod {mod_name} {{\n{scope_import}{sentinels}\
const __SCRIPT: &str = {script:?};\n\
#[allow(non_snake_case)]\n{reg_fn}\
#[allow(non_snake_case, unused_variables)]\n\
{signature} {{\n\
\x20 static __PRELUDE: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {prelude_expr});\n\
\x20 {call}\n\
}}\n}}\n\
pub use {mod_name}::{fn_name};\n",
script = script
))
}
js2rust::SingleFileOutcome::JsFallback { rust_err, rhai_err } => Err(format!(
"#[{kind_hint}]: `{}` needs the JS fallback tier, which is not \
supported in single-file macro mode (rust tier: {rust_err}; rhai \
tier: {rhai_err}) — use the project-level bridge! with offline \
codegen instead",
args.source
)),
}
}
fn sentinel_manifest_dir(manifest_dir: &Path, file: &Path, tag: &str) -> String {
let inc = match relative_posix(manifest_dir, file) {
Some(rel) => format!("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{rel}\")"),
None => format!("\"{}\"", to_posix(file)),
};
format!(
" #[allow(dead_code)]\n const __J2R_SENTINEL_{tag}: &[u8] = include_bytes!({inc});\n"
)
}
fn overlay_posix(manifest_dir: &Path, overlay_abs: &Path) -> String {
match relative_posix(manifest_dir, overlay_abs) {
Some(rel) => rel,
None => to_posix(overlay_abs),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn temp_fixture(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!(
"js2rust-bridge-macro-test-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
fn write(path: &Path, content: &str) {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(path, content).unwrap();
}
#[test]
fn resolve_uses_output_dir_from_config() {
let dir = temp_fixture("resolve_custom");
let cfg = dir.join("js2rust.toml");
write(&cfg, "[output]\ndir = \"gen-out\"\n");
let (_c, out) = resolve_paths(&dir, "js2rust.toml").unwrap();
assert_eq!(out, dir.join("gen-out"));
}
#[test]
fn resolve_defaults_output_dir_when_section_missing() {
let dir = temp_fixture("resolve_default");
write(&dir.join("js2rust.toml"), "[corpus]\nroot = \"data\"\n");
let (_c, out) = resolve_paths(&dir, "js2rust.toml").unwrap();
assert_eq!(out, dir.join("output"));
}
#[test]
fn resolve_errs_when_config_missing() {
let dir = temp_fixture("resolve_missing");
let err = resolve_paths(&dir, "nope.toml").unwrap_err();
assert!(err.contains("not found"), "unexpected error: {err}");
}
#[test]
fn resolve_errs_on_broken_toml() {
let dir = temp_fixture("resolve_broken");
write(&dir.join("js2rust.toml"), "[[[ not toml");
let err = resolve_paths(&dir, "js2rust.toml").unwrap_err();
assert!(err.contains("parse"), "unexpected error: {err}");
}
#[test]
fn validate_accepts_wellformed_output() {
let dir = temp_fixture("validate_ok");
write(&dir.join("gen.rs"), "// stub\n");
let manifest = r#"{
"version": 1,
"generator": "js2rust",
"tiers": { "rust": 1 },
"handlers": [
{ "source": "routes/51.js", "route_name": "51", "kind": "Route",
"tier": "rust", "handler": "handler_route51", "struct_name": "Route51" },
{ "source": "func/x.js", "route_name": "x", "kind": "Func",
"tier": "rhai", "handler": "handler_funcx", "struct_name": "FuncX" }
]
}"#;
write(&dir.join("manifest.json"), manifest);
let summary = validate_output(&dir).unwrap();
assert_eq!(summary.handler_count, 2);
}
#[test]
fn validate_errs_without_gen_rs() {
let dir = temp_fixture("validate_no_gen");
let err = validate_output(&dir).unwrap_err();
assert!(err.contains("codegen output not found"), "unexpected: {err}");
}
#[test]
fn validate_errs_without_manifest() {
let dir = temp_fixture("validate_no_manifest");
write(&dir.join("gen.rs"), "// stub\n");
let err = validate_output(&dir).unwrap_err();
assert!(err.contains("manifest.json not found"), "unexpected: {err}");
}
#[test]
fn validate_rejects_version_mismatch() {
let dir = temp_fixture("validate_version");
write(&dir.join("gen.rs"), "// stub\n");
write(&dir.join("manifest.json"), r#"{ "version": 99, "handlers": [] }"#);
let err = validate_output(&dir).unwrap_err();
assert!(err.contains("version"), "unexpected: {err}");
}
#[test]
fn validate_rejects_duplicate_handlers() {
let dir = temp_fixture("validate_dupes");
write(&dir.join("gen.rs"), "// stub\n");
let manifest = r#"{
"version": 1,
"handlers": [
{ "handler": "handler_a" },
{ "handler": "handler_a" }
]
}"#;
write(&dir.join("manifest.json"), manifest);
let err = validate_output(&dir).unwrap_err();
assert!(err.contains("duplicate handler"), "unexpected: {err}");
}
#[test]
fn emit_uses_env_concat_for_in_crate_output() {
let root = PathBuf::from("/ws/proj");
let out = root.join("output");
let code = emit_bridge(&root, &out).unwrap();
assert!(code.contains("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/output/gen.rs\"))"));
assert!(code.contains("include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/output/manifest.json\"))"));
}
#[test]
fn emit_escapes_upward_paths() {
let root = PathBuf::from("/ws/proj/crate");
let out = PathBuf::from("/ws/proj/out");
let code = emit_bridge(&root, &out).unwrap();
assert!(code.contains("\"/../out/gen.rs\""), "got: {code}");
}
#[test]
fn str_literal_unquoting() {
assert_eq!(parse_str_literal("\"js2rust.toml\"").unwrap(), "js2rust.toml");
assert!(parse_str_literal("raw\"x").is_err());
assert!(parse_str_literal("not_a_literal").is_err());
}
}