1use proc_macro::{TokenStream, TokenTree};
50use std::collections::HashSet;
51use std::path::{Path, PathBuf};
52
53const MANIFEST_SCHEMA_VERSION: i64 = 1;
56
57const DEFAULT_CONFIG: &str = "js2rust.toml";
59
60#[proc_macro]
65pub fn bridge(input: TokenStream) -> TokenStream {
66 let manifest_dir = PathBuf::from(
67 std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()),
68 );
69 let expanded = match run_bridge(input, &manifest_dir) {
70 Ok(code) => code,
71 Err(msg) => format!("compile_error!({:?});", msg),
72 };
73 expanded
74 .parse::<TokenStream>()
75 .expect("bridge! emitted invalid Rust code — this is a macro bug")
76}
77
78fn run_bridge(input: TokenStream, manifest_dir: &Path) -> Result<String, String> {
81 let config_rel = parse_args(input)?;
82 let (_config_abs, output_dir) = resolve_paths(manifest_dir, &config_rel)?;
83 let summary = validate_output(&output_dir)?;
84 debug_assert!(
88 summary.handler_count > 0,
89 "bridge!: manifest.json declares 0 handlers — did the codegen run find the corpus?"
90 );
91 emit_bridge(manifest_dir, &output_dir)
92}
93
94fn parse_args(input: TokenStream) -> Result<String, String> {
101 const USAGE: &str = "supported syntax: bridge! { config: \"js2rust.toml\" } (config optional)";
102 let mut config: Option<String> = None;
103 let mut it = input.into_iter().peekable();
104 while let Some(tok) = it.next() {
105 match tok {
106 TokenTree::Punct(p) if p.as_char() == ',' => continue,
107 TokenTree::Ident(id) => {
108 if id.to_string() != "config" {
109 return Err(format!("bridge!: unknown key `{id}` — {USAGE}"));
110 }
111 match (it.next(), it.next()) {
112 (Some(TokenTree::Punct(c)), Some(TokenTree::Literal(lit)))
113 if c.as_char() == ':' =>
114 {
115 if config.is_some() {
116 return Err(format!("bridge!: duplicate key `config` — {USAGE}"));
117 }
118 config = Some(parse_str_literal(&lit.to_string())?);
119 }
120 _ => return Err(format!("bridge!: expected `: \"<path>\"` after `config` — {USAGE}")),
121 }
122 }
123 other => {
124 return Err(format!("bridge!: unexpected token `{other}` — {USAGE}"));
125 }
126 }
127 }
128 Ok(config.unwrap_or_else(|| DEFAULT_CONFIG.to_string()))
129}
130
131fn parse_str_literal(raw: &str) -> Result<String, String> {
133 let Some(inner) = raw.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else {
134 return Err(format!(
135 "bridge!: config value must be a plain string literal, got `{raw}`"
136 ));
137 };
138 Ok(inner.replace("\\\\", "\u{0}").replace("\\\"", "\"").replace('\u{0}', "\\"))
139}
140
141pub(crate) fn resolve_paths(
152 manifest_dir: &Path,
153 config_rel: &str,
154) -> Result<(PathBuf, PathBuf), String> {
155 let config_abs = manifest_dir.join(config_rel);
156 if !config_abs.is_file() {
157 return Err(format!(
158 "js2rust config not found: {} (CARGO_MANIFEST_DIR + {config_rel})",
159 config_abs.display()
160 ));
161 }
162 let text = std::fs::read_to_string(&config_abs)
163 .map_err(|e| format!("read {}: {e}", config_abs.display()))?;
164 let tbl: toml::Table = toml::from_str(&text)
165 .map_err(|e| format!("parse {}: {e}", config_abs.display()))?;
166 let out_dir = tbl
167 .get("output")
168 .and_then(|o| o.get("dir"))
169 .and_then(|d| d.as_str())
170 .unwrap_or("output")
171 .to_string();
172 let base_dir = config_abs.parent().unwrap_or(manifest_dir);
173 let output_abs = base_dir.join(&out_dir);
174 Ok((config_abs, output_abs))
175}
176
177#[derive(Debug)]
179pub(crate) struct ManifestSummary {
180 pub handler_count: usize,
181}
182
183pub(crate) fn validate_output(output_dir: &Path) -> Result<ManifestSummary, String> {
186 let gen_rs = output_dir.join("gen.rs");
187 if !gen_rs.is_file() {
188 return Err(format!(
189 "codegen output not found: {} — run the codegen step first \
190 (e.g. `cargo run --bin codegen` in the js2rust example project, \
191 or `js2rust codegen --config <cfg>`)",
192 gen_rs.display()
193 ));
194 }
195 let manifest_path = output_dir.join("manifest.json");
196 if !manifest_path.is_file() {
197 return Err(format!(
198 "manifest.json not found: {} — the bridge! contract (schema v{}) \
199 is written by the offline codegen; regenerate the output",
200 manifest_path.display(),
201 MANIFEST_SCHEMA_VERSION
202 ));
203 }
204 let text = std::fs::read_to_string(&manifest_path)
205 .map_err(|e| format!("read {}: {e}", manifest_path.display()))?;
206 let v: serde_json::Value = serde_json::from_str(&text)
207 .map_err(|e| format!("parse {}: {e}", manifest_path.display()))?;
208 let version = v
209 .get("version")
210 .and_then(|x| x.as_i64())
211 .ok_or_else(|| "manifest.json: missing `version`".to_string())?;
212 if version != MANIFEST_SCHEMA_VERSION {
213 return Err(format!(
214 "manifest schema version {version} is not supported by this \
215 bridge macro (expects {MANIFEST_SCHEMA_VERSION}) — update \
216 js2rust-bridge-macro or regenerate with a matching js2rust"
217 ));
218 }
219 let handlers = v
220 .get("handlers")
221 .and_then(|x| x.as_array())
222 .ok_or_else(|| "manifest.json: missing `handlers` array".to_string())?;
223 let mut seen: HashSet<&str> = HashSet::new();
224 for h in handlers {
225 let name = h
226 .get("handler")
227 .and_then(|x| x.as_str())
228 .ok_or_else(|| "manifest.json: handler entry missing `handler`".to_string())?;
229 if !seen.insert(name) {
230 return Err(format!("manifest.json: duplicate handler `{name}`"));
231 }
232 }
233 Ok(ManifestSummary { handler_count: handlers.len() })
234}
235
236pub(crate) fn emit_bridge(manifest_dir: &Path, output_dir: &Path) -> Result<String, String> {
246 let (gen_path, manifest_path) = if let Some(rel) = relative_posix(manifest_dir, output_dir) {
247 (
248 format!(
249 "concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{}/gen.rs\")",
250 rel
251 ),
252 format!(
253 "concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{}/manifest.json\")",
254 rel
255 ),
256 )
257 } else {
258 (
259 format!("\"{}\"", to_posix(&output_dir.join("gen.rs"))),
260 format!("\"{}\"", to_posix(&output_dir.join("manifest.json"))),
261 )
262 };
263 Ok(format!(
264 "pub mod gen {{ include!({gen_path}); }}\n\
265 const _: &[u8] = include_bytes!({manifest_path});\n"
266 ))
267}
268
269fn relative_posix(manifest_dir: &Path, output_dir: &Path) -> Option<String> {
272 let base: Vec<_> = manifest_dir.components().collect();
273 let target: Vec<_> = output_dir.components().collect();
274 if base.is_empty() || target.is_empty() || base[0] != target[0] {
275 return None; }
277 let mut i = 0;
278 while i + 1 < base.len() && i + 1 < target.len() && base[i + 1] == target[i + 1] {
279 i += 1;
280 }
281 let mut parts: Vec<String> = Vec::new();
282 for _ in (i + 1)..base.len() {
283 parts.push("..".to_string());
284 }
285 for c in &target[i + 1..] {
286 parts.push(c.as_os_str().to_string_lossy().to_string());
287 }
288 Some(parts.join("/"))
289}
290
291fn to_posix(p: &Path) -> String {
293 p.to_string_lossy().replace('\\', "/")
294}
295
296#[proc_macro_attribute]
320pub fn func(attr: TokenStream, item: TokenStream) -> TokenStream {
321 translate_attr("func", attr, item)
322}
323
324#[proc_macro_attribute]
326pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
327 translate_attr("route", attr, item)
328}
329
330fn translate_attr(kind_hint: &str, attr: TokenStream, item: TokenStream) -> TokenStream {
332 let manifest_dir = PathBuf::from(
333 std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()),
334 );
335 let expanded = match run_translate_attr(kind_hint, attr, item, &manifest_dir) {
336 Ok(code) => code,
337 Err(msg) => format!("compile_error!({:?});", msg),
338 };
339 expanded
340 .parse::<TokenStream>()
341 .expect("#[func]/#[route] emitted invalid Rust code — this is a macro bug")
342}
343
344struct FuncArgs {
345 config: String,
346 source: String,
347 scope: Option<String>,
348}
349
350fn parse_func_args(kind_hint: &str, attr: TokenStream) -> Result<FuncArgs, String> {
352 const USAGE: &str = "supported syntax: #[func(config = \"js2rust.toml\", source = \"func/x.js\", scope = \"gen\"))]";
353 let mut config: Option<String> = None;
354 let mut source: Option<String> = None;
355 let mut scope: Option<String> = None;
356 let mut it = attr.into_iter().peekable();
357 while let Some(tok) = it.next() {
358 match tok {
359 TokenTree::Punct(p) if p.as_char() == ',' => continue,
360 TokenTree::Ident(id) => {
361 let key = id.to_string();
362 match (it.next(), it.next()) {
363 (Some(TokenTree::Punct(eq)), Some(TokenTree::Literal(lit)))
364 if eq.as_char() == '=' =>
365 {
366 let value = parse_str_literal(&lit.to_string())?;
367 match key.as_str() {
368 "config" if config.is_none() => config = Some(value),
369 "source" if source.is_none() => source = Some(value),
370 "scope" if scope.is_none() => scope = Some(value),
371 _ => return Err(format!("#[{kind_hint}]: unknown or duplicate key `{key}` — {USAGE}")),
372 }
373 }
374 _ => return Err(format!("#[{kind_hint}]: expected `= \"<value>\"` after `{key}` — {USAGE}")),
375 }
376 }
377 other => return Err(format!("#[{kind_hint}]: unexpected token `{other}` — {USAGE}")),
378 }
379 }
380 let source = source.ok_or_else(|| format!("#[{kind_hint}]: `source` is required — {USAGE}"))?;
381 Ok(FuncArgs {
382 config: config.unwrap_or_else(|| DEFAULT_CONFIG.to_string()),
383 source,
384 scope,
385 })
386}
387
388fn run_translate_attr(
389 kind_hint: &str,
390 attr: TokenStream,
391 item: TokenStream,
392 manifest_dir: &Path,
393) -> Result<String, String> {
394 use syn::ItemFn;
395
396 let args = parse_func_args(kind_hint, attr)?;
397
398 let stub: ItemFn = syn::parse2(item.into())
400 .map_err(|e| format!("#[{kind_hint}]: annotated item must be a fn: {e}"))?;
401 let fn_name = stub.sig.ident.to_string();
402
403 let config_abs = manifest_dir.join(&args.config);
405 if !config_abs.is_file() {
406 return Err(format!(
407 "#[{kind_hint}]: js2rust config not found: {} (CARGO_MANIFEST_DIR + {})",
408 config_abs.display(),
409 args.config
410 ));
411 }
412 let cfg = js2rust::TranslateConfig::load(&config_abs)
413 .map_err(|e| format!("#[{kind_hint}]: load {}: {e}", config_abs.display()))?;
414 let base_dir = config_abs
415 .parent()
416 .unwrap_or(manifest_dir)
417 .to_path_buf();
418 let outcome = js2rust::translate_single_file(&cfg, &base_dir, &args.source)
419 .map_err(|e| format!("#[{kind_hint}]: {e}"))?;
420
421 let source_abs = base_dir.join(&cfg.corpus.root).join(&args.source);
423 let schema_abs = base_dir.join(&cfg.schema.path);
424 let mut sentinels = sentinel_manifest_dir(manifest_dir, &source_abs, "SOURCE");
425 sentinels.push_str(&sentinel_manifest_dir(manifest_dir, &config_abs, "CONFIG"));
426 sentinels.push_str(&sentinel_manifest_dir(manifest_dir, &schema_abs, "SCHEMA"));
427 let scope_import = match &args.scope {
428 Some(s) => format!(
431 "#[allow(unused_imports, unused_qualifications)]\n pub use super::{s}::*;\n"
432 ),
433 None => String::new(),
434 };
435 let mod_name = format!("{fn_name}_js2rust_bridge");
436
437 match outcome {
438 js2rust::SingleFileOutcome::Rust { mut handler_code, kind } => {
439 let translator_fn = js2rust::handler_fn_name(&args.source);
442 if !handler_code.contains(&translator_fn) {
443 return Err(format!(
444 "#[{kind_hint}]: translator output does not declare `{translator_fn}` — macro/version mismatch"
445 ));
446 }
447 handler_code = handler_code.replace(&translator_fn, &fn_name);
448 let fn_header = format!("async fn {fn_name}");
451 if !handler_code.contains(&fn_header) {
452 return Err(format!(
453 "#[{kind_hint}]: translator output fn header `{fn_header}` not found"
454 ));
455 }
456 handler_code = handler_code.replace(&fn_header, &format!("pub async fn {fn_name}"));
457 let _ = kind; Ok(format!(
459 "mod {mod_name} {{\n{scope_import}{sentinels}{handler_code}}}\n\
460 pub use {mod_name}::{fn_name};\n"
461 ))
462 }
463 js2rust::SingleFileOutcome::Rhai { script, host_deps, kind, route_arity } => {
464 let (signature, call) = match kind {
465 js2rust::rhai_translator::FileKind::Func => (
466 format!("pub async fn {fn_name}(req: &str, host: &dyn Host) -> Result<serde_json::Value, String>"),
467 "// Safety: `host` outlives this call; the engine is local and dropped\n\
468 // before the function returns, so the 'static borrow never escapes.\n\
469 let __host_static: &'static dyn Host = unsafe { std::mem::transmute(host) };\n\
470 ::js2rust::rhai_translator::rt::run_rhai_func(&__PRELUDE, __SCRIPT, req, __host_static, __REG).await"
471 .to_string(),
472 ),
473 js2rust::rhai_translator::FileKind::Route => (
474 format!("pub async fn {fn_name}(code: &str, extra: &str, host: &dyn Host) -> Result<Route, String>"),
475 "// Safety: `host` outlives this call; the engine is local and dropped\n\
476 // before the function returns, so the 'static borrow never escapes.\n\
477 let __host_static: &'static dyn Host = unsafe { std::mem::transmute(host) };\n\
478 let __value = ::js2rust::rhai_translator::rt::run_rhai_route(&__PRELUDE, __SCRIPT, {route_arity}, code, extra, __host_static, __REG).await?;\n\
479 serde_json::from_value::<Route>(__value).map_err(|e| format!(\"Route deserialize: {e}\"))"
480 .to_string(),
481 ),
482 };
483 let prelude_expr = match &cfg.prelude.project_file {
484 Some(overlay) => format!(
485 "format!(\"{{}}\\n{{}}\", ::js2rust::rhai_translator::PRELUDE_CORE, include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{}\")))",
486 overlay_posix(manifest_dir, &base_dir.join(overlay))
487 ),
488 None => "::js2rust::rhai_translator::PRELUDE_CORE.to_string()".to_string(),
489 };
490 let host_fns = js2rust::host_table::effective_host_fns(&cfg.host);
491 let reg_body = js2rust::host_table::gen_register_fns(&host_deps, " ", host_fns);
492 let reg_fn = format!(
493 "fn __REG(engine: &mut rhai::Engine, host: &'static dyn Host) {{\n\
494 \x20 use rhai::Dynamic;\n\
495 \x20 use ::js2rust::rhai_translator::host_bridge::RhaiHostBridge;\n\
496 \x20 use ::js2rust::rhai_translator::host_bridge::{{dyn_to_json, dyn_to_str, json_to_dyn}};\n\
497 \x20 let bridge = RhaiHostBridge::new(host);\n\
498 {reg_body}\
499 }}\n"
500 );
501 Ok(format!(
502 "mod {mod_name} {{\n{scope_import}{sentinels}\
503 const __SCRIPT: &str = {script:?};\n\
504 #[allow(non_snake_case)]\n{reg_fn}\
505 #[allow(non_snake_case, unused_variables)]\n\
506 {signature} {{\n\
507 \x20 static __PRELUDE: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {prelude_expr});\n\
508 \x20 {call}\n\
509 }}\n}}\n\
510 pub use {mod_name}::{fn_name};\n",
511 script = script
512 ))
513 }
514 js2rust::SingleFileOutcome::JsFallback { rust_err, rhai_err } => Err(format!(
515 "#[{kind_hint}]: `{}` needs the JS fallback tier, which is not \
516 supported in single-file macro mode (rust tier: {rust_err}; rhai \
517 tier: {rhai_err}) — use the project-level bridge! with offline \
518 codegen instead",
519 args.source
520 )),
521 }
522}
523
524fn sentinel_manifest_dir(manifest_dir: &Path, file: &Path, tag: &str) -> String {
528 let inc = match relative_posix(manifest_dir, file) {
529 Some(rel) => format!("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{rel}\")"),
530 None => format!("\"{}\"", to_posix(file)),
531 };
532 format!(
533 " #[allow(dead_code)]\n const __J2R_SENTINEL_{tag}: &[u8] = include_bytes!({inc});\n"
534 )
535}
536
537fn overlay_posix(manifest_dir: &Path, overlay_abs: &Path) -> String {
540 match relative_posix(manifest_dir, overlay_abs) {
541 Some(rel) => rel,
542 None => to_posix(overlay_abs),
543 }
544}
545
546#[cfg(test)]
551mod tests {
552 use super::*;
553 use std::fs;
554
555 fn temp_fixture(name: &str) -> PathBuf {
556 let d = std::env::temp_dir().join(format!(
557 "js2rust-bridge-macro-test-{name}-{}",
558 std::process::id()
559 ));
560 let _ = fs::remove_dir_all(&d);
561 fs::create_dir_all(&d).unwrap();
562 d
563 }
564
565 fn write(path: &Path, content: &str) {
566 if let Some(parent) = path.parent() {
567 fs::create_dir_all(parent).unwrap();
568 }
569 fs::write(path, content).unwrap();
570 }
571
572 #[test]
573 fn resolve_uses_output_dir_from_config() {
574 let dir = temp_fixture("resolve_custom");
575 let cfg = dir.join("js2rust.toml");
576 write(&cfg, "[output]\ndir = \"gen-out\"\n");
577 let (_c, out) = resolve_paths(&dir, "js2rust.toml").unwrap();
578 assert_eq!(out, dir.join("gen-out"));
579 }
580
581 #[test]
582 fn resolve_defaults_output_dir_when_section_missing() {
583 let dir = temp_fixture("resolve_default");
584 write(&dir.join("js2rust.toml"), "[corpus]\nroot = \"data\"\n");
585 let (_c, out) = resolve_paths(&dir, "js2rust.toml").unwrap();
586 assert_eq!(out, dir.join("output"));
587 }
588
589 #[test]
590 fn resolve_errs_when_config_missing() {
591 let dir = temp_fixture("resolve_missing");
592 let err = resolve_paths(&dir, "nope.toml").unwrap_err();
593 assert!(err.contains("not found"), "unexpected error: {err}");
594 }
595
596 #[test]
597 fn resolve_errs_on_broken_toml() {
598 let dir = temp_fixture("resolve_broken");
599 write(&dir.join("js2rust.toml"), "[[[ not toml");
600 let err = resolve_paths(&dir, "js2rust.toml").unwrap_err();
601 assert!(err.contains("parse"), "unexpected error: {err}");
602 }
603
604 #[test]
605 fn validate_accepts_wellformed_output() {
606 let dir = temp_fixture("validate_ok");
607 write(&dir.join("gen.rs"), "// stub\n");
608 let manifest = r#"{
609 "version": 1,
610 "generator": "js2rust",
611 "tiers": { "rust": 1 },
612 "handlers": [
613 { "source": "routes/51.js", "route_name": "51", "kind": "Route",
614 "tier": "rust", "handler": "handler_route51", "struct_name": "Route51" },
615 { "source": "func/x.js", "route_name": "x", "kind": "Func",
616 "tier": "rhai", "handler": "handler_funcx", "struct_name": "FuncX" }
617 ]
618 }"#;
619 write(&dir.join("manifest.json"), manifest);
620 let summary = validate_output(&dir).unwrap();
621 assert_eq!(summary.handler_count, 2);
622 }
623
624 #[test]
625 fn validate_errs_without_gen_rs() {
626 let dir = temp_fixture("validate_no_gen");
627 let err = validate_output(&dir).unwrap_err();
628 assert!(err.contains("codegen output not found"), "unexpected: {err}");
629 }
630
631 #[test]
632 fn validate_errs_without_manifest() {
633 let dir = temp_fixture("validate_no_manifest");
634 write(&dir.join("gen.rs"), "// stub\n");
635 let err = validate_output(&dir).unwrap_err();
636 assert!(err.contains("manifest.json not found"), "unexpected: {err}");
637 }
638
639 #[test]
640 fn validate_rejects_version_mismatch() {
641 let dir = temp_fixture("validate_version");
642 write(&dir.join("gen.rs"), "// stub\n");
643 write(&dir.join("manifest.json"), r#"{ "version": 99, "handlers": [] }"#);
644 let err = validate_output(&dir).unwrap_err();
645 assert!(err.contains("version"), "unexpected: {err}");
646 }
647
648 #[test]
649 fn validate_rejects_duplicate_handlers() {
650 let dir = temp_fixture("validate_dupes");
651 write(&dir.join("gen.rs"), "// stub\n");
652 let manifest = r#"{
653 "version": 1,
654 "handlers": [
655 { "handler": "handler_a" },
656 { "handler": "handler_a" }
657 ]
658 }"#;
659 write(&dir.join("manifest.json"), manifest);
660 let err = validate_output(&dir).unwrap_err();
661 assert!(err.contains("duplicate handler"), "unexpected: {err}");
662 }
663
664 #[test]
665 fn emit_uses_env_concat_for_in_crate_output() {
666 let root = PathBuf::from("/ws/proj");
667 let out = root.join("output");
668 let code = emit_bridge(&root, &out).unwrap();
669 assert!(code.contains("concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/output/gen.rs\"))"));
670 assert!(code.contains("include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/output/manifest.json\"))"));
671 }
672
673 #[test]
674 fn emit_escapes_upward_paths() {
675 let root = PathBuf::from("/ws/proj/crate");
676 let out = PathBuf::from("/ws/proj/out");
677 let code = emit_bridge(&root, &out).unwrap();
678 assert!(code.contains("\"/../out/gen.rs\""), "got: {code}");
679 }
680
681 #[test]
682 fn str_literal_unquoting() {
683 assert_eq!(parse_str_literal("\"js2rust.toml\"").unwrap(), "js2rust.toml");
684 assert!(parse_str_literal("raw\"x").is_err());
685 assert!(parse_str_literal("not_a_literal").is_err());
686 }
687}