js2rust-bridge-macro 0.19.0

Procedural macros bridging js2rust-translated JavaScript into Rust at compile time.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! js2rust-bridge-macro — compile-time bridge macros for js2rust.
//!
//! Stages:
//!
//! - **P-A2** — [`bridge!`]: project-level wiring macro. Reads `js2rust.toml`
//!   (the `[output]` section) plus the codegen `manifest.json`, validates
//!   the contract, and expands into the `gen` module tree (`include!` of the
//!   offline codegen output) with an `include_bytes!` dependency-tracking
//!   sentinel so rustc rebuilds when codegen reruns.
//! - **P-A3 (this revision)** — [`func`] / [`route`]: single-file
//!   translation attribute macros. Translate one JS source inside macro
//!   expansion (same Rust → Rhai tiers as the offline pipeline, no codegen
//!   products needed), replace the annotated fn with the translated
//!   handler, and emit sentinels tracking the JS source, the config, and
//!   the GraphQL schema. The JS fallback tier is not supported in
//!   single-file mode — use the project-level [`bridge!`] instead.
//!
//! Dependency direction (Cargo requires a DAG):
//!
//! ```text
//! js2rust-bridge-macro ──▶ js2rust   (macro expansion uses the translator)
//!        ▲                       ▲
//!        └──── user crate ───────┘
//! ```
//!
//! This crate may depend on `js2rust`; `js2rust` must never depend on this
//! crate. Generated code references runtime types via `::js2rust::...`.
//!
//! # [`bridge!`] usage
//!
//! ```ignore
//! js2rust_bridge_macro::bridge! { config: "js2rust.toml" };
//! // or simply: js2rust_bridge_macro::bridge! {};
//! //            (defaults to config = "js2rust.toml")
//! ```
//!
//! The `config` path is resolved against `CARGO_MANIFEST_DIR` of the crate
//! invoking the macro. The expanded code is:
//!
//! ```ignore
//! pub mod gen { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/<output>/gen.rs")); }
//! const _: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/<output>/manifest.json"));
//! ```
//!
//! The sentinel makes rustc track `manifest.json`: rerunning the offline
//! codegen (which rewrites the manifest) automatically triggers recompile,
//! closing the classic proc-macro "external file not tracked" gap.

use proc_macro::{TokenStream, TokenTree};
use std::collections::HashSet;
use std::path::{Path, PathBuf};

/// Manifest schema version this macro build understands. Bump in lockstep
/// with pipeline.rs (`manifest.version`) on breaking contract changes.
const MANIFEST_SCHEMA_VERSION: i64 = 1;

/// Default config file name, matching TranslateConfig conventions.
const DEFAULT_CONFIG: &str = "js2rust.toml";

/// Expand `bridge! { config: "<path>"? }`.
///
/// See the crate docs for the wiring semantics. All failures surface as
/// `compile_error!` with an actionable message pointing at the codegen step.
#[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")
}

/// Full pipeline behind the proc-macro entry (kept out of `bridge` so the
/// proc_macro API boundary stays thin).
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)?;
    // The manifest's handler count is a cheap cross-check: an empty corpus
    // (or a codegen run that silently produced nothing) surfaces in debug
    // builds instead of as a confusing dispatch-empty runtime.
    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)
}

// ============================================================================
// bridge! argument parsing (hand-parsed: the grammar is one optional pair).
// ============================================================================

/// Parse `bridge!` args. Grammar: `[ config : "<path>" ]`.
/// Empty input selects [`DEFAULT_CONFIG`]. Anything else is an error.
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()))
}

/// Unquote a plain (non-raw) string literal `"..."`.
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}', "\\"))
}

// ============================================================================
// Path resolution + contract validation (pure std — unit-testable).
// ============================================================================

/// Resolve the config file and the codegen output directory.
///
/// `config_rel` is relative to the invoking crate's manifest dir. The
/// `[output] dir` value inside the config is relative to the config file's
/// own directory (the js2rust `base_dir` convention); it defaults to
/// `"output"`, matching `TranslateConfig`.
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))
}

/// Summary of a validated manifest.
#[derive(Debug)]
pub(crate) struct ManifestSummary {
    pub handler_count: usize,
}

/// Validate the codegen output: `gen.rs` present, `manifest.json` present,
/// schema version compatible, handler names unique.
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() })
}

// ============================================================================
// Code emission.
// ============================================================================

/// Emit the wiring module + dependency-tracking sentinel.
///
/// Paths are emitted as `concat!(env!("CARGO_MANIFEST_DIR"), "/...")` when
/// the output dir lives under the invoking crate's manifest dir (portable),
/// or as plain absolute paths otherwise (rare: output outside the crate).
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"
    ))
}

/// `output` dir as a POSIX-style relative path from `manifest_dir`, or
/// `None` when it is not reachable by `..`-walking (different Windows drive).
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; // different roots (e.g. C: vs D:) — absolute path
    }
    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("/"))
}

/// Normalize a path to forward slashes for emission into generated code.
fn to_posix(p: &Path) -> String {
    p.to_string_lossy().replace('\\', "/")
}

// ============================================================================
// P-A3: single-file translation macros — #[func] / #[route].
// ============================================================================

/// Attribute macro: translate ONE JS source at compile time and replace
/// the annotated fn with the translated handler (P-A3).
///
/// ```ignore
/// #[js2rust_bridge_macro::func(
///     config = "js2rust.toml",        // relative to CARGO_MANIFEST_DIR
///     source = "func/create_sms.js",  // relative to corpus root, required
///     scope = "gen",                  // module providing Host/Route/types,
/// )]                                  // default: no scope imports
/// async fn create_sms_stub() {}       // name kept; signature replaced
/// ```
///
/// The stub fn is discarded — only its name, visibility, and docs are kept.
/// The macro runs the same Rust→Rhai translation tiers as the offline
/// pipeline and emits: a private module (scope imports + regenerated
/// handler + per-script host-fn register fn + `include_bytes!` sentinels
/// tracking the JS source, the config, and the GraphQL schema), plus a
/// re-export of the handler under the stub's name. Editing the JS source
/// or the schema triggers a rebuild of the generated handler.
#[proc_macro_attribute]
pub fn func(attr: TokenStream, item: TokenStream) -> TokenStream {
    translate_attr("func", attr, item)
}

/// Route flavor of [`func`] (entry `route(code[, extra])`, returns `Route`).
#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
    translate_attr("route", attr, item)
}

/// Shared implementation behind #[func] / #[route].
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>,
}

/// Parse `#[func(config = "..", source = "..", scope = "..")]`.
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)?;

    // Stub fn: name + visibility + docs kept, everything else replaced.
    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();

    // Load config (relative to CARGO_MANIFEST_DIR) and translate the file.
    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}"))?;

    // Dependency-tracking sentinels: JS source + config + GraphQL schema.
    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 {
        // `super::` inside the emitted module = the macro call site, where
        // the user's `gen` module (from bridge! or a hand-written mod) lives.
        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 } => {
            // The translator names the fn handler_<struct>; rename to the
            // stub's name (appears exactly once, in the fn header).
            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);
            // The translator emits `async fn` (no visibility); the handler
            // is `pub` inside its private module so the re-export works.
            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; // signature already encodes the 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
        )),
    }
}

/// Emit one `include_bytes!` sentinel const as manifest_dir-relative
/// `concat!(env!(...))` when possible (portable), or as an absolute path
/// otherwise.
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"
    )
}

/// Project prelude overlay path, normalized relative to CARGO_MANIFEST_DIR
/// for `include_str!` (absolute fallback).
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),
    }
}

// ============================================================================
// Tests — pure functions only (proc_macro APIs are unavailable in tests).
// ============================================================================

#[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());
    }
}