Skip to main content

rust_anything/
bridge.rs

1//! Step 2: scaffold a Rust crate for one unit, with JS bindings and a manifest the later
2//! steps read.
3//!
4//! The crate splits bindings from logic: `src/lib.rs` holds thin `#[napi]` or
5//! `#[wasm_bindgen]` wrappers, `src/port.rs` holds the port in plain Rust with
6//! `#![forbid(unsafe_code)]`, so it can be tested without a JS runtime.
7
8use crate::walk::Canonical;
9use std::path::{Path, PathBuf};
10
11use anyhow::{Context, Result, bail};
12use serde::{Deserialize, Serialize};
13
14use crate::analyze::{self, Bridge, Status};
15use crate::codegen;
16use crate::risks::Risk;
17use crate::ts::exports::{
18    ExportedClass, ExportedFn, LocalType, exported_classes, exported_functions, local_types,
19};
20
21pub const MANIFEST: &str = "rust-anything.json";
22pub const SCHEMA: &str = "rust-anything/bridge@1";
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum Kind {
27    Napi,
28    Wasm,
29    Pyo3,
30    /// `extern "C"` functions with the original names: a drop-in replacement for C code.
31    #[serde(rename = "c-abi")]
32    CAbi,
33    /// A JSON dispatcher over the port, called from a generated Go, Ruby or Java wrapper.
34    Ffi,
35}
36
37/// The global allocator of a crate with batches (`bridge --allocator`).
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
39pub enum Allocator {
40    /// mimalloc, built from C with `cc`. Wasm crates keep Rust's default allocator.
41    #[default]
42    #[serde(rename = "mimalloc")]
43    #[value(name = "mimalloc")]
44    Mimalloc,
45    /// rusty_alloc, a pure-Rust remake of mimalloc: no C compiler, and wasm crates get it too.
46    #[serde(rename = "rusty_alloc")]
47    #[value(name = "rusty_alloc", alias = "rusty-alloc")]
48    RustyAlloc,
49}
50
51impl Allocator {
52    fn is_default(&self) -> bool {
53        *self == Self::default()
54    }
55}
56
57/// What `bridge` generated; every later step starts from it.
58#[derive(Clone, Debug, Serialize, Deserialize)]
59pub struct Manifest {
60    pub schema: String,
61    /// The repository root: absolute, or relative to the crate folder (so a crate kept inside
62    /// the repository it ports works in any clone). Resolved when the manifest is loaded.
63    pub root: PathBuf,
64    /// `root` as written in the file, when it was relative; written back instead of the resolved
65    /// path.
66    #[serde(skip)]
67    pub root_written: Option<PathBuf>,
68    pub unit: String,
69    #[serde(default)]
70    pub language: crate::lang::Lang,
71    pub kind: Kind,
72    pub crate_name: String,
73    /// Exports ported to Rust.
74    pub exports: Vec<ExportedFn>,
75    /// Exported classes ported to Rust: a struct with `new` and methods.
76    #[serde(default)]
77    pub classes: Vec<ExportedClass>,
78    /// Exports that cannot cross the bridge as they are; they stay in TS and the shadow module
79    /// re-exports them from the original.
80    #[serde(default)]
81    pub js_only: Vec<JsOnly>,
82    /// Functions run over many items kept in Rust (`--batch function:param`).
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub batches: Vec<crate::codegen_batch::Batch>,
85    /// The global allocator when the crate has batches (`bridge --allocator`).
86    #[serde(default, skip_serializing_if = "Allocator::is_default")]
87    pub allocator: Allocator,
88    /// Floats match within this relative tolerance (`record --float-tolerance`).
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub float_tolerance: Option<f64>,
91    /// Objects match regardless of key order (`record --ignore-key-order`).
92    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
93    pub ignore_key_order: bool,
94}
95
96#[derive(Clone, Debug, Serialize, Deserialize)]
97pub struct JsOnly {
98    pub name: String,
99    pub file: String,
100    pub line: u32,
101    pub reason: String,
102}
103
104/// Whether values of the local type `name` can hold functions: the type has a function or
105/// method member, or extends or mentions a type that does.
106fn has_functions(name: &str, local_types: &[LocalType], seen: &mut Vec<String>) -> bool {
107    if seen.iter().any(|s| s == name) {
108        return false;
109    }
110    seen.push(name.to_string());
111    let Some(t) = local_types.iter().find(|t| t.name == name) else {
112        return false;
113    };
114    let text = &t.text;
115    let method = text.lines().skip(1).any(|l| {
116        let l = l.trim().trim_start_matches("readonly ");
117        l.contains('(')
118            && l.split('(').next().is_some_and(|head| {
119                !head.is_empty()
120                    && head
121                        .chars()
122                        .all(|c| c.is_alphanumeric() || c == '_' || c == '?')
123            })
124    });
125    if text.contains("=>") || method {
126        return true;
127    }
128    text.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
129        .filter(|w| !w.is_empty() && *w != name)
130        .any(|w| has_functions(w, local_types, seen))
131}
132
133/// The exported functions of a TS/JS `file` with the types `bridge` judges them by: a sibling
134/// `.d.ts` applied, aliases resolved and generic constraints substituted. `analyze` counts
135/// bridgeable exports from the same list.
136pub fn ts_functions(root: &Path, file: &str, text: &str, types: &[LocalType]) -> Vec<ExportedFn> {
137    let mut functions = exported_functions(file, text);
138    crate::ts::jsdoc::apply_declarations(root, file, &mut functions);
139    for f in &mut functions {
140        for p in &mut f.params {
141            p.ts_type = resolve_aliases(&p.ts_type, types);
142        }
143        f.returns = resolve_aliases(&f.returns, types);
144        substitute_constraints(f, types);
145    }
146    functions
147}
148
149/// Why a class has to stay in the source language: its blocker, else the first method (and, for
150/// TS/JS, the constructor) that cannot cross. `None` when it can be bridged.
151pub fn class_reason(class: &ExportedClass, types: &[LocalType], ts: bool) -> Option<String> {
152    let constructor = ts.then(|| ExportedFn {
153        name: format!("{} constructor", class.name),
154        file: class.file.clone(),
155        line: class.line,
156        params: class.constructor.clone(),
157        returns: "void".into(),
158        ..Default::default()
159    });
160    class.blocker.clone().or_else(|| {
161        constructor
162            .iter()
163            .chain(&class.methods)
164            .find_map(|m| js_only_reason(m, types).map(|r| format!("`{}`: {r}", m.name)))
165    })
166}
167
168/// Why an export cannot cross a JS/Rust bridge unchanged, if it cannot.
169///
170/// Functions, iterators, RegExp objects and objects with function members are JS values a
171/// Rust function can neither take nor return; porting them would change the public API.
172pub fn js_only_reason(f: &ExportedFn, local_types: &[LocalType]) -> Option<String> {
173    if let Some(blocker) = &f.blocker {
174        return Some(blocker.clone());
175    }
176    if f.is_generator {
177        return Some("generator: returns a lazy iterator".into());
178    }
179    if f.uses_instanceof {
180        return Some("checks `instanceof`: class identity does not survive the bridge".into());
181    }
182    let types: Vec<&str> = f
183        .params
184        .iter()
185        .map(|p| p.ts_type.as_str())
186        .chain(std::iter::once(f.returns.as_str()))
187        .collect();
188    if types.iter().any(|t| t.contains("=>")) {
189        return Some("takes or returns a function".into());
190    }
191    let words = |t: &str| -> Vec<String> {
192        t.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
193            .filter(|w| !w.is_empty())
194            .map(str::to_string)
195            .collect()
196    };
197    for t in &types {
198        for word in words(t) {
199            match word.as_str() {
200                "RegExp" => return Some("takes or returns a RegExp".into()),
201                "Generator" | "Iterator" | "IterableIterator" | "AsyncGenerator"
202                | "AsyncIterable" => {
203                    return Some(format!("uses `{word}`, a lazy iterator"));
204                }
205                "Function" => return Some("takes or returns a function".into()),
206                _ => {}
207            }
208            if f.type_params.contains(&word) {
209                return Some(format!(
210                    "generic over `{word}`: values of any shape, functions included"
211                ));
212            }
213            if has_functions(&word, local_types, &mut Vec::new()) {
214                return Some(format!("uses `{word}`, which has function members"));
215            }
216        }
217    }
218    None
219}
220
221impl Manifest {
222    pub fn load(crate_dir: &Path) -> Result<Self> {
223        let path = crate_dir.join(MANIFEST);
224        let text = std::fs::read_to_string(&path).with_context(|| {
225            format!(
226                "reading {} (run `rust-anything bridge` first)",
227                path.display()
228            )
229        })?;
230        let mut manifest: Self =
231            serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
232        if manifest.root.is_relative() {
233            let resolved = crate_dir.join(&manifest.root);
234            let resolved = resolved.canonical().unwrap_or(resolved);
235            manifest.root_written = Some(std::mem::replace(&mut manifest.root, resolved));
236        }
237        Ok(manifest)
238    }
239
240    /// Writes the manifest back, keeping a relative root relative.
241    pub fn save(&self, crate_dir: &Path) -> Result<()> {
242        let mut m = self.clone();
243        if let Some(written) = m.root_written.take() {
244            m.root = written;
245        }
246        let path = crate_dir.join(MANIFEST);
247        std::fs::write(&path, serde_json::to_string_pretty(&m)? + "\n")
248            .with_context(|| format!("writing {}", path.display()))
249    }
250
251    /// Rust library name: the crate name with `-` replaced.
252    pub fn lib_name(&self) -> String {
253        self.crate_name.replace('-', "_")
254    }
255}
256
257pub struct Options<'a> {
258    pub root: &'a Path,
259    pub unit: &'a str,
260    pub kind: Option<Kind>,
261    pub out: Option<PathBuf>,
262    pub name: Option<String>,
263    /// Bridge a unit the plan marks blocked or keep.
264    pub force: bool,
265    /// Exports to keep in TS, with an optional reason: `name` or `name: reason`.
266    pub keep: Vec<String>,
267    /// Source language; detected from the repository when `None`.
268    pub lang: Option<crate::lang::Lang>,
269    /// `function:param` pairs: batch classes running `function` over many `param` values.
270    pub batch: Vec<String>,
271    /// Type parameters the app only fills with data: bridged as JSON values instead of keeping
272    /// the export in TS.
273    pub as_json: Vec<String>,
274    /// The global allocator for crates with batches.
275    pub allocator: Allocator,
276}
277
278#[derive(Debug, Serialize)]
279pub struct Outcome {
280    pub crate_dir: PathBuf,
281    pub kind: Kind,
282    pub files: Vec<String>,
283    pub exports: Vec<String>,
284    pub notes: Vec<String>,
285}
286
287/// A Rust type as seen by the port, from a TS type annotation.
288#[derive(Clone, Debug, PartialEq, Eq)]
289pub enum RType {
290    Str,
291    F64,
292    /// A whole number (`int` in the type dialect: Python, Go, Java and C have one; JS does not).
293    Int,
294    Bool,
295    /// A byte buffer (`bytes` in the type dialect): `Vec<u8>` in the port.
296    Bytes,
297    Unit,
298    Vec(Box<RType>),
299    Opt(Box<RType>),
300    /// Anything structured: crosses the bridge as JSON.
301    Json,
302}
303
304impl RType {
305    pub fn from_ts(ts: &str) -> Self {
306        let ts = ts.trim().trim_start_matches("readonly ").trim();
307        // `(string | null)`: one parenthesized group around the whole type.
308        if let Some(inner) = ts.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
309            && balanced(inner)
310        {
311            return Self::from_ts(inner);
312        }
313        if let Some(inner) = ts
314            .strip_prefix("Promise<")
315            .and_then(|t| t.strip_suffix('>'))
316        {
317            return Self::from_ts(inner);
318        }
319        let parts = split_top(ts, '|');
320        if parts.len() > 1 {
321            let (nullish, rest): (Vec<&str>, Vec<&str>) = parts
322                .iter()
323                .partition(|p| matches!(p.trim(), "undefined" | "null" | "void"));
324            if rest.iter().all(|p| is_string_literal(p)) {
325                return Self::wrap_opt(Self::Str, !nullish.is_empty());
326            }
327            if rest.len() == 1 {
328                return Self::wrap_opt(Self::from_ts(rest[0]), !nullish.is_empty());
329            }
330            return Self::Json;
331        }
332        if let Some(inner) = ts.strip_suffix("[]") {
333            return Self::Vec(Box::new(Self::from_ts(
334                inner.trim_start_matches('(').trim_end_matches(')'),
335            )));
336        }
337        for wrapper in ["Array<", "ReadonlyArray<"] {
338            if let Some(inner) = ts.strip_prefix(wrapper).and_then(|t| t.strip_suffix('>')) {
339                return Self::Vec(Box::new(Self::from_ts(inner)));
340            }
341        }
342        // `value is MessageLeaf`: a type predicate returns a boolean; `asserts x` returns nothing.
343        if ts.starts_with("asserts ") {
344            return Self::Unit;
345        }
346        if let Some((subject, _)) = ts.split_once(" is ")
347            && subject
348                .trim()
349                .chars()
350                .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
351        {
352            return Self::Bool;
353        }
354        match ts {
355            "string" => Self::Str,
356            "number" => Self::F64,
357            "int" => Self::Int,
358            "boolean" => Self::Bool,
359            "pybytes" => Self::Bytes,
360            "void" | "undefined" => Self::Unit,
361            _ if is_string_literal(ts) => Self::Str,
362            _ => Self::Json,
363        }
364    }
365
366    fn wrap_opt(t: Self, optional: bool) -> Self {
367        if optional { Self::Opt(Box::new(t)) } else { t }
368    }
369
370    pub fn rust(&self) -> String {
371        match self {
372            Self::Str => "String".into(),
373            Self::F64 => "f64".into(),
374            Self::Int => "i64".into(),
375            Self::Bool => "bool".into(),
376            Self::Bytes => "Vec<u8>".into(),
377            Self::Unit => "()".into(),
378            Self::Vec(t) => format!("Vec<{}>", t.rust()),
379            Self::Opt(t) => format!("Option<{}>", t.rust()),
380            Self::Json => "serde_json::Value".into(),
381        }
382    }
383
384    pub fn contains_json(&self) -> bool {
385        match self {
386            Self::Json => true,
387            Self::Vec(t) | Self::Opt(t) => t.contains_json(),
388            _ => false,
389        }
390    }
391}
392
393fn is_string_literal(ts: &str) -> bool {
394    let ts = ts.trim();
395    ts.len() >= 2
396        && ((ts.starts_with('\'') && ts.ends_with('\''))
397            || (ts.starts_with('"') && ts.ends_with('"')))
398}
399
400fn balanced(ts: &str) -> bool {
401    let mut depth = 0i32;
402    for c in ts.chars() {
403        match c {
404            '(' => depth += 1,
405            ')' => {
406                depth -= 1;
407                if depth < 0 {
408                    return false;
409                }
410            }
411            _ => {}
412        }
413    }
414    depth == 0
415}
416
417/// Splits on `sep` outside brackets.
418fn split_top(ts: &str, sep: char) -> Vec<&str> {
419    let mut out = Vec::new();
420    let mut depth = 0i32;
421    let mut start = 0;
422    for (i, c) in ts.char_indices() {
423        match c {
424            '<' | '(' | '[' | '{' => depth += 1,
425            '>' | ')' | ']' | '}' => depth -= 1,
426            c if c == sep && depth == 0 => {
427                out.push(ts[start..i].trim());
428                start = i + c.len_utf8();
429            }
430            _ => {}
431        }
432    }
433    out.push(ts[start..].trim());
434    out.retain(|p| !p.is_empty());
435    out
436}
437
438/// A parameter's type for the port, rest and optional parameters included.
439pub fn param_type(p: &crate::ts::exports::Param) -> RType {
440    let base = RType::from_ts(&p.ts_type);
441    let base = if p.rest {
442        match base {
443            RType::Vec(_) => base,
444            other => RType::Vec(Box::new(other)),
445        }
446    } else {
447        base
448    };
449    if p.optional && !matches!(base, RType::Opt(_)) {
450        RType::Opt(Box::new(base))
451    } else {
452        base
453    }
454}
455
456pub fn snake_case(name: &str) -> String {
457    let chars: Vec<char> = name.chars().collect();
458    let mut out = String::new();
459    for (i, &c) in chars.iter().enumerate() {
460        if c.is_uppercase() {
461            let prev = i.checked_sub(1).map(|j| chars[j]);
462            let next = chars.get(i + 1);
463            let boundary = prev.is_some_and(|p| p.is_lowercase() || p.is_ascii_digit())
464                || (prev.is_some_and(char::is_uppercase) && next.is_some_and(|n| n.is_lowercase()));
465            if boundary {
466                out.push('_');
467            }
468            out.extend(c.to_lowercase());
469        } else if c.is_alphanumeric() {
470            out.push(c);
471        } else {
472            out.push('_');
473        }
474    }
475    rust_ident(&out)
476}
477
478const KEYWORDS: &[&str] = &[
479    "as", "break", "const", "continue", "else", "enum", "extern", "false", "fn", "for", "if",
480    "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "static",
481    "struct", "trait", "true", "type", "unsafe", "use", "where", "while", "async", "await", "dyn",
482    "abstract", "become", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized",
483    "virtual", "yield", "try", "gen",
484];
485
486pub(crate) fn rust_ident(word: &str) -> String {
487    if matches!(word, "self" | "Self" | "super" | "crate" | "_") {
488        format!("{word}_")
489    } else if KEYWORDS.contains(&word) {
490        format!("r#{word}")
491    } else {
492        word.to_string()
493    }
494}
495
496/// Types declared in `file` and in the files it imports relatively (one level deep).
497pub fn types_in_scope(root: &Path, file: &str, text: &str) -> Vec<LocalType> {
498    let mut types = Vec::new();
499    let mut seen = std::collections::HashSet::new();
500    collect_types(root, file, text, 0, &mut seen, &mut types);
501    types
502}
503
504/// Types of a file and of the files it imports or re-exports, a few levels deep
505/// (`./types` -> `types/index.ts` -> `export * from './host'`).
506fn collect_types(
507    root: &Path,
508    file: &str,
509    text: &str,
510    depth: usize,
511    seen: &mut std::collections::HashSet<String>,
512    types: &mut Vec<LocalType>,
513) {
514    if depth > 4 || !seen.insert(file.to_string()) {
515        return;
516    }
517    types.extend(local_types(file, text));
518    let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
519    for import in crate::ts::scan::scan(file, text).imports {
520        let spec = import.specifier;
521        // Workspace packages (`@x18n/core`) are followed to their source entry.
522        let base = if spec.starts_with('.') {
523            let joined = if dir.is_empty() {
524                spec.clone()
525            } else {
526                format!("{dir}/{spec}")
527            };
528            match normalize_rel(&joined) {
529                Some(base) => base,
530                None => continue,
531            }
532        } else {
533            let name = crate::ts::deps::package_name(&spec);
534            let Some(pkg_dir) = workspace_packages(root).get(name).cloned() else {
535                continue;
536            };
537            let sub = spec[name.len()..].trim_start_matches('/');
538            let src = if root.join(&pkg_dir).join("src").is_dir() {
539                format!("{pkg_dir}/src")
540            } else {
541                pkg_dir
542            };
543            let src = src.trim_start_matches('/').to_string();
544            if sub.is_empty() {
545                format!("{src}/index")
546            } else {
547                format!("{src}/{sub}")
548            }
549        };
550        let stem = base.trim_end_matches(".js");
551        let candidates = [
552            format!("{stem}.ts"),
553            format!("{stem}.mts"),
554            format!("{stem}.d.ts"),
555            format!("{stem}/index.ts"),
556            base.clone(),
557        ];
558        if let Some(found) = candidates.iter().find(|c| root.join(c).is_file())
559            && let Ok(imported) = std::fs::read_to_string(root.join(found))
560        {
561            collect_types(root, found, &imported, depth + 1, seen, types);
562        }
563    }
564}
565
566/// Workspace package names and their root-relative folders, read once per root.
567fn workspace_packages(root: &Path) -> std::collections::HashMap<String, String> {
568    use std::sync::{Mutex, OnceLock};
569    static CACHE: OnceLock<
570        Mutex<std::collections::HashMap<PathBuf, std::collections::HashMap<String, String>>>,
571    > = OnceLock::new();
572    let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
573    let mut cache = cache
574        .lock()
575        .unwrap_or_else(std::sync::PoisonError::into_inner);
576    cache
577        .entry(root.to_path_buf())
578        .or_insert_with(|| {
579            crate::ts::discover::discover(root)
580                .map(|ws| ws.packages.into_iter().map(|p| (p.name, p.dir)).collect())
581                .unwrap_or_default()
582        })
583        .clone()
584}
585
586/// Collapses `.` and `..` in a root-relative path.
587fn normalize_rel(path: &str) -> Option<String> {
588    let mut parts: Vec<&str> = Vec::new();
589    for part in path.split('/') {
590        match part {
591            "" | "." => {}
592            ".." => {
593                parts.pop()?;
594            }
595            _ => parts.push(part),
596        }
597    }
598    Some(parts.join("/"))
599}
600
601/// `f<T extends string>(s: T)` takes a string: type parameters with a simple constraint are
602/// replaced by it. The rest stay listed, and keep the function in TS.
603pub fn substitute_constraints(f: &mut ExportedFn, types: &[LocalType]) {
604    let mut remaining = Vec::new();
605    for tp in std::mem::take(&mut f.type_params) {
606        let Some((name, constraint)) = tp.split_once(" extends ") else {
607            remaining.push(tp);
608            continue;
609        };
610        let constraint = resolve_aliases(constraint, types);
611        // Data constraints (`string`, `string | readonly string[]`) are substituted; anything that
612        // could hold a function keeps the type parameter, and the function stays in TS.
613        let open_ended = constraint.contains("=>")
614            || constraint
615                .split(|c: char| !(c.is_alphanumeric() || c == '_'))
616                .any(|w| {
617                    matches!(w, "Function" | "object" | "unknown" | "any")
618                        || has_functions(w, types, &mut Vec::new())
619                });
620        if open_ended {
621            remaining.push(name.to_string());
622            continue;
623        }
624        let replacement = format!("({constraint})");
625        for p in &mut f.params {
626            p.ts_type = replace_word(&p.ts_type, name, &replacement);
627        }
628        f.returns = replace_word(&f.returns, name, &replacement);
629    }
630    f.type_params = remaining;
631}
632
633/// Turns the type parameters named in `names` into `unknown` (a JSON value on the Rust side).
634pub fn substitute_json(f: &mut ExportedFn, names: &[String]) {
635    let mut remaining = Vec::new();
636    for tp in std::mem::take(&mut f.type_params) {
637        let name = tp
638            .split_once(" extends ")
639            .map_or(tp.as_str(), |(n, _)| n)
640            .trim();
641        if !names.iter().any(|n| n == name) {
642            remaining.push(tp);
643            continue;
644        }
645        for p in &mut f.params {
646            p.ts_type = replace_word(&p.ts_type, name, "unknown");
647        }
648        f.returns = replace_word(&f.returns, name, "unknown");
649    }
650    f.type_params = remaining;
651}
652
653fn replace_word(text: &str, word: &str, with: &str) -> String {
654    let mut out = String::new();
655    let mut current = String::new();
656    for c in text.chars().chain(std::iter::once(' ')) {
657        if c.is_alphanumeric() || c == '_' || c == '$' {
658            current.push(c);
659        } else {
660            out.push_str(if current == word { with } else { &current });
661            current.clear();
662            out.push(c);
663        }
664    }
665    out.pop();
666    out
667}
668
669/// Replaces simple type aliases (`type KeyString = string`) by what they stand for.
670pub fn resolve_aliases(ts: &str, types: &[LocalType]) -> String {
671    let mut out = ts.to_string();
672    for _ in 0..4 {
673        let mut changed = false;
674        let mut next = String::with_capacity(out.len());
675        let mut word = String::new();
676        let flush = |word: &mut String, next: &mut String, changed: &mut bool| {
677            if let Some(t) = types.iter().find(|t| t.alias && t.name == *word) {
678                let text = t.text.trim();
679                if text.contains('|') {
680                    next.push('(');
681                    next.push_str(text);
682                    next.push(')');
683                } else {
684                    next.push_str(text);
685                }
686                *changed = true;
687            } else {
688                next.push_str(word);
689            }
690            word.clear();
691        };
692        for c in out.chars() {
693            if c.is_alphanumeric() || c == '_' || c == '$' {
694                word.push(c);
695            } else {
696                flush(&mut word, &mut next, &mut changed);
697                next.push(c);
698            }
699        }
700        flush(&mut word, &mut next, &mut changed);
701        out = next;
702        if !changed {
703            break;
704        }
705    }
706    out
707}
708
709fn needs_js(api: &codegen::PortApi) -> bool {
710    api.needs_json()
711}
712
713/// The name and the reason of a `--keep name` or `--keep "name: reason"` entry, trimmed.
714fn keep_entry(k: &str) -> (&str, &str) {
715    let (name, reason) = k.split_once(':').unwrap_or((k, ""));
716    (name.trim(), reason.trim())
717}
718
719/// Fails when a `--keep` entry names none of the unit's exports and classes (`names`), so a typo
720/// does not bridge the export it meant to keep.
721fn check_keep(keep: &[String], names: &[&str], unit: &str) -> Result<()> {
722    if let Some((name, _)) = keep
723        .iter()
724        .map(|k| keep_entry(k))
725        .find(|(name, _)| !names.contains(name))
726    {
727        let mut known = names.to_vec();
728        known.sort_unstable();
729        known.dedup();
730        bail!(
731            "--keep `{name}` is not an export of `{unit}` (exports: {})",
732            known.join(", ")
733        );
734    }
735    Ok(())
736}
737
738/// The reason given with `--keep name` or `--keep "name: reason"`, if `name` is kept.
739fn keep_reason(keep: &[String], name: &str) -> Option<String> {
740    keep.iter().find_map(|k| {
741        let (kept, reason) = keep_entry(k);
742        (kept == name).then(|| {
743            if reason.is_empty() {
744                "kept on request".to_string()
745            } else {
746                reason.to_string()
747            }
748        })
749    })
750}
751
752/// Formats the generated Rust, best effort: the gate checks formatting.
753fn format_rust(crate_dir: &Path) {
754    let files: Vec<PathBuf> = std::fs::read_dir(crate_dir.join("src"))
755        .into_iter()
756        .flatten()
757        .flatten()
758        .map(|e| e.path())
759        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
760        .collect();
761    let _ = std::process::Command::new("rustfmt")
762        .args(["--edition", "2024"])
763        .args(&files)
764        .output();
765}
766
767/// Formats a generated Go wrapper with `gofmt`, best effort.
768fn format_wrapper(crate_dir: &Path) {
769    if crate_dir.join("go").is_dir() {
770        let _ = std::process::Command::new("gofmt")
771            .arg("-w")
772            .arg(crate_dir.join("go"))
773            .output();
774    }
775}
776
777/// `lib.rs` of a JS crate: the bindings, and the binary wire when functions use it.
778fn js_lib_rs(m: &Manifest, api: &codegen::PortApi, modules: &codegen::Modules) -> Result<String> {
779    let mut lib = with_allocator(m, codegen::lib_rs(m, api, modules));
780    if m.kind != Kind::Pyo3 && !m.batches.is_empty() {
781        lib.push_str(&crate::codegen_batch::js_rs(m, api).map_err(anyhow::Error::msg)?);
782    }
783    if !crate::codegen_tswire::uses_wire(m, api) {
784        return Ok(lib);
785    }
786    Ok(lib.replacen(
787        "pub mod port;",
788        "pub mod port;\npub mod wire;\n\n#[allow(unused_imports)]\nuse serde_json::Value;",
789        1,
790    ) + &crate::codegen_tswire::napi_rs(m, api))
791}
792
793fn parse_batches(specs: &[String]) -> Result<Vec<crate::codegen_batch::Batch>> {
794    specs
795        .iter()
796        .map(|s| {
797            crate::codegen_batch::Batch::parse(s)
798                .with_context(|| format!("`--batch {s}`: write it as function:param"))
799        })
800        .collect()
801}
802
803/// Fails when `lang` or `kind` has no batch generator yet, so `bridge` and `refresh --batch`
804/// refuse `--batch` in one place with the same message.
805fn ensure_batch_support(lang: crate::lang::Lang, kind: Kind) -> Result<()> {
806    use crate::lang::Lang;
807    let unsupported = match lang {
808        Lang::C | Lang::Php | Lang::Csharp | Lang::Powershell => Some(lang.name()),
809        _ if kind == Kind::CAbi => Some(Lang::C.name()),
810        _ => None,
811    };
812    if let Some(name) = unsupported {
813        bail!("`--batch` is not available for {name} units yet");
814    }
815    Ok(())
816}
817
818/// Adds batch classes to a bridged crate, then regenerates its bindings.
819pub fn add_batches(crate_dir: &Path, specs: &[String]) -> Result<Refreshed> {
820    let path = crate_dir.join(MANIFEST);
821    let before = std::fs::read_to_string(&path).with_context(|| format!("{}", path.display()))?;
822    let mut manifest = Manifest::load(crate_dir)?;
823    if !specs.is_empty() {
824        ensure_batch_support(manifest.language, manifest.kind)?;
825    }
826    for b in parse_batches(specs)? {
827        if !manifest.batches.contains(&b) {
828            manifest.batches.push(b);
829        }
830    }
831    if let Some(written) = manifest.root_written.clone() {
832        manifest.root = written;
833    }
834    std::fs::write(&path, serde_json::to_string_pretty(&manifest)? + "\n")?;
835    // A batch the port cannot serve leaves the crate as it was.
836    refresh(crate_dir).inspect_err(|_| {
837        let _ = std::fs::write(&path, &before);
838    })
839}
840
841/// Cargo.toml with the dependencies and library types today's bindings need, for crates
842/// bridged by an older rust-anything; versions and features already set are kept.
843fn with_template_deps(cargo: &str, template: &str) -> Result<String> {
844    let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
845    let template: toml_edit::DocumentMut = template.parse().context("Cargo.toml template")?;
846    if let Some(want) = template.get("dependencies").and_then(|d| d.as_table()) {
847        let deps = doc["dependencies"].or_insert(toml_edit::table());
848        for (name, item) in want {
849            if deps.get(name).is_none() {
850                deps[name] = item.clone();
851            }
852        }
853    }
854    if let Some(want) = template.get("features").and_then(|d| d.as_table()) {
855        let features = doc["features"].or_insert(toml_edit::table());
856        for (name, item) in want {
857            if features.get(name).is_none() {
858                features[name] = item.clone();
859            }
860        }
861    }
862    if let Some(kinds) = template.get("lib").and_then(|l| l.get("crate-type")) {
863        doc["lib"]["crate-type"] = kinds.clone();
864    }
865    Ok(doc.to_string())
866}
867
868/// The global allocator of a crate, if it sets one: crates with batches allocate from all cores
869/// at once (the system allocator serializes them: 1.6x on 4 cores instead of 3.2x). mimalloc
870/// leaves wasm alone, which runs on one thread; rusty_alloc also replaces Rust's wasm allocator.
871/// Only Rust code uses this heap; every buffer that crosses the bridge is copied or freed by Rust.
872fn global_allocator(m: &Manifest) -> Option<Allocator> {
873    if m.batches.is_empty() {
874        return None;
875    }
876    match m.allocator {
877        Allocator::Mimalloc if m.kind == Kind::Wasm => None,
878        a => Some(a),
879    }
880}
881
882/// `lib.rs` with the [`global_allocator`].
883fn with_allocator(m: &Manifest, lib: String) -> String {
884    let line = match global_allocator(m) {
885        None => return lib,
886        Some(Allocator::Mimalloc) => {
887            "/// Batches allocate on all cores at once; mimalloc keeps that from serializing.\n\
888             #[global_allocator]\nstatic GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;\n"
889        }
890        Some(Allocator::RustyAlloc) => {
891            "/// Batches allocate on all cores at once; rusty_alloc keeps that from serializing.\n\
892             #[global_allocator]\n\
893             static GLOBAL: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;\n"
894        }
895    };
896    lib.replacen("pub mod port;", &format!("pub mod port;\n\n{line}"), 1)
897}
898
899/// Cargo.toml with rayon (and the global allocator) when batches run on all cores.
900fn with_rayon(m: &Manifest, cargo: String) -> Result<String> {
901    let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
902    let deps = doc["dependencies"].or_insert(toml_edit::table());
903    // Batch methods take their other parameters as napi values; structured ones need serde.
904    if m.kind == Kind::Napi
905        && !m.batches.is_empty()
906        && let Some(napi) = deps.get_mut("napi")
907    {
908        let mut table = toml_edit::InlineTable::new();
909        match napi {
910            toml_edit::Item::Value(toml_edit::Value::String(v)) => {
911                table.insert("version", v.value().clone().into());
912            }
913            toml_edit::Item::Value(toml_edit::Value::InlineTable(t)) => table = t.clone(),
914            _ => {}
915        }
916        let mut features = table
917            .get("features")
918            .and_then(|f| f.as_array())
919            .cloned()
920            .unwrap_or_default();
921        if !features.iter().any(|f| f.as_str() == Some("serde-json")) {
922            features.push("serde-json");
923        }
924        table.insert("features", toml_edit::Value::Array(features));
925        *napi = toml_edit::value(table);
926    }
927    if !crate::codegen_batch::needs_rayon(m) {
928        return Ok(doc.to_string());
929    }
930    if deps.get("rayon").is_none() {
931        deps["rayon"] = toml_edit::value("1");
932    }
933    let allocator = match global_allocator(m) {
934        Some(Allocator::Mimalloc) => Some(("mimalloc", "0.1")),
935        Some(Allocator::RustyAlloc) => Some(("rusty_alloc-api", "2.6")),
936        None => None,
937    };
938    if let Some((name, version)) = allocator
939        && deps.get(name).is_none()
940    {
941        deps[name] = toml_edit::value(version);
942    }
943    Ok(doc.to_string())
944}
945
946/// The language-side loader: `index.cjs` for JS, the wrapper package for Python.
947fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
948    match m.kind {
949        Kind::Pyo3 => (
950            format!("python/{}/__init__.py", m.lib_name()),
951            crate::codegen_py::package_init(m, api),
952        ),
953        _ => (
954            "index.cjs".into(),
955            codegen::index_cjs(m, api)
956                + &crate::codegen_tswire::index_cjs(m, api)
957                + &crate::codegen_batch::index_cjs(m, api)
958                + &codegen::guard_cjs(api, &crate::codegen_tswire::wired(m, api)),
959        ),
960    }
961}
962
963/// A port function whose doc line does not name an export (`/// Port of \`Integer.toString\``)
964/// takes the name of the export it was generated for, matched by its Rust name.
965pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
966    for f in &mut api.functions {
967        if m.exports.iter().any(|e| e.name == f.js_name) {
968            continue;
969        }
970        let rust = f.rust_name.trim_start_matches("r#");
971        if let Some(e) = m
972            .exports
973            .iter()
974            .find(|e| snake_case(&e.name).trim_start_matches("r#") == rust)
975        {
976            f.js_name = e.name.clone();
977        }
978    }
979}
980
981/// What `refresh` rewrote.
982#[derive(Debug, Serialize)]
983pub struct Refreshed {
984    pub functions: Vec<String>,
985    pub files: Vec<String>,
986}
987
988/// Regenerates the binding layer (`lib.rs`, `index.cjs`, `js.rs`) from the signatures in
989/// `port.rs`, and adds the dependencies they need to Cargo.toml. Never touches `port.rs`.
990pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
991    let manifest = Manifest::load(crate_dir)?;
992    if manifest.kind == Kind::CAbi {
993        let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
994            .context("reading src/port.rs")?;
995        let mut files = c_bindings(&manifest, &port);
996        let cargo =
997            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
998        files.push((
999            "Cargo.toml".into(),
1000            with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
1001        ));
1002        write_files(crate_dir, &files)?;
1003        format_rust(crate_dir);
1004        return Ok(Refreshed {
1005            functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1006            files: files.into_iter().map(|(p, _)| p).collect(),
1007        });
1008    }
1009    if manifest.kind == Kind::Ffi {
1010        let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
1011            .context("reading src/port.rs")?;
1012        let mut api = codegen::parse_port(&port);
1013        match_export_names(&manifest, &mut api);
1014        let mut files = ffi_bindings(&manifest, &api)?;
1015        let cargo =
1016            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
1017        let template = if manifest.language == crate::lang::Lang::Ruby {
1018            crate::codegen_ruby::cargo_toml(&manifest)
1019        } else {
1020            crate::codegen_ffi::cargo_toml(&manifest)
1021        };
1022        let cargo = with_template_deps(&cargo, &template)?;
1023        files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
1024        write_files(crate_dir, &files)?;
1025        format_rust(crate_dir);
1026        format_wrapper(crate_dir);
1027        return Ok(Refreshed {
1028            functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
1029            files: files.into_iter().map(|(p, _)| p).collect(),
1030        });
1031    }
1032    let port =
1033        std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
1034    let mut fns = codegen::parse_port(&port);
1035    match_export_names(&manifest, &mut fns);
1036    if fns.functions.is_empty() && fns.classes.is_empty() {
1037        bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
1038    }
1039    let modules = codegen::Modules {
1040        utf16: crate_dir.join("src/utf16.rs").exists(),
1041        js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
1042    };
1043    let mut files: Vec<(String, String)> = vec![
1044        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1045        loader_file(&manifest, &fns),
1046    ];
1047    if modules.js {
1048        files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
1049    }
1050    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1051        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1052    }
1053    let extension = manifest.kind == Kind::Pyo3
1054        || (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
1055    if extension && !crate_dir.join("build.rs").exists() {
1056        files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
1057    }
1058    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1059        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1060        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1061    }
1062    let cargo_path = crate_dir.join("Cargo.toml");
1063    let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
1064    let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns).map_err(anyhow::Error::msg)?;
1065    let cargo = with_rayon(&manifest, cargo)?;
1066    files.push(("Cargo.toml".into(), cargo));
1067    for (path, text) in &files {
1068        let target = crate_dir.join(path);
1069        if let Some(parent) = target.parent() {
1070            std::fs::create_dir_all(parent)?;
1071        }
1072        std::fs::write(&target, text).with_context(|| format!("writing {path}"))?;
1073    }
1074    format_rust(crate_dir);
1075    Ok(Refreshed {
1076        functions: fns
1077            .functions
1078            .iter()
1079            .map(|f| f.js_name.clone())
1080            .chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
1081            .collect(),
1082        files: files.into_iter().map(|(p, _)| p).collect(),
1083    })
1084}
1085
1086/// `build.rs` for Python and Ruby extensions: on macOS the library (and its test binary) links
1087/// against symbols the interpreter provides only at load time.
1088pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
1089    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
1090        println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
1091    }
1092}
1093"#;
1094
1095/// Rejects Cargo package names that would produce invalid `Cargo.toml` / Rust library names or
1096/// write outside `<root>/rust/` via path separators.
1097fn validate_crate_name(name: &str) -> Result<&str> {
1098    const RUST_KEYWORDS: &[&str] = &[
1099        "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
1100        "extern", "false", "fn", "for", "gen", "if", "impl", "in", "let", "loop", "match", "mod",
1101        "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super",
1102        "trait", "true", "type", "unsafe", "use", "where", "while", "abstract", "become", "box",
1103        "do", "final", "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
1104    ];
1105    const WINDOWS_RESERVED: &[&str] = &[
1106        "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",
1107        "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
1108    ];
1109    let first = name.bytes().next();
1110    let valid_chars = first.is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
1111        && name
1112            .bytes()
1113            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
1114    if !valid_chars {
1115        bail!(
1116            "invalid crate name `{name}`: must be non-empty, start with an ASCII letter or `_`, \
1117             and use only ASCII letters, digits, `-` and `_`"
1118        );
1119    }
1120    let lib = name.replace('-', "_");
1121    if lib == "_" || RUST_KEYWORDS.contains(&lib.as_str()) {
1122        bail!("invalid crate name `{name}`: `{lib}` is a reserved Rust keyword");
1123    }
1124    let lower = name.to_ascii_lowercase();
1125    if WINDOWS_RESERVED.contains(&lower.as_str()) {
1126        bail!("invalid crate name `{name}`: `{name}` is a reserved filename on Windows");
1127    }
1128    Ok(name)
1129}
1130
1131/// Derives a valid Cargo crate name from a unit's file/folder stem.
1132fn default_crate_name(stem: &str) -> String {
1133    let clean: String = stem
1134        .chars()
1135        .map(|c| {
1136            if c.is_ascii_alphanumeric() {
1137                c.to_ascii_lowercase()
1138            } else {
1139                '-'
1140            }
1141        })
1142        .collect();
1143    let trimmed = clean.trim_matches('-');
1144    if trimmed.is_empty() {
1145        "unit-rs".to_string()
1146    } else if trimmed.as_bytes()[0].is_ascii_digit() {
1147        format!("unit-{trimmed}-rs")
1148    } else {
1149        format!("{trimmed}-rs")
1150    }
1151}
1152
1153pub fn bridge(opts: &Options) -> Result<Outcome> {
1154    let explicit_name = opts.name.as_deref().map(validate_crate_name).transpose()?;
1155    let root = opts
1156        .root
1157        .canonical()
1158        .with_context(|| format!("resolving {}", opts.root.display()))?;
1159    let lang = opts
1160        .lang
1161        .unwrap_or_else(|| crate::lang::Lang::detect(&root));
1162    let report = analyze::analyze_lang(&root, lang)?;
1163    let wanted = opts.unit.trim_start_matches("./");
1164    let whole = report
1165        .units
1166        .iter()
1167        .find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'));
1168    let single = || {
1169        report
1170            .units
1171            .iter()
1172            .find(|u| u.files.iter().any(|f| f == wanted))
1173            .map(|u| {
1174                let mut one = u.clone();
1175                one.id = wanted.to_string();
1176                one.files = vec![wanted.to_string()];
1177                one
1178            })
1179    };
1180    let unit = match whole.cloned().or_else(single) {
1181        Some(unit) => unit,
1182        None => bail!(
1183            "no unit or source file `{wanted}`; `rust-anything analyze` lists unit ids, and any \
1184             source file inside a unit can be bridged on its own"
1185        ),
1186    };
1187    let unit = &unit;
1188    if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
1189        bail!(
1190            "unit `{}` is {:?}: {}. Pass --force to bridge it anyway.",
1191            unit.id,
1192            unit.status,
1193            unit.notes.first().map_or("", String::as_str)
1194        );
1195    }
1196    let kind = opts.kind.unwrap_or(match unit.bridge {
1197        Bridge::WasmBindgen => Kind::Wasm,
1198        Bridge::Pyo3 => Kind::Pyo3,
1199        Bridge::CAbi => Kind::CAbi,
1200        Bridge::Cgo
1201        | Bridge::Fiddle
1202        | Bridge::Jni
1203        | Bridge::PhpFfi
1204        | Bridge::DotnetFfi
1205        | Bridge::PwshFfi => Kind::Ffi,
1206        _ => Kind::Napi,
1207    });
1208    if !opts.batch.is_empty() {
1209        ensure_batch_support(lang, kind)?;
1210    }
1211
1212    let mut exports = Vec::new();
1213    let mut classes = Vec::new();
1214    let mut js_only = Vec::new();
1215    // Name and file of each overloaded function already kept, so its other overloads join it.
1216    let mut kept_overloads = std::collections::HashSet::new();
1217    if lang == crate::lang::Lang::C {
1218        crate::lang::c::use_typedefs(&root);
1219    }
1220    if lang == crate::lang::Lang::Csharp {
1221        crate::lang::csharp::use_shapes(&root);
1222    }
1223    for file in &unit.files {
1224        if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
1225            continue;
1226        }
1227        let text =
1228            std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
1229        if lang != crate::lang::Lang::Ts {
1230            let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
1231            for f in functions {
1232                // The overloads of one name (Java, Kotlin, C#) stay in the original together: one
1233                // name in one file, not two exports that would replace each other, whether they
1234                // stay for being overloaded or because `--keep` names them.
1235                let overload = f.blocker.as_deref() == Some(crate::lang::OVERLOADED);
1236                match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
1237                    Some(_)
1238                        if overload && !kept_overloads.insert((f.name.clone(), f.file.clone())) => {
1239                    }
1240                    Some(reason) => js_only.push(JsOnly {
1241                        name: f.name,
1242                        file: f.file,
1243                        line: f.line,
1244                        reason,
1245                    }),
1246                    None => exports.push(f),
1247                }
1248            }
1249            for class in foreign_classes {
1250                match keep_reason(&opts.keep, &class.name)
1251                    .or_else(|| class_reason(&class, &[], false))
1252                {
1253                    Some(reason) => js_only.push(JsOnly {
1254                        name: class.name,
1255                        file: class.file,
1256                        line: class.line,
1257                        reason: format!("class: {reason}"),
1258                    }),
1259                    None => classes.push(class),
1260                }
1261            }
1262            continue;
1263        }
1264        let types = types_in_scope(&root, file, &text);
1265        for mut class in exported_classes(file, &text) {
1266            let kept = keep_reason(&opts.keep, &class.name);
1267            match kept.or_else(|| class_reason(&class, &types, true)) {
1268                Some(reason) => js_only.push(JsOnly {
1269                    name: class.name,
1270                    file: class.file,
1271                    line: class.line,
1272                    reason: format!("class: {reason}"),
1273                }),
1274                None => {
1275                    for p in &mut class.constructor {
1276                        p.ts_type = resolve_aliases(&p.ts_type, &types);
1277                    }
1278                    for m in &mut class.methods {
1279                        for p in &mut m.params {
1280                            p.ts_type = resolve_aliases(&p.ts_type, &types);
1281                        }
1282                        m.returns = resolve_aliases(&m.returns, &types);
1283                    }
1284                    classes.push(class);
1285                }
1286            }
1287        }
1288        for mut f in ts_functions(&root, file, &text, &types) {
1289            substitute_json(&mut f, &opts.as_json);
1290            let kept = keep_reason(&opts.keep, &f.name);
1291            match kept.or_else(|| js_only_reason(&f, &types)) {
1292                Some(reason) => js_only.push(JsOnly {
1293                    name: f.name,
1294                    file: f.file,
1295                    line: f.line,
1296                    reason,
1297                }),
1298                None => exports.push(f),
1299            }
1300        }
1301    }
1302    let mut defined: Vec<(&str, String)> = exports
1303        .iter()
1304        .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1305        .chain(
1306            classes
1307                .iter()
1308                .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1309        )
1310        .chain(
1311            js_only
1312                .iter()
1313                .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1314        )
1315        .collect();
1316    defined.sort();
1317    check_keep(
1318        &opts.keep,
1319        &defined.iter().map(|(name, _)| *name).collect::<Vec<_>>(),
1320        &unit.id,
1321    )?;
1322    if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1323        bail!(
1324            "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1325             itself, so one would silently replace the other. Bridge the module you want on its \
1326             own (`rust-anything bridge <root> <that file>`), or rename one of them",
1327            pair[0].0,
1328            unit.id,
1329            pair[0].1,
1330            pair[1].1
1331        );
1332    }
1333    if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1334        bail!(
1335            "every export of `{}` must stay in {}: {}",
1336            unit.id,
1337            lang.name(),
1338            js_only
1339                .iter()
1340                .map(|j| format!("{} ({})", j.name, j.reason))
1341                .collect::<Vec<_>>()
1342                .join(", ")
1343        );
1344    }
1345    if exports.is_empty() && classes.is_empty() {
1346        bail!(
1347            "unit `{}` exports no functions; bridge a unit with an exported function API",
1348            unit.id
1349        );
1350    }
1351
1352    let stem = unit
1353        .id
1354        .trim_end_matches('/')
1355        .rsplit('/')
1356        .next()
1357        .unwrap_or("unit")
1358        .split('.')
1359        .next()
1360        .unwrap_or("unit");
1361    let crate_name = explicit_name
1362        .map(str::to_string)
1363        .unwrap_or_else(|| default_crate_name(stem));
1364    let crate_dir = opts
1365        .out
1366        .clone()
1367        .unwrap_or_else(|| root.join("rust").join(&crate_name));
1368    if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1369        bail!(
1370            "{} already exists and is not empty; rust-anything never overwrites a port in progress",
1371            crate_dir.display()
1372        );
1373    }
1374
1375    // UTF-16 helpers matter for JS strings only; Python indexes code points, like `chars()`.
1376    let utf16 =
1377        lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1378    let manifest = Manifest {
1379        schema: SCHEMA.into(),
1380        root: root.clone(),
1381        root_written: None,
1382        unit: unit.id.clone(),
1383        language: lang,
1384        kind,
1385        crate_name: crate_name.clone(),
1386        exports: exports.clone(),
1387        classes: classes.clone(),
1388        js_only: js_only.clone(),
1389        batches: parse_batches(&opts.batch)?,
1390        allocator: opts.allocator,
1391        float_tolerance: None,
1392        ignore_key_order: false,
1393    };
1394    if kind == Kind::CAbi {
1395        return bridge_c(&manifest, &crate_dir, &js_only);
1396    }
1397    if kind == Kind::Ffi {
1398        return bridge_ffi(&manifest, &crate_dir, &js_only);
1399    }
1400    let port = codegen::port_rs(&manifest);
1401    let fns = codegen::parse_port(&port);
1402    let modules = codegen::Modules {
1403        utf16,
1404        js: needs_js(&fns),
1405    };
1406    let mut files: Vec<(String, String)> = vec![
1407        (
1408            "Cargo.toml".into(),
1409            with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1410        ),
1411        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1412        ("src/port.rs".into(), port),
1413        loader_file(&manifest, &fns),
1414        (
1415            ".gitignore".into(),
1416            "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1417        ),
1418        ("README.md".into(), readme(&manifest)),
1419        (
1420            MANIFEST.into(),
1421            serde_json::to_string_pretty(&manifest)? + "\n",
1422        ),
1423    ];
1424    match kind {
1425        Kind::Napi => files.push((
1426            "build.rs".into(),
1427            "fn main() {\n    napi_build::setup();\n}\n".into(),
1428        )),
1429        Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1430        _ => {}
1431    }
1432    if utf16 {
1433        files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1434    }
1435    if modules.js {
1436        files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1437    }
1438    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1439        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1440    }
1441    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1442        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1443        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1444    }
1445    for (path, text) in &files {
1446        let target = crate_dir.join(path);
1447        if let Some(parent) = target.parent() {
1448            std::fs::create_dir_all(parent)?;
1449        }
1450        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1451    }
1452
1453    format_rust(&crate_dir);
1454    let mut notes = vec![format!(
1455        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1456        crate_dir.display()
1457    )];
1458    if utf16 {
1459        notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1460    }
1461    for j in &js_only {
1462        notes.push(format!(
1463            "`{}` stays in {}: {}. The shadow module re-exports the original.",
1464            j.name,
1465            lang.name(),
1466            j.reason
1467        ));
1468    }
1469    if exports.iter().any(codegen::is_async) {
1470        notes.push(
1471            "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1472        );
1473    }
1474    Ok(Outcome {
1475        crate_dir,
1476        kind,
1477        files: files.into_iter().map(|(p, _)| p).collect(),
1478        exports: exports
1479            .iter()
1480            .map(|f| f.name.clone())
1481            .chain(classes.iter().map(|c| format!("class {}", c.name)))
1482            .collect(),
1483        notes,
1484    })
1485}
1486
1487fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1488    for (path, text) in files {
1489        let target = crate_dir.join(path);
1490        if let Some(parent) = target.parent() {
1491            std::fs::create_dir_all(parent)?;
1492        }
1493        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1494    }
1495    Ok(())
1496}
1497
1498/// The generated C-side files: the `extern "C"` layer and its header. C signatures are fixed
1499/// by the original, so they come from the manifest, not from `port.rs`.
1500fn c_bindings(m: &Manifest, port: &str) -> Vec<(String, String)> {
1501    vec![
1502        ("src/lib.rs".into(), crate::codegen_c::lib_rs(m, port)),
1503        (
1504            format!("include/{}.h", m.lib_name()),
1505            crate::codegen_c::header(m),
1506        ),
1507    ]
1508}
1509
1510/// The generated layers of a JSON-dispatcher crate: `lib.rs` and the language-side wrapper.
1511fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1512    let mut files = if m.language == crate::lang::Lang::Ruby {
1513        vec![
1514            (
1515                "src/lib.rs".to_string(),
1516                with_allocator(
1517                    m,
1518                    crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1519                ),
1520            ),
1521            (
1522                "src/rbconv.rs".to_string(),
1523                crate::codegen_ruby::RBCONV_RS.to_string(),
1524            ),
1525            ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1526        ]
1527    } else {
1528        let mut lib = crate::codegen_ffi::lib_rs(m, api);
1529        if matches!(
1530            m.language,
1531            crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1532        ) {
1533            lib.push_str(&crate::codegen_java::typed_rs(m, api));
1534        }
1535        if m.language == crate::lang::Lang::Go {
1536            lib.push_str(&crate::codegen_go::typed_rs(m, api));
1537            lib.push_str(&crate::codegen_go::wire_rs(m, api));
1538            lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1539        }
1540        if matches!(
1541            m.language,
1542            crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1543        ) {
1544            lib.push_str(&crate::codegen_java::wire_rs(m, api));
1545            lib.push_str(
1546                &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1547            );
1548        }
1549        if matches!(
1550            m.language,
1551            crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1552        ) {
1553            lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1554        }
1555        let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1556        if matches!(
1557            m.language,
1558            crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1559        ) {
1560            files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1561        }
1562        files
1563    };
1564    match m.language {
1565        crate::lang::Lang::Go => {
1566            // The wrapper package takes its name and types from the original sources: without
1567            // them it would be written under a wrong name beside the old one.
1568            if crate::codegen_go::unit_sources(m).is_empty() {
1569                bail!(
1570                    "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1571                    m.unit,
1572                    m.root.display()
1573                );
1574            }
1575            files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1576            files.push((
1577                format!("go/{}.go", crate::codegen_go::package_name(m)),
1578                crate::codegen_go::wrapper(m, api),
1579            ));
1580        }
1581        crate::lang::Lang::Ruby => {
1582            files.push((
1583                crate::harness_ruby::wrapper_path(m),
1584                crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1585            ));
1586        }
1587        crate::lang::Lang::Php => {
1588            files.push((
1589                crate::codegen_php::wrapper_path(m),
1590                crate::codegen_php::wrapper(m),
1591            ));
1592        }
1593        crate::lang::Lang::Csharp => {
1594            files.push((
1595                crate::codegen_csharp::wrapper_path(m),
1596                crate::codegen_csharp::wrapper(m),
1597            ));
1598        }
1599        crate::lang::Lang::Powershell => {
1600            files.push((
1601                crate::codegen_powershell::wrapper_path(m),
1602                crate::codegen_powershell::wrapper(m),
1603            ));
1604        }
1605        crate::lang::Lang::Java | crate::lang::Lang::Kotlin => {
1606            files.extend(crate::codegen_java::wrappers(m, api));
1607            files.extend(
1608                crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1609            );
1610            files.push((
1611                format!(
1612                    "java/rustanything/{}.java",
1613                    crate::codegen_ffi::java_native_class(m)
1614                ),
1615                crate::codegen_java::native_class(m, api),
1616            ));
1617            files.push((
1618                "java/rustanything/RustAnythingJson.java".into(),
1619                crate::codegen_java::JSON_JAVA.into(),
1620            ));
1621            files.push((
1622                "java/rustanything/RustAnythingWire.java".into(),
1623                crate::codegen_java::WIRE_JAVA.into(),
1624            ));
1625            files.push((
1626                "java/rustanything/RustAnythingError.java".into(),
1627                crate::codegen_java::ERROR_JAVA.into(),
1628            ));
1629        }
1630        other => bail!("no wrapper generator for {}", other.name()),
1631    }
1632    Ok(files)
1633}
1634
1635fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1636    let port = codegen::port_rs(manifest);
1637    let api = codegen::parse_port(&port);
1638    let mut files = vec![
1639        (
1640            "Cargo.toml".to_string(),
1641            with_rayon(
1642                manifest,
1643                if manifest.language == crate::lang::Lang::Ruby {
1644                    crate::codegen_ruby::cargo_toml(manifest)
1645                } else {
1646                    crate::codegen_ffi::cargo_toml(manifest)
1647                },
1648            )?,
1649        ),
1650        ("src/port.rs".into(), port),
1651        (
1652            ".gitignore".into(),
1653            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\ncs/*.so\ncs/*.dylib\ncs/*.dll\nps/*.so\nps/*.dylib\nps/*.dll\n".into(),
1654        ),
1655        ("README.md".into(), readme(manifest)),
1656        (
1657            MANIFEST.into(),
1658            serde_json::to_string_pretty(manifest)? + "\n",
1659        ),
1660    ];
1661    files.extend(ffi_bindings(manifest, &api)?);
1662    write_files(crate_dir, &files)?;
1663    format_rust(crate_dir);
1664    format_wrapper(crate_dir);
1665    let mut notes = vec![format!(
1666        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1667        crate_dir.display()
1668    )];
1669    for j in kept {
1670        notes.push(format!(
1671            "`{}` stays in {}: {}.",
1672            j.name,
1673            manifest.language.name(),
1674            j.reason
1675        ));
1676    }
1677    Ok(Outcome {
1678        crate_dir: crate_dir.to_path_buf(),
1679        kind: Kind::Ffi,
1680        files: files.into_iter().map(|(p, _)| p).collect(),
1681        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1682        notes,
1683    })
1684}
1685
1686fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1687    let mut files = vec![
1688        (
1689            "Cargo.toml".to_string(),
1690            crate::codegen_c::cargo_toml(manifest),
1691        ),
1692        ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1693        (
1694            ".gitignore".into(),
1695            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\n".into(),
1696        ),
1697        ("README.md".into(), readme(manifest)),
1698        (
1699            MANIFEST.into(),
1700            serde_json::to_string_pretty(manifest)? + "\n",
1701        ),
1702    ];
1703    let port = crate::codegen_c::port_rs(manifest);
1704    files.extend(c_bindings(manifest, &port));
1705    write_files(crate_dir, &files)?;
1706    format_rust(crate_dir);
1707    let mut notes = vec![
1708        format!(
1709            "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1710            crate_dir.display()
1711        ),
1712        format!(
1713            "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1714            manifest.lib_name(),
1715            manifest.lib_name()
1716        ),
1717    ];
1718    for j in kept {
1719        notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1720    }
1721    Ok(Outcome {
1722        crate_dir: crate_dir.to_path_buf(),
1723        kind: Kind::CAbi,
1724        files: files.into_iter().map(|(p, _)| p).collect(),
1725        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1726        notes,
1727    })
1728}
1729
1730fn readme(m: &Manifest) -> String {
1731    use crate::lang::Lang;
1732    let functions: String = m
1733        .exports
1734        .iter()
1735        .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1736        .collect();
1737    let original = match m.language {
1738        Lang::Ts => "TS",
1739        other => other.name(),
1740    };
1741    let module = match m.kind {
1742        Kind::Napi => "napi-rs module",
1743        Kind::Wasm => "wasm-bindgen module",
1744        Kind::Pyo3 => "PyO3 module",
1745        Kind::CAbi => "C library",
1746        Kind::Ffi => "shared library",
1747    };
1748    let shadow = match m.language {
1749        Lang::Php | Lang::Csharp | Lang::Powershell => String::new(),
1750        _ => "rust-anything shadow .   # run both in the app, log mismatches\n".into(),
1751    };
1752    let switch = match m.language {
1753        Lang::Php => format!(
1754            "\nPHP has no shadow module: once `diff` passes, require `{}` in place of the original files.\n",
1755            crate::codegen_php::wrapper_path(m)
1756        ),
1757        Lang::Powershell => format!(
1758            "\nPowerShell has no shadow module: once `diff` passes, `rust-anything enable .` \
1759             dot-sources `{}` at the end of the original file, so every caller (the module's own \
1760             functions too) gets Rust. Most slow PowerShell is the start-up of a new `pwsh` per \
1761             command, which no port fixes: keep one shell open and call into it.\n",
1762            crate::codegen_powershell::wrapper_path(m)
1763        ),
1764        Lang::Csharp => format!(
1765            "\nC# has no shadow module: once `diff` passes, compile `{}` into the project and call \
1766             the `<namespace>.Rust` classes, with the built library next to the app.\n",
1767            crate::codegen_csharp::wrapper_path(m)
1768        ),
1769        _ => String::new(),
1770    };
1771    format!(
1772        "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1773         ## Loop\n\n```sh\nrust-anything record .   # record what the {original} code does\nrust-anything build .    # build the {module}\n\
1774         rust-anything diff .     # run the recorded cases against Rust\n{shadow}\
1775         rust-anything gate .     # fmt, clippy, tests, unsafe, API, diff\n```\n{switch}",
1776        name = m.crate_name,
1777        unit = m.unit,
1778        kind = match m.kind {
1779            Kind::Napi => "napi-rs",
1780            Kind::Wasm => "wasm-bindgen",
1781            Kind::Pyo3 => "PyO3",
1782            Kind::CAbi => "the C ABI",
1783            Kind::Ffi => "a JSON dispatcher",
1784        },
1785    )
1786}
1787
1788const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1789//!
1790//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1791//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1792
1793#![forbid(unsafe_code)]
1794
1795/// The UTF-16 code units of `s`, as JS sees the string.
1796pub fn units(s: &str) -> Vec<u16> {
1797    s.encode_utf16().collect()
1798}
1799
1800/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1801pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1802    let end = end.min(units.len());
1803    let start = start.min(end);
1804    String::from_utf16_lossy(&units[start..end])
1805}
1806
1807/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1808pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1809    let from = from.min(haystack.len());
1810    if needle.is_empty() {
1811        return Some(from);
1812    }
1813    haystack[from..]
1814        .windows(needle.len())
1815        .position(|w| w == needle)
1816        .map(|i| i + from)
1817}
1818
1819/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1820pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1821    if needle.is_empty() {
1822        return Some(haystack.len());
1823    }
1824    haystack.windows(needle.len()).rposition(|w| w == needle)
1825}
1826
1827/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1828pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1829    let mut seen = 0;
1830    for (byte, c) in s.char_indices() {
1831        if seen >= utf16_offset {
1832            return byte;
1833        }
1834        seen += c.len_utf16();
1835    }
1836    s.len()
1837}
1838
1839/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1840pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1841    s[..byte_offset.min(s.len())].encode_utf16().count()
1842}
1843
1844#[cfg(test)]
1845mod tests {
1846    use super::*;
1847
1848    #[test]
1849    fn matches_js_indexing() {
1850        let s = units("a👍b");
1851        assert_eq!(s.len(), 4);
1852        assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1853        assert_eq!(last_index_of(&s, &units("a")), Some(0));
1854        assert_eq!(slice(&s, 3, 4), "b");
1855        assert_eq!(byte_offset("a👍b", 3), 5);
1856        assert_eq!(utf16_offset("a👍b", 5), 3);
1857    }
1858}
1859"#;
1860
1861#[cfg(test)]
1862mod tests {
1863    use super::*;
1864
1865    #[test]
1866    fn keep_entries_are_trimmed() {
1867        let keep = |k: &[&str]| k.iter().map(|s| s.to_string()).collect::<Vec<_>>();
1868        assert_eq!(
1869            keep_reason(&keep(&["add"]), "add").as_deref(),
1870            Some("kept on request")
1871        );
1872        assert_eq!(
1873            keep_reason(&keep(&[" add "]), "add").as_deref(),
1874            Some("kept on request")
1875        );
1876        assert_eq!(
1877            keep_reason(&keep(&[" add : slow in Rust "]), "add").as_deref(),
1878            Some("slow in Rust")
1879        );
1880        assert_eq!(
1881            keep_reason(&keep(&["add:"]), "add").as_deref(),
1882            Some("kept on request")
1883        );
1884        assert_eq!(keep_reason(&keep(&["add"]), "sub"), None);
1885    }
1886
1887    #[test]
1888    fn unknown_keep_names_are_refused() {
1889        let keep = |k: &str| vec![k.to_string()];
1890        assert!(check_keep(&keep(" add : reason"), &["add", "Point"], "src/add.ts").is_ok());
1891        assert!(check_keep(&keep("Point"), &["add", "Point"], "src/add.ts").is_ok());
1892        let err = check_keep(&keep("nope"), &["sub", "add"], "src/add.ts")
1893            .unwrap_err()
1894            .to_string();
1895        assert_eq!(
1896            err,
1897            "--keep `nope` is not an export of `src/add.ts` (exports: add, sub)"
1898        );
1899    }
1900
1901    #[test]
1902    fn bridge_refuses_unknown_keep_name() {
1903        let dir = crate::app::temp_dir("bridge-keep").unwrap();
1904        std::fs::write(
1905            dir.join("package.json"),
1906            r#"{"name":"demo","version":"1.0.0"}"#,
1907        )
1908        .unwrap();
1909        std::fs::create_dir_all(dir.join("src")).unwrap();
1910        std::fs::write(
1911            dir.join("src/add.ts"),
1912            "export function add(a: number, b: number): number { return a + b; }\n",
1913        )
1914        .unwrap();
1915        let out = dir.join("rust/add-rs");
1916        let err = bridge(&Options {
1917            root: &dir,
1918            unit: "src/add.ts",
1919            kind: Some(Kind::Napi),
1920            out: Some(out.clone()),
1921            name: None,
1922            force: false,
1923            lang: None,
1924            keep: vec!["nope".into()],
1925            batch: vec![],
1926            allocator: Allocator::default(),
1927            as_json: vec![],
1928        })
1929        .unwrap_err();
1930        assert!(
1931            format!("{err:#}")
1932                .contains("--keep `nope` is not an export of `src/add.ts` (exports: add)"),
1933            "{err:#}"
1934        );
1935        assert!(!out.exists());
1936        std::fs::remove_dir_all(dir).unwrap();
1937    }
1938
1939    #[test]
1940    fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1941        let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1942        let _ = std::fs::remove_dir_all(&base);
1943        let crate_dir = base.join("repo/rust/x-rs");
1944        std::fs::create_dir_all(&crate_dir).unwrap();
1945        std::fs::write(
1946            crate_dir.join(MANIFEST),
1947            r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1948        )
1949        .unwrap();
1950        let m = Manifest::load(&crate_dir).unwrap();
1951        assert_eq!(m.root, base.join("repo").canonical().unwrap());
1952        assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1953        // Written back, the file keeps the relative root.
1954        let mut back = m.clone();
1955        if let Some(w) = back.root_written.clone() {
1956            back.root = w;
1957        }
1958        assert!(
1959            serde_json::to_string(&back)
1960                .unwrap()
1961                .contains(r#""root":"../..""#)
1962        );
1963        std::fs::remove_dir_all(&base).unwrap();
1964    }
1965
1966    #[test]
1967    fn maps_ts_types() {
1968        assert_eq!(RType::from_ts("string").rust(), "String");
1969        assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1970        assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1971        assert_eq!(
1972            RType::from_ts("string | undefined").rust(),
1973            "Option<String>"
1974        );
1975        assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1976        assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1977        assert_eq!(
1978            RType::from_ts("Map<string, number>").rust(),
1979            "serde_json::Value"
1980        );
1981        assert_eq!(
1982            RType::from_ts("string | number").rust(),
1983            "serde_json::Value"
1984        );
1985        assert_eq!(
1986            RType::from_ts("Record<string, string | number>").rust(),
1987            "serde_json::Value"
1988        );
1989        assert_eq!(
1990            RType::from_ts("(string | undefined)").rust(),
1991            "Option<String>"
1992        );
1993        assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
1994    }
1995
1996    #[test]
1997    fn keeps_unbridgeable_exports_in_js() {
1998        let source = "export interface LineIndex {\n  readonly lineCount: number\n  position(offset: number): number\n}\n\
1999            export interface Range { start: number, end: number }\n\
2000            export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
2001            export function globToRegExp(glob: string): RegExp { return /x/ }\n\
2002            export function createLineIndex(text: string): LineIndex { return null! }\n\
2003            export function* walk(tree: object) {}\n\
2004            export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
2005            export function contains(range: Range, offset: number): boolean { return true }\n";
2006        let types = local_types("a.ts", source);
2007        let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
2008            .iter()
2009            .map(|f| (f.name.clone(), js_only_reason(f, &types)))
2010            .collect();
2011        let js_only: Vec<&str> = reasons
2012            .iter()
2013            .filter(|(_, r)| r.is_some())
2014            .map(|(n, _)| n.as_str())
2015            .collect();
2016        assert_eq!(
2017            js_only,
2018            [
2019                "keyMatcher",
2020                "globToRegExp",
2021                "createLineIndex",
2022                "walk",
2023                "sortTree"
2024            ]
2025        );
2026    }
2027
2028    #[test]
2029    fn resolves_simple_aliases() {
2030        let types = local_types(
2031            "m.ts",
2032            "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
2033        );
2034        assert_eq!(
2035            resolve_aliases("readonly KeyString[]", &types),
2036            "readonly string[]"
2037        );
2038        assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
2039        assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
2040    }
2041
2042    #[test]
2043    fn substitutes_simple_constraints() {
2044        let found = exported_functions(
2045            "a.ts",
2046            "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
2047             export function pick<T>(x: T): T { return x }\n\
2048             export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
2049        );
2050        let mut fns = found;
2051        for f in &mut fns {
2052            substitute_constraints(f, &[]);
2053        }
2054        assert_eq!(fns[0].params[0].ts_type, "(string)");
2055        assert!(fns[0].type_params.is_empty());
2056        assert_eq!(fns[1].type_params, ["T"]);
2057        assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
2058        assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
2059    }
2060
2061    #[test]
2062    fn as_json_bridges_a_data_generic() {
2063        let mut fns = exported_functions(
2064            "a.ts",
2065            "export function paginate<T>(items: T[], page: number): { data: T[] } { return { data: items } }\n",
2066        );
2067        assert!(js_only_reason(&fns[0], &[]).is_some());
2068        substitute_json(&mut fns[0], &["T".to_string()]);
2069        assert!(fns[0].type_params.is_empty());
2070        assert_eq!(fns[0].params[0].ts_type, "unknown[]");
2071        assert_eq!(fns[0].returns, "{ data: unknown[] }");
2072        assert!(js_only_reason(&fns[0], &[]).is_none());
2073    }
2074
2075    #[test]
2076    fn readme_fits_the_language() {
2077        let manifest = |language: &str, kind: &str| -> Manifest {
2078            serde_json::from_str(&format!(
2079                r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "src/X.cs", "language": "{language}", "kind": "{kind}", "crate_name": "x-rs", "exports": []}}"#
2080            ))
2081            .unwrap()
2082        };
2083        let ts = readme(&manifest("ts", "napi"));
2084        assert!(ts.contains("what the TS code does") && ts.contains("build the napi-rs module"));
2085        assert!(ts.contains("rust-anything shadow ."));
2086        let c = readme(&manifest("c", "c-abi"));
2087        assert!(c.contains("what the C code does") && c.contains("build the C library"));
2088        let cs = readme(&manifest("csharp", "ffi"));
2089        assert!(cs.contains("what the C# code does") && cs.contains("build the shared library"));
2090        assert!(!cs.contains("rust-anything shadow") && cs.contains("C# has no shadow module"));
2091        let php = readme(&manifest("php", "ffi"));
2092        assert!(!php.contains("rust-anything shadow") && php.contains("PHP has no shadow module"));
2093    }
2094
2095    #[test]
2096    fn makes_rust_names() {
2097        assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
2098        assert_eq!(snake_case("type"), "r#type");
2099        assert_eq!(snake_case("toURL"), "to_url");
2100        assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
2101        assert_eq!(snake_case("box"), "r#box");
2102        assert_eq!(snake_case("yield"), "r#yield");
2103        assert_eq!(snake_case("try"), "r#try");
2104        assert_eq!(snake_case("self"), "self_");
2105        assert_eq!(snake_case("Super"), "super_");
2106    }
2107
2108    #[test]
2109    fn validates_crate_names() {
2110        for good in ["add-rs", "my_crate", "_helper", "Foo2", "a-1_b"] {
2111            assert_eq!(validate_crate_name(good).unwrap(), good, "{good}");
2112        }
2113        for bad in [
2114            "",
2115            " ",
2116            " add-rs ",
2117            "foo bar",
2118            "123-rs",
2119            "-foo",
2120            "../escape",
2121            "a/b",
2122            "a\\b",
2123            "a\"b",
2124            "café",
2125            "_",
2126            "fn",
2127            "type",
2128            "self",
2129            "Self",
2130            "gen",
2131            "con",
2132            "NUL",
2133        ] {
2134            assert!(
2135                validate_crate_name(bad).is_err(),
2136                "expected error for {bad:?}"
2137            );
2138        }
2139    }
2140
2141    #[test]
2142    fn default_crate_name_is_always_valid_for_cargo() {
2143        assert_eq!(default_crate_name("add"), "add-rs");
2144        assert_eq!(default_crate_name("my_util"), "my-util-rs");
2145        assert_eq!(default_crate_name("123"), "unit-123-rs");
2146        assert_eq!(default_crate_name("---"), "unit-rs");
2147        assert_eq!(default_crate_name(""), "unit-rs");
2148        for stem in ["add", "my_util", "123", "---", "", "00-index", "café"] {
2149            let name = default_crate_name(stem);
2150            assert!(
2151                validate_crate_name(&name).is_ok(),
2152                "{stem:?} -> {name:?} should be a valid crate name"
2153            );
2154        }
2155    }
2156
2157    #[test]
2158    fn bridge_refuses_invalid_name_before_writing_anything() {
2159        let out = std::env::temp_dir().join(format!("ra-bridge-bad-name-{}", std::process::id()));
2160        let _ = std::fs::remove_dir_all(&out);
2161        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
2162        for bad in ["../escape", "123bad", "", "fn"] {
2163            let err = bridge(&Options {
2164                root: &root,
2165                unit: "packages/a/src/util.ts",
2166                kind: Some(Kind::Napi),
2167                out: Some(out.clone()),
2168                name: Some(bad.to_string()),
2169                force: false,
2170                keep: Vec::new(),
2171                lang: None,
2172                batch: Vec::new(),
2173                as_json: Vec::new(),
2174                allocator: Allocator::default(),
2175            })
2176            .unwrap_err();
2177            assert!(
2178                format!("{err:#}").contains("invalid crate name"),
2179                "{bad:?}: {err:#}"
2180            );
2181            assert!(
2182                !out.exists(),
2183                "refused --name {bad:?} must not create folder"
2184            );
2185        }
2186    }
2187}