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    if let Some(k @ (Kind::Napi | Kind::Wasm)) = opts.kind
1197        && lang != crate::lang::Lang::Ts
1198    {
1199        bail!(
1200            "--kind {} is for TS/JS units; {wanted} is {} and is bridged with {}",
1201            if k == Kind::Napi { "napi" } else { "wasm" },
1202            lang.name(),
1203            Bridge::for_lang(lang).label()
1204        );
1205    }
1206    let kind = opts.kind.unwrap_or(match unit.bridge {
1207        Bridge::WasmBindgen => Kind::Wasm,
1208        Bridge::Pyo3 => Kind::Pyo3,
1209        Bridge::CAbi => Kind::CAbi,
1210        Bridge::Cgo
1211        | Bridge::Fiddle
1212        | Bridge::Jni
1213        | Bridge::PhpFfi
1214        | Bridge::DotnetFfi
1215        | Bridge::PwshFfi => Kind::Ffi,
1216        _ => Kind::Napi,
1217    });
1218    if !opts.batch.is_empty() {
1219        ensure_batch_support(lang, kind)?;
1220    }
1221
1222    let mut exports = Vec::new();
1223    let mut classes = Vec::new();
1224    let mut js_only = Vec::new();
1225    // Name and file of each overloaded function already kept, so its other overloads join it.
1226    let mut kept_overloads = std::collections::HashSet::new();
1227    if lang == crate::lang::Lang::C {
1228        crate::lang::c::use_typedefs(&root);
1229    }
1230    if lang == crate::lang::Lang::Csharp {
1231        crate::lang::csharp::use_shapes(&root);
1232    }
1233    for file in &unit.files {
1234        if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
1235            continue;
1236        }
1237        let text =
1238            std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
1239        if lang != crate::lang::Lang::Ts {
1240            let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
1241            for f in functions {
1242                // The overloads of one name (Java, Kotlin, C#) stay in the original together: one
1243                // name in one file, not two exports that would replace each other, whether they
1244                // stay for being overloaded or because `--keep` names them.
1245                let overload = f.blocker.as_deref() == Some(crate::lang::OVERLOADED);
1246                match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
1247                    Some(_)
1248                        if overload && !kept_overloads.insert((f.name.clone(), f.file.clone())) => {
1249                    }
1250                    Some(reason) => js_only.push(JsOnly {
1251                        name: f.name,
1252                        file: f.file,
1253                        line: f.line,
1254                        reason,
1255                    }),
1256                    None => exports.push(f),
1257                }
1258            }
1259            for class in foreign_classes {
1260                match keep_reason(&opts.keep, &class.name)
1261                    .or_else(|| class_reason(&class, &[], false))
1262                {
1263                    Some(reason) => js_only.push(JsOnly {
1264                        name: class.name,
1265                        file: class.file,
1266                        line: class.line,
1267                        reason: format!("class: {reason}"),
1268                    }),
1269                    None => classes.push(class),
1270                }
1271            }
1272            continue;
1273        }
1274        let types = types_in_scope(&root, file, &text);
1275        for mut class in exported_classes(file, &text) {
1276            let kept = keep_reason(&opts.keep, &class.name);
1277            match kept.or_else(|| class_reason(&class, &types, true)) {
1278                Some(reason) => js_only.push(JsOnly {
1279                    name: class.name,
1280                    file: class.file,
1281                    line: class.line,
1282                    reason: format!("class: {reason}"),
1283                }),
1284                None => {
1285                    for p in &mut class.constructor {
1286                        p.ts_type = resolve_aliases(&p.ts_type, &types);
1287                    }
1288                    for m in &mut class.methods {
1289                        for p in &mut m.params {
1290                            p.ts_type = resolve_aliases(&p.ts_type, &types);
1291                        }
1292                        m.returns = resolve_aliases(&m.returns, &types);
1293                    }
1294                    classes.push(class);
1295                }
1296            }
1297        }
1298        for mut f in ts_functions(&root, file, &text, &types) {
1299            substitute_json(&mut f, &opts.as_json);
1300            let kept = keep_reason(&opts.keep, &f.name);
1301            match kept.or_else(|| js_only_reason(&f, &types)) {
1302                Some(reason) => js_only.push(JsOnly {
1303                    name: f.name,
1304                    file: f.file,
1305                    line: f.line,
1306                    reason,
1307                }),
1308                None => exports.push(f),
1309            }
1310        }
1311    }
1312    let mut defined: Vec<(&str, String)> = exports
1313        .iter()
1314        .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1315        .chain(
1316            classes
1317                .iter()
1318                .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1319        )
1320        .chain(
1321            js_only
1322                .iter()
1323                .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1324        )
1325        .collect();
1326    defined.sort();
1327    check_keep(
1328        &opts.keep,
1329        &defined.iter().map(|(name, _)| *name).collect::<Vec<_>>(),
1330        &unit.id,
1331    )?;
1332    if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1333        bail!(
1334            "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1335             itself, so one would silently replace the other. Bridge the module you want on its \
1336             own (`rust-anything bridge <root> <that file>`), or rename one of them",
1337            pair[0].0,
1338            unit.id,
1339            pair[0].1,
1340            pair[1].1
1341        );
1342    }
1343    if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1344        bail!(
1345            "every export of `{}` must stay in {}: {}",
1346            unit.id,
1347            lang.name(),
1348            js_only
1349                .iter()
1350                .map(|j| format!("{} ({})", j.name, j.reason))
1351                .collect::<Vec<_>>()
1352                .join(", ")
1353        );
1354    }
1355    if exports.is_empty() && classes.is_empty() {
1356        bail!(
1357            "unit `{}` exports no functions; bridge a unit with an exported function API",
1358            unit.id
1359        );
1360    }
1361
1362    let stem = unit
1363        .id
1364        .trim_end_matches('/')
1365        .rsplit('/')
1366        .next()
1367        .unwrap_or("unit")
1368        .split('.')
1369        .next()
1370        .unwrap_or("unit");
1371    let crate_name = explicit_name
1372        .map(str::to_string)
1373        .unwrap_or_else(|| default_crate_name(stem));
1374    let crate_dir = opts
1375        .out
1376        .clone()
1377        .unwrap_or_else(|| root.join("rust").join(&crate_name));
1378    if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1379        bail!(
1380            "{dir} already exists and is not empty; rust-anything never overwrites a port in \
1381             progress. Run `rust-anything refresh {dir}` to regenerate the bindings, pass --out or \
1382             --name for a new crate, or remove the folder to start over",
1383            dir = crate_dir.display()
1384        );
1385    }
1386
1387    // UTF-16 helpers matter for JS strings only; Python indexes code points, like `chars()`.
1388    let utf16 =
1389        lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1390    let manifest = Manifest {
1391        schema: SCHEMA.into(),
1392        root: root.clone(),
1393        root_written: None,
1394        unit: unit.id.clone(),
1395        language: lang,
1396        kind,
1397        crate_name: crate_name.clone(),
1398        exports: exports.clone(),
1399        classes: classes.clone(),
1400        js_only: js_only.clone(),
1401        batches: parse_batches(&opts.batch)?,
1402        allocator: opts.allocator,
1403        float_tolerance: None,
1404        ignore_key_order: false,
1405    };
1406    if kind == Kind::CAbi {
1407        return bridge_c(&manifest, &crate_dir, &js_only);
1408    }
1409    if kind == Kind::Ffi {
1410        return bridge_ffi(&manifest, &crate_dir, &js_only);
1411    }
1412    let port = codegen::port_rs(&manifest);
1413    let fns = codegen::parse_port(&port);
1414    let modules = codegen::Modules {
1415        utf16,
1416        js: needs_js(&fns),
1417    };
1418    let mut files: Vec<(String, String)> = vec![
1419        (
1420            "Cargo.toml".into(),
1421            with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1422        ),
1423        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1424        ("src/port.rs".into(), port),
1425        loader_file(&manifest, &fns),
1426        (
1427            ".gitignore".into(),
1428            "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1429        ),
1430        ("README.md".into(), readme(&manifest)),
1431        (
1432            MANIFEST.into(),
1433            serde_json::to_string_pretty(&manifest)? + "\n",
1434        ),
1435    ];
1436    match kind {
1437        Kind::Napi => files.push((
1438            "build.rs".into(),
1439            "fn main() {\n    napi_build::setup();\n}\n".into(),
1440        )),
1441        Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1442        _ => {}
1443    }
1444    if utf16 {
1445        files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1446    }
1447    if modules.js {
1448        files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1449    }
1450    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1451        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1452    }
1453    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1454        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1455        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1456    }
1457    for (path, text) in &files {
1458        let target = crate_dir.join(path);
1459        if let Some(parent) = target.parent() {
1460            std::fs::create_dir_all(parent)?;
1461        }
1462        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1463    }
1464
1465    format_rust(&crate_dir);
1466    let mut notes = vec![format!(
1467        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1468        crate_dir.display()
1469    )];
1470    if utf16 {
1471        notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1472    }
1473    for j in &js_only {
1474        notes.push(format!(
1475            "`{}` stays in {}: {}. The shadow module re-exports the original.",
1476            j.name,
1477            lang.name(),
1478            j.reason
1479        ));
1480    }
1481    if exports.iter().any(codegen::is_async) {
1482        notes.push(
1483            "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1484        );
1485    }
1486    Ok(Outcome {
1487        crate_dir,
1488        kind,
1489        files: files.into_iter().map(|(p, _)| p).collect(),
1490        exports: exports
1491            .iter()
1492            .map(|f| f.name.clone())
1493            .chain(classes.iter().map(|c| format!("class {}", c.name)))
1494            .collect(),
1495        notes,
1496    })
1497}
1498
1499fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1500    for (path, text) in files {
1501        let target = crate_dir.join(path);
1502        if let Some(parent) = target.parent() {
1503            std::fs::create_dir_all(parent)?;
1504        }
1505        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1506    }
1507    Ok(())
1508}
1509
1510/// The generated C-side files: the `extern "C"` layer and its header. C signatures are fixed
1511/// by the original, so they come from the manifest, not from `port.rs`.
1512fn c_bindings(m: &Manifest, port: &str) -> Vec<(String, String)> {
1513    vec![
1514        ("src/lib.rs".into(), crate::codegen_c::lib_rs(m, port)),
1515        (
1516            format!("include/{}.h", m.lib_name()),
1517            crate::codegen_c::header(m),
1518        ),
1519    ]
1520}
1521
1522/// The generated layers of a JSON-dispatcher crate: `lib.rs` and the language-side wrapper.
1523fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1524    let mut files = if m.language == crate::lang::Lang::Ruby {
1525        vec![
1526            (
1527                "src/lib.rs".to_string(),
1528                with_allocator(
1529                    m,
1530                    crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1531                ),
1532            ),
1533            (
1534                "src/rbconv.rs".to_string(),
1535                crate::codegen_ruby::RBCONV_RS.to_string(),
1536            ),
1537            ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1538        ]
1539    } else {
1540        let mut lib = crate::codegen_ffi::lib_rs(m, api);
1541        if matches!(
1542            m.language,
1543            crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1544        ) {
1545            lib.push_str(&crate::codegen_java::typed_rs(m, api));
1546        }
1547        if m.language == crate::lang::Lang::Go {
1548            lib.push_str(&crate::codegen_go::typed_rs(m, api));
1549            lib.push_str(&crate::codegen_go::wire_rs(m, api));
1550            lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1551        }
1552        if matches!(
1553            m.language,
1554            crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1555        ) {
1556            lib.push_str(&crate::codegen_java::wire_rs(m, api));
1557            lib.push_str(
1558                &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1559            );
1560        }
1561        if matches!(
1562            m.language,
1563            crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1564        ) {
1565            lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1566        }
1567        let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1568        if matches!(
1569            m.language,
1570            crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1571        ) {
1572            files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1573        }
1574        files
1575    };
1576    match m.language {
1577        crate::lang::Lang::Go => {
1578            // The wrapper package takes its name and types from the original sources: without
1579            // them it would be written under a wrong name beside the old one.
1580            if crate::codegen_go::unit_sources(m).is_empty() {
1581                bail!(
1582                    "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1583                    m.unit,
1584                    m.root.display()
1585                );
1586            }
1587            files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1588            files.push((
1589                format!("go/{}.go", crate::codegen_go::package_name(m)),
1590                crate::codegen_go::wrapper(m, api),
1591            ));
1592        }
1593        crate::lang::Lang::Ruby => {
1594            files.push((
1595                crate::harness_ruby::wrapper_path(m),
1596                crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1597            ));
1598        }
1599        crate::lang::Lang::Php => {
1600            files.push((
1601                crate::codegen_php::wrapper_path(m),
1602                crate::codegen_php::wrapper(m),
1603            ));
1604        }
1605        crate::lang::Lang::Csharp => {
1606            files.push((
1607                crate::codegen_csharp::wrapper_path(m),
1608                crate::codegen_csharp::wrapper(m),
1609            ));
1610        }
1611        crate::lang::Lang::Powershell => {
1612            files.push((
1613                crate::codegen_powershell::wrapper_path(m),
1614                crate::codegen_powershell::wrapper(m),
1615            ));
1616        }
1617        crate::lang::Lang::Java | crate::lang::Lang::Kotlin => {
1618            files.extend(crate::codegen_java::wrappers(m, api));
1619            files.extend(
1620                crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1621            );
1622            files.push((
1623                format!(
1624                    "java/rustanything/{}.java",
1625                    crate::codegen_ffi::java_native_class(m)
1626                ),
1627                crate::codegen_java::native_class(m, api),
1628            ));
1629            files.push((
1630                "java/rustanything/RustAnythingJson.java".into(),
1631                crate::codegen_java::JSON_JAVA.into(),
1632            ));
1633            files.push((
1634                "java/rustanything/RustAnythingWire.java".into(),
1635                crate::codegen_java::WIRE_JAVA.into(),
1636            ));
1637            files.push((
1638                "java/rustanything/RustAnythingError.java".into(),
1639                crate::codegen_java::ERROR_JAVA.into(),
1640            ));
1641        }
1642        other => bail!("no wrapper generator for {}", other.name()),
1643    }
1644    Ok(files)
1645}
1646
1647fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1648    let port = codegen::port_rs(manifest);
1649    let api = codegen::parse_port(&port);
1650    let mut files = vec![
1651        (
1652            "Cargo.toml".to_string(),
1653            with_rayon(
1654                manifest,
1655                if manifest.language == crate::lang::Lang::Ruby {
1656                    crate::codegen_ruby::cargo_toml(manifest)
1657                } else {
1658                    crate::codegen_ffi::cargo_toml(manifest)
1659                },
1660            )?,
1661        ),
1662        ("src/port.rs".into(), port),
1663        (
1664            ".gitignore".into(),
1665            "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(),
1666        ),
1667        ("README.md".into(), readme(manifest)),
1668        (
1669            MANIFEST.into(),
1670            serde_json::to_string_pretty(manifest)? + "\n",
1671        ),
1672    ];
1673    files.extend(ffi_bindings(manifest, &api)?);
1674    write_files(crate_dir, &files)?;
1675    format_rust(crate_dir);
1676    format_wrapper(crate_dir);
1677    let mut notes = vec![format!(
1678        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1679        crate_dir.display()
1680    )];
1681    for j in kept {
1682        notes.push(format!(
1683            "`{}` stays in {}: {}.",
1684            j.name,
1685            manifest.language.name(),
1686            j.reason
1687        ));
1688    }
1689    Ok(Outcome {
1690        crate_dir: crate_dir.to_path_buf(),
1691        kind: Kind::Ffi,
1692        files: files.into_iter().map(|(p, _)| p).collect(),
1693        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1694        notes,
1695    })
1696}
1697
1698fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1699    let mut files = vec![
1700        (
1701            "Cargo.toml".to_string(),
1702            crate::codegen_c::cargo_toml(manifest),
1703        ),
1704        ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1705        (
1706            ".gitignore".into(),
1707            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\n".into(),
1708        ),
1709        ("README.md".into(), readme(manifest)),
1710        (
1711            MANIFEST.into(),
1712            serde_json::to_string_pretty(manifest)? + "\n",
1713        ),
1714    ];
1715    let port = crate::codegen_c::port_rs(manifest);
1716    files.extend(c_bindings(manifest, &port));
1717    write_files(crate_dir, &files)?;
1718    format_rust(crate_dir);
1719    let mut notes = vec![
1720        format!(
1721            "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1722            crate_dir.display()
1723        ),
1724        format!(
1725            "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1726            manifest.lib_name(),
1727            manifest.lib_name()
1728        ),
1729    ];
1730    for j in kept {
1731        notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1732    }
1733    Ok(Outcome {
1734        crate_dir: crate_dir.to_path_buf(),
1735        kind: Kind::CAbi,
1736        files: files.into_iter().map(|(p, _)| p).collect(),
1737        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1738        notes,
1739    })
1740}
1741
1742fn readme(m: &Manifest) -> String {
1743    use crate::lang::Lang;
1744    let functions: String = m
1745        .exports
1746        .iter()
1747        .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1748        .collect();
1749    let original = match m.language {
1750        Lang::Ts => "TS",
1751        other => other.name(),
1752    };
1753    let module = match m.kind {
1754        Kind::Napi => "napi-rs module",
1755        Kind::Wasm => "wasm-bindgen module",
1756        Kind::Pyo3 => "PyO3 module",
1757        Kind::CAbi => "C library",
1758        Kind::Ffi => "shared library",
1759    };
1760    let shadow = match m.language {
1761        Lang::Php | Lang::Csharp | Lang::Powershell => String::new(),
1762        _ => "rust-anything shadow .   # run both in the app, log mismatches\n".into(),
1763    };
1764    let switch = match m.language {
1765        Lang::Php => format!(
1766            "\nPHP has no shadow module: once `diff` passes, require `{}` in place of the original files.\n",
1767            crate::codegen_php::wrapper_path(m)
1768        ),
1769        Lang::Powershell => format!(
1770            "\nPowerShell has no shadow module: once `diff` passes, `rust-anything enable .` \
1771             dot-sources `{}` at the end of the original file, so every caller (the module's own \
1772             functions too) gets Rust. Most slow PowerShell is the start-up of a new `pwsh` per \
1773             command, which no port fixes: keep one shell open and call into it.\n",
1774            crate::codegen_powershell::wrapper_path(m)
1775        ),
1776        Lang::Csharp => format!(
1777            "\nC# has no shadow module: once `diff` passes, compile `{}` into the project and call \
1778             the `<namespace>.Rust` classes, with the built library next to the app.\n",
1779            crate::codegen_csharp::wrapper_path(m)
1780        ),
1781        _ => String::new(),
1782    };
1783    format!(
1784        "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1785         ## Loop\n\n```sh\nrust-anything record .   # record what the {original} code does\nrust-anything build .    # build the {module}\n\
1786         rust-anything diff .     # run the recorded cases against Rust\n{shadow}\
1787         rust-anything gate .     # fmt, clippy, tests, unsafe, API, diff\n```\n{switch}",
1788        name = m.crate_name,
1789        unit = m.unit,
1790        kind = match m.kind {
1791            Kind::Napi => "napi-rs",
1792            Kind::Wasm => "wasm-bindgen",
1793            Kind::Pyo3 => "PyO3",
1794            Kind::CAbi => "the C ABI",
1795            Kind::Ffi => "a JSON dispatcher",
1796        },
1797    )
1798}
1799
1800const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1801//!
1802//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1803//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1804
1805#![forbid(unsafe_code)]
1806
1807/// The UTF-16 code units of `s`, as JS sees the string.
1808pub fn units(s: &str) -> Vec<u16> {
1809    s.encode_utf16().collect()
1810}
1811
1812/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1813pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1814    let end = end.min(units.len());
1815    let start = start.min(end);
1816    String::from_utf16_lossy(&units[start..end])
1817}
1818
1819/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1820pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1821    let from = from.min(haystack.len());
1822    if needle.is_empty() {
1823        return Some(from);
1824    }
1825    haystack[from..]
1826        .windows(needle.len())
1827        .position(|w| w == needle)
1828        .map(|i| i + from)
1829}
1830
1831/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1832pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1833    if needle.is_empty() {
1834        return Some(haystack.len());
1835    }
1836    haystack.windows(needle.len()).rposition(|w| w == needle)
1837}
1838
1839/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1840pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1841    let mut seen = 0;
1842    for (byte, c) in s.char_indices() {
1843        if seen >= utf16_offset {
1844            return byte;
1845        }
1846        seen += c.len_utf16();
1847    }
1848    s.len()
1849}
1850
1851/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1852pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1853    s[..byte_offset.min(s.len())].encode_utf16().count()
1854}
1855
1856#[cfg(test)]
1857mod tests {
1858    use super::*;
1859
1860    #[test]
1861    fn matches_js_indexing() {
1862        let s = units("a👍b");
1863        assert_eq!(s.len(), 4);
1864        assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1865        assert_eq!(last_index_of(&s, &units("a")), Some(0));
1866        assert_eq!(slice(&s, 3, 4), "b");
1867        assert_eq!(byte_offset("a👍b", 3), 5);
1868        assert_eq!(utf16_offset("a👍b", 5), 3);
1869    }
1870}
1871"#;
1872
1873#[cfg(test)]
1874mod tests {
1875    use super::*;
1876
1877    #[test]
1878    fn keep_entries_are_trimmed() {
1879        let keep = |k: &[&str]| k.iter().map(|s| s.to_string()).collect::<Vec<_>>();
1880        assert_eq!(
1881            keep_reason(&keep(&["add"]), "add").as_deref(),
1882            Some("kept on request")
1883        );
1884        assert_eq!(
1885            keep_reason(&keep(&[" add "]), "add").as_deref(),
1886            Some("kept on request")
1887        );
1888        assert_eq!(
1889            keep_reason(&keep(&[" add : slow in Rust "]), "add").as_deref(),
1890            Some("slow in Rust")
1891        );
1892        assert_eq!(
1893            keep_reason(&keep(&["add:"]), "add").as_deref(),
1894            Some("kept on request")
1895        );
1896        assert_eq!(keep_reason(&keep(&["add"]), "sub"), None);
1897    }
1898
1899    #[test]
1900    fn unknown_keep_names_are_refused() {
1901        let keep = |k: &str| vec![k.to_string()];
1902        assert!(check_keep(&keep(" add : reason"), &["add", "Point"], "src/add.ts").is_ok());
1903        assert!(check_keep(&keep("Point"), &["add", "Point"], "src/add.ts").is_ok());
1904        let err = check_keep(&keep("nope"), &["sub", "add"], "src/add.ts")
1905            .unwrap_err()
1906            .to_string();
1907        assert_eq!(
1908            err,
1909            "--keep `nope` is not an export of `src/add.ts` (exports: add, sub)"
1910        );
1911    }
1912
1913    #[test]
1914    fn bridge_refuses_unknown_keep_name() {
1915        let dir = crate::app::temp_dir("bridge-keep").unwrap();
1916        std::fs::write(
1917            dir.join("package.json"),
1918            r#"{"name":"demo","version":"1.0.0"}"#,
1919        )
1920        .unwrap();
1921        std::fs::create_dir_all(dir.join("src")).unwrap();
1922        std::fs::write(
1923            dir.join("src/add.ts"),
1924            "export function add(a: number, b: number): number { return a + b; }\n",
1925        )
1926        .unwrap();
1927        let out = dir.join("rust/add-rs");
1928        let err = bridge(&Options {
1929            root: &dir,
1930            unit: "src/add.ts",
1931            kind: Some(Kind::Napi),
1932            out: Some(out.clone()),
1933            name: None,
1934            force: false,
1935            lang: None,
1936            keep: vec!["nope".into()],
1937            batch: vec![],
1938            allocator: Allocator::default(),
1939            as_json: vec![],
1940        })
1941        .unwrap_err();
1942        assert!(
1943            format!("{err:#}")
1944                .contains("--keep `nope` is not an export of `src/add.ts` (exports: add)"),
1945            "{err:#}"
1946        );
1947        assert!(!out.exists());
1948        std::fs::remove_dir_all(dir).unwrap();
1949    }
1950
1951    #[test]
1952    fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1953        let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1954        let _ = std::fs::remove_dir_all(&base);
1955        let crate_dir = base.join("repo/rust/x-rs");
1956        std::fs::create_dir_all(&crate_dir).unwrap();
1957        std::fs::write(
1958            crate_dir.join(MANIFEST),
1959            r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1960        )
1961        .unwrap();
1962        let m = Manifest::load(&crate_dir).unwrap();
1963        assert_eq!(m.root, base.join("repo").canonical().unwrap());
1964        assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1965        // Written back, the file keeps the relative root.
1966        let mut back = m.clone();
1967        if let Some(w) = back.root_written.clone() {
1968            back.root = w;
1969        }
1970        assert!(
1971            serde_json::to_string(&back)
1972                .unwrap()
1973                .contains(r#""root":"../..""#)
1974        );
1975        std::fs::remove_dir_all(&base).unwrap();
1976    }
1977
1978    #[test]
1979    fn maps_ts_types() {
1980        assert_eq!(RType::from_ts("string").rust(), "String");
1981        assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1982        assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1983        assert_eq!(
1984            RType::from_ts("string | undefined").rust(),
1985            "Option<String>"
1986        );
1987        assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1988        assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1989        assert_eq!(
1990            RType::from_ts("Map<string, number>").rust(),
1991            "serde_json::Value"
1992        );
1993        assert_eq!(
1994            RType::from_ts("string | number").rust(),
1995            "serde_json::Value"
1996        );
1997        assert_eq!(
1998            RType::from_ts("Record<string, string | number>").rust(),
1999            "serde_json::Value"
2000        );
2001        assert_eq!(
2002            RType::from_ts("(string | undefined)").rust(),
2003            "Option<String>"
2004        );
2005        assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
2006    }
2007
2008    #[test]
2009    fn keeps_unbridgeable_exports_in_js() {
2010        let source = "export interface LineIndex {\n  readonly lineCount: number\n  position(offset: number): number\n}\n\
2011            export interface Range { start: number, end: number }\n\
2012            export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
2013            export function globToRegExp(glob: string): RegExp { return /x/ }\n\
2014            export function createLineIndex(text: string): LineIndex { return null! }\n\
2015            export function* walk(tree: object) {}\n\
2016            export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
2017            export function contains(range: Range, offset: number): boolean { return true }\n";
2018        let types = local_types("a.ts", source);
2019        let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
2020            .iter()
2021            .map(|f| (f.name.clone(), js_only_reason(f, &types)))
2022            .collect();
2023        let js_only: Vec<&str> = reasons
2024            .iter()
2025            .filter(|(_, r)| r.is_some())
2026            .map(|(n, _)| n.as_str())
2027            .collect();
2028        assert_eq!(
2029            js_only,
2030            [
2031                "keyMatcher",
2032                "globToRegExp",
2033                "createLineIndex",
2034                "walk",
2035                "sortTree"
2036            ]
2037        );
2038    }
2039
2040    #[test]
2041    fn resolves_simple_aliases() {
2042        let types = local_types(
2043            "m.ts",
2044            "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
2045        );
2046        assert_eq!(
2047            resolve_aliases("readonly KeyString[]", &types),
2048            "readonly string[]"
2049        );
2050        assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
2051        assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
2052    }
2053
2054    #[test]
2055    fn substitutes_simple_constraints() {
2056        let found = exported_functions(
2057            "a.ts",
2058            "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
2059             export function pick<T>(x: T): T { return x }\n\
2060             export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
2061        );
2062        let mut fns = found;
2063        for f in &mut fns {
2064            substitute_constraints(f, &[]);
2065        }
2066        assert_eq!(fns[0].params[0].ts_type, "(string)");
2067        assert!(fns[0].type_params.is_empty());
2068        assert_eq!(fns[1].type_params, ["T"]);
2069        assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
2070        assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
2071    }
2072
2073    #[test]
2074    fn as_json_bridges_a_data_generic() {
2075        let mut fns = exported_functions(
2076            "a.ts",
2077            "export function paginate<T>(items: T[], page: number): { data: T[] } { return { data: items } }\n",
2078        );
2079        assert!(js_only_reason(&fns[0], &[]).is_some());
2080        substitute_json(&mut fns[0], &["T".to_string()]);
2081        assert!(fns[0].type_params.is_empty());
2082        assert_eq!(fns[0].params[0].ts_type, "unknown[]");
2083        assert_eq!(fns[0].returns, "{ data: unknown[] }");
2084        assert!(js_only_reason(&fns[0], &[]).is_none());
2085    }
2086
2087    #[test]
2088    fn readme_fits_the_language() {
2089        let manifest = |language: &str, kind: &str| -> Manifest {
2090            serde_json::from_str(&format!(
2091                r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "src/X.cs", "language": "{language}", "kind": "{kind}", "crate_name": "x-rs", "exports": []}}"#
2092            ))
2093            .unwrap()
2094        };
2095        let ts = readme(&manifest("ts", "napi"));
2096        assert!(ts.contains("what the TS code does") && ts.contains("build the napi-rs module"));
2097        assert!(ts.contains("rust-anything shadow ."));
2098        let c = readme(&manifest("c", "c-abi"));
2099        assert!(c.contains("what the C code does") && c.contains("build the C library"));
2100        let cs = readme(&manifest("csharp", "ffi"));
2101        assert!(cs.contains("what the C# code does") && cs.contains("build the shared library"));
2102        assert!(!cs.contains("rust-anything shadow") && cs.contains("C# has no shadow module"));
2103        let php = readme(&manifest("php", "ffi"));
2104        assert!(!php.contains("rust-anything shadow") && php.contains("PHP has no shadow module"));
2105    }
2106
2107    #[test]
2108    fn makes_rust_names() {
2109        assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
2110        assert_eq!(snake_case("type"), "r#type");
2111        assert_eq!(snake_case("toURL"), "to_url");
2112        assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
2113        assert_eq!(snake_case("box"), "r#box");
2114        assert_eq!(snake_case("yield"), "r#yield");
2115        assert_eq!(snake_case("try"), "r#try");
2116        assert_eq!(snake_case("self"), "self_");
2117        assert_eq!(snake_case("Super"), "super_");
2118    }
2119
2120    #[test]
2121    fn validates_crate_names() {
2122        for good in ["add-rs", "my_crate", "_helper", "Foo2", "a-1_b"] {
2123            assert_eq!(validate_crate_name(good).unwrap(), good, "{good}");
2124        }
2125        for bad in [
2126            "",
2127            " ",
2128            " add-rs ",
2129            "foo bar",
2130            "123-rs",
2131            "-foo",
2132            "../escape",
2133            "a/b",
2134            "a\\b",
2135            "a\"b",
2136            "café",
2137            "_",
2138            "fn",
2139            "type",
2140            "self",
2141            "Self",
2142            "gen",
2143            "con",
2144            "NUL",
2145        ] {
2146            assert!(
2147                validate_crate_name(bad).is_err(),
2148                "expected error for {bad:?}"
2149            );
2150        }
2151    }
2152
2153    #[test]
2154    fn default_crate_name_is_always_valid_for_cargo() {
2155        assert_eq!(default_crate_name("add"), "add-rs");
2156        assert_eq!(default_crate_name("my_util"), "my-util-rs");
2157        assert_eq!(default_crate_name("123"), "unit-123-rs");
2158        assert_eq!(default_crate_name("---"), "unit-rs");
2159        assert_eq!(default_crate_name(""), "unit-rs");
2160        for stem in ["add", "my_util", "123", "---", "", "00-index", "café"] {
2161            let name = default_crate_name(stem);
2162            assert!(
2163                validate_crate_name(&name).is_ok(),
2164                "{stem:?} -> {name:?} should be a valid crate name"
2165            );
2166        }
2167    }
2168
2169    #[test]
2170    fn bridge_refuses_invalid_name_before_writing_anything() {
2171        let out = std::env::temp_dir().join(format!("ra-bridge-bad-name-{}", std::process::id()));
2172        let _ = std::fs::remove_dir_all(&out);
2173        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
2174        for bad in ["../escape", "123bad", "", "fn"] {
2175            let err = bridge(&Options {
2176                root: &root,
2177                unit: "packages/a/src/util.ts",
2178                kind: Some(Kind::Napi),
2179                out: Some(out.clone()),
2180                name: Some(bad.to_string()),
2181                force: false,
2182                keep: Vec::new(),
2183                lang: None,
2184                batch: Vec::new(),
2185                as_json: Vec::new(),
2186                allocator: Allocator::default(),
2187            })
2188            .unwrap_err();
2189            assert!(
2190                format!("{err:#}").contains("invalid crate name"),
2191                "{bad:?}: {err:#}"
2192            );
2193            assert!(
2194                !out.exists(),
2195                "refused --name {bad:?} must not create folder"
2196            );
2197        }
2198    }
2199}