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 reason given with `--keep name` or `--keep "name: reason"`, if `name` is kept.
714fn keep_reason(keep: &[String], name: &str) -> Option<String> {
715    keep.iter().find_map(|k| {
716        let (kept, reason) = k
717            .split_once(':')
718            .map_or((k.as_str(), ""), |(n, r)| (n.trim(), r.trim()));
719        (kept == name).then(|| {
720            if reason.is_empty() {
721                "kept on request".to_string()
722            } else {
723                reason.to_string()
724            }
725        })
726    })
727}
728
729/// Formats the generated Rust, best effort: the gate checks formatting.
730fn format_rust(crate_dir: &Path) {
731    let files: Vec<PathBuf> = std::fs::read_dir(crate_dir.join("src"))
732        .into_iter()
733        .flatten()
734        .flatten()
735        .map(|e| e.path())
736        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
737        .collect();
738    let _ = std::process::Command::new("rustfmt")
739        .args(["--edition", "2024"])
740        .args(&files)
741        .output();
742}
743
744/// Formats a generated Go wrapper with `gofmt`, best effort.
745fn format_wrapper(crate_dir: &Path) {
746    if crate_dir.join("go").is_dir() {
747        let _ = std::process::Command::new("gofmt")
748            .arg("-w")
749            .arg(crate_dir.join("go"))
750            .output();
751    }
752}
753
754/// `lib.rs` of a JS crate: the bindings, and the binary wire when functions use it.
755fn js_lib_rs(m: &Manifest, api: &codegen::PortApi, modules: &codegen::Modules) -> Result<String> {
756    let mut lib = with_allocator(m, codegen::lib_rs(m, api, modules));
757    if m.kind != Kind::Pyo3 && !m.batches.is_empty() {
758        lib.push_str(&crate::codegen_batch::js_rs(m, api).map_err(anyhow::Error::msg)?);
759    }
760    if !crate::codegen_tswire::uses_wire(m, api) {
761        return Ok(lib);
762    }
763    Ok(lib.replacen(
764        "pub mod port;",
765        "pub mod port;\npub mod wire;\n\n#[allow(unused_imports)]\nuse serde_json::Value;",
766        1,
767    ) + &crate::codegen_tswire::napi_rs(m, api))
768}
769
770fn parse_batches(specs: &[String]) -> Result<Vec<crate::codegen_batch::Batch>> {
771    specs
772        .iter()
773        .map(|s| {
774            crate::codegen_batch::Batch::parse(s)
775                .with_context(|| format!("`--batch {s}`: write it as function:param"))
776        })
777        .collect()
778}
779
780/// Fails when `lang` or `kind` has no batch generator yet, so `bridge` and `refresh --batch`
781/// refuse `--batch` in one place with the same message.
782fn ensure_batch_support(lang: crate::lang::Lang, kind: Kind) -> Result<()> {
783    use crate::lang::Lang;
784    let unsupported = match lang {
785        Lang::C | Lang::Php | Lang::Csharp | Lang::Powershell => Some(lang.name()),
786        _ if kind == Kind::CAbi => Some(Lang::C.name()),
787        _ => None,
788    };
789    if let Some(name) = unsupported {
790        bail!("`--batch` is not available for {name} units yet");
791    }
792    Ok(())
793}
794
795/// Adds batch classes to a bridged crate, then regenerates its bindings.
796pub fn add_batches(crate_dir: &Path, specs: &[String]) -> Result<Refreshed> {
797    let path = crate_dir.join(MANIFEST);
798    let before = std::fs::read_to_string(&path).with_context(|| format!("{}", path.display()))?;
799    let mut manifest = Manifest::load(crate_dir)?;
800    if !specs.is_empty() {
801        ensure_batch_support(manifest.language, manifest.kind)?;
802    }
803    for b in parse_batches(specs)? {
804        if !manifest.batches.contains(&b) {
805            manifest.batches.push(b);
806        }
807    }
808    if let Some(written) = manifest.root_written.clone() {
809        manifest.root = written;
810    }
811    std::fs::write(&path, serde_json::to_string_pretty(&manifest)? + "\n")?;
812    // A batch the port cannot serve leaves the crate as it was.
813    refresh(crate_dir).inspect_err(|_| {
814        let _ = std::fs::write(&path, &before);
815    })
816}
817
818/// Cargo.toml with the dependencies and library types today's bindings need, for crates
819/// bridged by an older rust-anything; versions and features already set are kept.
820fn with_template_deps(cargo: &str, template: &str) -> Result<String> {
821    let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
822    let template: toml_edit::DocumentMut = template.parse().context("Cargo.toml template")?;
823    if let Some(want) = template.get("dependencies").and_then(|d| d.as_table()) {
824        let deps = doc["dependencies"].or_insert(toml_edit::table());
825        for (name, item) in want {
826            if deps.get(name).is_none() {
827                deps[name] = item.clone();
828            }
829        }
830    }
831    if let Some(want) = template.get("features").and_then(|d| d.as_table()) {
832        let features = doc["features"].or_insert(toml_edit::table());
833        for (name, item) in want {
834            if features.get(name).is_none() {
835                features[name] = item.clone();
836            }
837        }
838    }
839    if let Some(kinds) = template.get("lib").and_then(|l| l.get("crate-type")) {
840        doc["lib"]["crate-type"] = kinds.clone();
841    }
842    Ok(doc.to_string())
843}
844
845/// The global allocator of a crate, if it sets one: crates with batches allocate from all cores
846/// at once (the system allocator serializes them: 1.6x on 4 cores instead of 3.2x). mimalloc
847/// leaves wasm alone, which runs on one thread; rusty_alloc also replaces Rust's wasm allocator.
848/// Only Rust code uses this heap; every buffer that crosses the bridge is copied or freed by Rust.
849fn global_allocator(m: &Manifest) -> Option<Allocator> {
850    if m.batches.is_empty() {
851        return None;
852    }
853    match m.allocator {
854        Allocator::Mimalloc if m.kind == Kind::Wasm => None,
855        a => Some(a),
856    }
857}
858
859/// `lib.rs` with the [`global_allocator`].
860fn with_allocator(m: &Manifest, lib: String) -> String {
861    let line = match global_allocator(m) {
862        None => return lib,
863        Some(Allocator::Mimalloc) => {
864            "/// Batches allocate on all cores at once; mimalloc keeps that from serializing.\n\
865             #[global_allocator]\nstatic GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;\n"
866        }
867        Some(Allocator::RustyAlloc) => {
868            "/// Batches allocate on all cores at once; rusty_alloc keeps that from serializing.\n\
869             #[global_allocator]\n\
870             static GLOBAL: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;\n"
871        }
872    };
873    lib.replacen("pub mod port;", &format!("pub mod port;\n\n{line}"), 1)
874}
875
876/// Cargo.toml with rayon (and the global allocator) when batches run on all cores.
877fn with_rayon(m: &Manifest, cargo: String) -> Result<String> {
878    let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
879    let deps = doc["dependencies"].or_insert(toml_edit::table());
880    // Batch methods take their other parameters as napi values; structured ones need serde.
881    if m.kind == Kind::Napi
882        && !m.batches.is_empty()
883        && let Some(napi) = deps.get_mut("napi")
884    {
885        let mut table = toml_edit::InlineTable::new();
886        match napi {
887            toml_edit::Item::Value(toml_edit::Value::String(v)) => {
888                table.insert("version", v.value().clone().into());
889            }
890            toml_edit::Item::Value(toml_edit::Value::InlineTable(t)) => table = t.clone(),
891            _ => {}
892        }
893        let mut features = table
894            .get("features")
895            .and_then(|f| f.as_array())
896            .cloned()
897            .unwrap_or_default();
898        if !features.iter().any(|f| f.as_str() == Some("serde-json")) {
899            features.push("serde-json");
900        }
901        table.insert("features", toml_edit::Value::Array(features));
902        *napi = toml_edit::value(table);
903    }
904    if !crate::codegen_batch::needs_rayon(m) {
905        return Ok(doc.to_string());
906    }
907    if deps.get("rayon").is_none() {
908        deps["rayon"] = toml_edit::value("1");
909    }
910    let allocator = match global_allocator(m) {
911        Some(Allocator::Mimalloc) => Some(("mimalloc", "0.1")),
912        Some(Allocator::RustyAlloc) => Some(("rusty_alloc-api", "2.6")),
913        None => None,
914    };
915    if let Some((name, version)) = allocator
916        && deps.get(name).is_none()
917    {
918        deps[name] = toml_edit::value(version);
919    }
920    Ok(doc.to_string())
921}
922
923/// The language-side loader: `index.cjs` for JS, the wrapper package for Python.
924fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
925    match m.kind {
926        Kind::Pyo3 => (
927            format!("python/{}/__init__.py", m.lib_name()),
928            crate::codegen_py::package_init(m, api),
929        ),
930        _ => (
931            "index.cjs".into(),
932            codegen::index_cjs(m, api)
933                + &crate::codegen_tswire::index_cjs(m, api)
934                + &crate::codegen_batch::index_cjs(m, api)
935                + &codegen::guard_cjs(api, &crate::codegen_tswire::wired(m, api)),
936        ),
937    }
938}
939
940/// A port function whose doc line does not name an export (`/// Port of \`Integer.toString\``)
941/// takes the name of the export it was generated for, matched by its Rust name.
942pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
943    for f in &mut api.functions {
944        if m.exports.iter().any(|e| e.name == f.js_name) {
945            continue;
946        }
947        let rust = f.rust_name.trim_start_matches("r#");
948        if let Some(e) = m
949            .exports
950            .iter()
951            .find(|e| snake_case(&e.name).trim_start_matches("r#") == rust)
952        {
953            f.js_name = e.name.clone();
954        }
955    }
956}
957
958/// What `refresh` rewrote.
959#[derive(Debug, Serialize)]
960pub struct Refreshed {
961    pub functions: Vec<String>,
962    pub files: Vec<String>,
963}
964
965/// Regenerates the binding layer (`lib.rs`, `index.cjs`, `js.rs`) from the signatures in
966/// `port.rs`, and adds the dependencies they need to Cargo.toml. Never touches `port.rs`.
967pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
968    let manifest = Manifest::load(crate_dir)?;
969    if manifest.kind == Kind::CAbi {
970        let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
971            .context("reading src/port.rs")?;
972        let mut files = c_bindings(&manifest, &port);
973        let cargo =
974            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
975        files.push((
976            "Cargo.toml".into(),
977            with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
978        ));
979        write_files(crate_dir, &files)?;
980        format_rust(crate_dir);
981        return Ok(Refreshed {
982            functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
983            files: files.into_iter().map(|(p, _)| p).collect(),
984        });
985    }
986    if manifest.kind == Kind::Ffi {
987        let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
988            .context("reading src/port.rs")?;
989        let mut api = codegen::parse_port(&port);
990        match_export_names(&manifest, &mut api);
991        let mut files = ffi_bindings(&manifest, &api)?;
992        let cargo =
993            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
994        let template = if manifest.language == crate::lang::Lang::Ruby {
995            crate::codegen_ruby::cargo_toml(&manifest)
996        } else {
997            crate::codegen_ffi::cargo_toml(&manifest)
998        };
999        let cargo = with_template_deps(&cargo, &template)?;
1000        files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
1001        write_files(crate_dir, &files)?;
1002        format_rust(crate_dir);
1003        format_wrapper(crate_dir);
1004        return Ok(Refreshed {
1005            functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
1006            files: files.into_iter().map(|(p, _)| p).collect(),
1007        });
1008    }
1009    let port =
1010        std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
1011    let mut fns = codegen::parse_port(&port);
1012    match_export_names(&manifest, &mut fns);
1013    if fns.functions.is_empty() && fns.classes.is_empty() {
1014        bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
1015    }
1016    let modules = codegen::Modules {
1017        utf16: crate_dir.join("src/utf16.rs").exists(),
1018        js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
1019    };
1020    let mut files: Vec<(String, String)> = vec![
1021        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1022        loader_file(&manifest, &fns),
1023    ];
1024    if modules.js {
1025        files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
1026    }
1027    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1028        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1029    }
1030    let extension = manifest.kind == Kind::Pyo3
1031        || (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
1032    if extension && !crate_dir.join("build.rs").exists() {
1033        files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
1034    }
1035    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1036        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1037        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1038    }
1039    let cargo_path = crate_dir.join("Cargo.toml");
1040    let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
1041    let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns).map_err(anyhow::Error::msg)?;
1042    let cargo = with_rayon(&manifest, cargo)?;
1043    files.push(("Cargo.toml".into(), cargo));
1044    for (path, text) in &files {
1045        let target = crate_dir.join(path);
1046        if let Some(parent) = target.parent() {
1047            std::fs::create_dir_all(parent)?;
1048        }
1049        std::fs::write(&target, text).with_context(|| format!("writing {path}"))?;
1050    }
1051    format_rust(crate_dir);
1052    Ok(Refreshed {
1053        functions: fns
1054            .functions
1055            .iter()
1056            .map(|f| f.js_name.clone())
1057            .chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
1058            .collect(),
1059        files: files.into_iter().map(|(p, _)| p).collect(),
1060    })
1061}
1062
1063/// `build.rs` for Python and Ruby extensions: on macOS the library (and its test binary) links
1064/// against symbols the interpreter provides only at load time.
1065pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
1066    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
1067        println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
1068    }
1069}
1070"#;
1071
1072pub fn bridge(opts: &Options) -> Result<Outcome> {
1073    let root = opts
1074        .root
1075        .canonical()
1076        .with_context(|| format!("resolving {}", opts.root.display()))?;
1077    let lang = opts
1078        .lang
1079        .unwrap_or_else(|| crate::lang::Lang::detect(&root));
1080    let report = analyze::analyze_lang(&root, lang)?;
1081    let wanted = opts.unit.trim_start_matches("./");
1082    let whole = report
1083        .units
1084        .iter()
1085        .find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'));
1086    let single = || {
1087        report
1088            .units
1089            .iter()
1090            .find(|u| u.files.iter().any(|f| f == wanted))
1091            .map(|u| {
1092                let mut one = u.clone();
1093                one.id = wanted.to_string();
1094                one.files = vec![wanted.to_string()];
1095                one
1096            })
1097    };
1098    let unit = match whole.cloned().or_else(single) {
1099        Some(unit) => unit,
1100        None => bail!(
1101            "no unit or source file `{wanted}`; `rust-anything analyze` lists unit ids, and any \
1102             source file inside a unit can be bridged on its own"
1103        ),
1104    };
1105    let unit = &unit;
1106    if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
1107        bail!(
1108            "unit `{}` is {:?}: {}. Pass --force to bridge it anyway.",
1109            unit.id,
1110            unit.status,
1111            unit.notes.first().map_or("", String::as_str)
1112        );
1113    }
1114    let kind = opts.kind.unwrap_or(match unit.bridge {
1115        Bridge::WasmBindgen => Kind::Wasm,
1116        Bridge::Pyo3 => Kind::Pyo3,
1117        Bridge::CAbi => Kind::CAbi,
1118        Bridge::Cgo
1119        | Bridge::Fiddle
1120        | Bridge::Jni
1121        | Bridge::PhpFfi
1122        | Bridge::DotnetFfi
1123        | Bridge::PwshFfi => Kind::Ffi,
1124        _ => Kind::Napi,
1125    });
1126    if !opts.batch.is_empty() {
1127        ensure_batch_support(lang, kind)?;
1128    }
1129
1130    let mut exports = Vec::new();
1131    let mut classes = Vec::new();
1132    let mut js_only = Vec::new();
1133    // Name and file of each overloaded function already kept, so its other overloads join it.
1134    let mut kept_overloads = std::collections::HashSet::new();
1135    if lang == crate::lang::Lang::C {
1136        crate::lang::c::use_typedefs(&root);
1137    }
1138    if lang == crate::lang::Lang::Csharp {
1139        crate::lang::csharp::use_shapes(&root);
1140    }
1141    for file in &unit.files {
1142        if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
1143            continue;
1144        }
1145        let text =
1146            std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
1147        if lang != crate::lang::Lang::Ts {
1148            let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
1149            for f in functions {
1150                // The overloads of one name (Java, Kotlin, C#) stay in the original together: one
1151                // name in one file, not two exports that would replace each other, whether they
1152                // stay for being overloaded or because `--keep` names them.
1153                let overload = f.blocker.as_deref() == Some(crate::lang::OVERLOADED);
1154                match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
1155                    Some(_)
1156                        if overload && !kept_overloads.insert((f.name.clone(), f.file.clone())) => {
1157                    }
1158                    Some(reason) => js_only.push(JsOnly {
1159                        name: f.name,
1160                        file: f.file,
1161                        line: f.line,
1162                        reason,
1163                    }),
1164                    None => exports.push(f),
1165                }
1166            }
1167            for class in foreign_classes {
1168                match keep_reason(&opts.keep, &class.name)
1169                    .or_else(|| class_reason(&class, &[], false))
1170                {
1171                    Some(reason) => js_only.push(JsOnly {
1172                        name: class.name,
1173                        file: class.file,
1174                        line: class.line,
1175                        reason: format!("class: {reason}"),
1176                    }),
1177                    None => classes.push(class),
1178                }
1179            }
1180            continue;
1181        }
1182        let types = types_in_scope(&root, file, &text);
1183        for mut class in exported_classes(file, &text) {
1184            let kept = keep_reason(&opts.keep, &class.name);
1185            match kept.or_else(|| class_reason(&class, &types, true)) {
1186                Some(reason) => js_only.push(JsOnly {
1187                    name: class.name,
1188                    file: class.file,
1189                    line: class.line,
1190                    reason: format!("class: {reason}"),
1191                }),
1192                None => {
1193                    for p in &mut class.constructor {
1194                        p.ts_type = resolve_aliases(&p.ts_type, &types);
1195                    }
1196                    for m in &mut class.methods {
1197                        for p in &mut m.params {
1198                            p.ts_type = resolve_aliases(&p.ts_type, &types);
1199                        }
1200                        m.returns = resolve_aliases(&m.returns, &types);
1201                    }
1202                    classes.push(class);
1203                }
1204            }
1205        }
1206        for mut f in ts_functions(&root, file, &text, &types) {
1207            substitute_json(&mut f, &opts.as_json);
1208            let kept = keep_reason(&opts.keep, &f.name);
1209            match kept.or_else(|| js_only_reason(&f, &types)) {
1210                Some(reason) => js_only.push(JsOnly {
1211                    name: f.name,
1212                    file: f.file,
1213                    line: f.line,
1214                    reason,
1215                }),
1216                None => exports.push(f),
1217            }
1218        }
1219    }
1220    let mut defined: Vec<(&str, String)> = exports
1221        .iter()
1222        .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1223        .chain(
1224            classes
1225                .iter()
1226                .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1227        )
1228        .chain(
1229            js_only
1230                .iter()
1231                .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1232        )
1233        .collect();
1234    defined.sort();
1235    if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1236        bail!(
1237            "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1238             itself, so one would silently replace the other. Bridge the module you want on its \
1239             own (`rust-anything bridge <root> <that file>`), or rename one of them",
1240            pair[0].0,
1241            unit.id,
1242            pair[0].1,
1243            pair[1].1
1244        );
1245    }
1246    if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1247        bail!(
1248            "every export of `{}` must stay in {}: {}",
1249            unit.id,
1250            lang.name(),
1251            js_only
1252                .iter()
1253                .map(|j| format!("{} ({})", j.name, j.reason))
1254                .collect::<Vec<_>>()
1255                .join(", ")
1256        );
1257    }
1258    if exports.is_empty() && classes.is_empty() {
1259        bail!(
1260            "unit `{}` exports no functions; bridge a unit with an exported function API",
1261            unit.id
1262        );
1263    }
1264
1265    let stem = unit
1266        .id
1267        .trim_end_matches('/')
1268        .rsplit('/')
1269        .next()
1270        .unwrap_or("unit")
1271        .split('.')
1272        .next()
1273        .unwrap_or("unit");
1274    let crate_name = opts.name.clone().unwrap_or_else(|| {
1275        let clean: String = stem
1276            .chars()
1277            .map(|c| {
1278                if c.is_ascii_alphanumeric() {
1279                    c.to_ascii_lowercase()
1280                } else {
1281                    '-'
1282                }
1283            })
1284            .collect();
1285        format!("{}-rs", clean.trim_matches('-'))
1286    });
1287    let crate_dir = opts
1288        .out
1289        .clone()
1290        .unwrap_or_else(|| root.join("rust").join(&crate_name));
1291    if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1292        bail!(
1293            "{} already exists and is not empty; rust-anything never overwrites a port in progress",
1294            crate_dir.display()
1295        );
1296    }
1297
1298    // UTF-16 helpers matter for JS strings only; Python indexes code points, like `chars()`.
1299    let utf16 =
1300        lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1301    let manifest = Manifest {
1302        schema: SCHEMA.into(),
1303        root: root.clone(),
1304        root_written: None,
1305        unit: unit.id.clone(),
1306        language: lang,
1307        kind,
1308        crate_name: crate_name.clone(),
1309        exports: exports.clone(),
1310        classes: classes.clone(),
1311        js_only: js_only.clone(),
1312        batches: parse_batches(&opts.batch)?,
1313        allocator: opts.allocator,
1314        float_tolerance: None,
1315        ignore_key_order: false,
1316    };
1317    if kind == Kind::CAbi {
1318        return bridge_c(&manifest, &crate_dir, &js_only);
1319    }
1320    if kind == Kind::Ffi {
1321        return bridge_ffi(&manifest, &crate_dir, &js_only);
1322    }
1323    let port = codegen::port_rs(&manifest);
1324    let fns = codegen::parse_port(&port);
1325    let modules = codegen::Modules {
1326        utf16,
1327        js: needs_js(&fns),
1328    };
1329    let mut files: Vec<(String, String)> = vec![
1330        (
1331            "Cargo.toml".into(),
1332            with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1333        ),
1334        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1335        ("src/port.rs".into(), port),
1336        loader_file(&manifest, &fns),
1337        (
1338            ".gitignore".into(),
1339            "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1340        ),
1341        ("README.md".into(), readme(&manifest)),
1342        (
1343            MANIFEST.into(),
1344            serde_json::to_string_pretty(&manifest)? + "\n",
1345        ),
1346    ];
1347    match kind {
1348        Kind::Napi => files.push((
1349            "build.rs".into(),
1350            "fn main() {\n    napi_build::setup();\n}\n".into(),
1351        )),
1352        Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1353        _ => {}
1354    }
1355    if utf16 {
1356        files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1357    }
1358    if modules.js {
1359        files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1360    }
1361    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1362        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1363    }
1364    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1365        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1366        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1367    }
1368    for (path, text) in &files {
1369        let target = crate_dir.join(path);
1370        if let Some(parent) = target.parent() {
1371            std::fs::create_dir_all(parent)?;
1372        }
1373        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1374    }
1375
1376    format_rust(&crate_dir);
1377    let mut notes = vec![format!(
1378        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1379        crate_dir.display()
1380    )];
1381    if utf16 {
1382        notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1383    }
1384    for j in &js_only {
1385        notes.push(format!(
1386            "`{}` stays in {}: {}. The shadow module re-exports the original.",
1387            j.name,
1388            lang.name(),
1389            j.reason
1390        ));
1391    }
1392    if exports.iter().any(codegen::is_async) {
1393        notes.push(
1394            "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1395        );
1396    }
1397    Ok(Outcome {
1398        crate_dir,
1399        kind,
1400        files: files.into_iter().map(|(p, _)| p).collect(),
1401        exports: exports
1402            .iter()
1403            .map(|f| f.name.clone())
1404            .chain(classes.iter().map(|c| format!("class {}", c.name)))
1405            .collect(),
1406        notes,
1407    })
1408}
1409
1410fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1411    for (path, text) in files {
1412        let target = crate_dir.join(path);
1413        if let Some(parent) = target.parent() {
1414            std::fs::create_dir_all(parent)?;
1415        }
1416        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1417    }
1418    Ok(())
1419}
1420
1421/// The generated C-side files: the `extern "C"` layer and its header. C signatures are fixed
1422/// by the original, so they come from the manifest, not from `port.rs`.
1423fn c_bindings(m: &Manifest, port: &str) -> Vec<(String, String)> {
1424    vec![
1425        ("src/lib.rs".into(), crate::codegen_c::lib_rs(m, port)),
1426        (
1427            format!("include/{}.h", m.lib_name()),
1428            crate::codegen_c::header(m),
1429        ),
1430    ]
1431}
1432
1433/// The generated layers of a JSON-dispatcher crate: `lib.rs` and the language-side wrapper.
1434fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1435    let mut files = if m.language == crate::lang::Lang::Ruby {
1436        vec![
1437            (
1438                "src/lib.rs".to_string(),
1439                with_allocator(
1440                    m,
1441                    crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1442                ),
1443            ),
1444            (
1445                "src/rbconv.rs".to_string(),
1446                crate::codegen_ruby::RBCONV_RS.to_string(),
1447            ),
1448            ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1449        ]
1450    } else {
1451        let mut lib = crate::codegen_ffi::lib_rs(m, api);
1452        if matches!(
1453            m.language,
1454            crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1455        ) {
1456            lib.push_str(&crate::codegen_java::typed_rs(m, api));
1457        }
1458        if m.language == crate::lang::Lang::Go {
1459            lib.push_str(&crate::codegen_go::typed_rs(m, api));
1460            lib.push_str(&crate::codegen_go::wire_rs(m, api));
1461            lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1462        }
1463        if matches!(
1464            m.language,
1465            crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1466        ) {
1467            lib.push_str(&crate::codegen_java::wire_rs(m, api));
1468            lib.push_str(
1469                &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1470            );
1471        }
1472        if matches!(
1473            m.language,
1474            crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1475        ) {
1476            lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1477        }
1478        let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1479        if matches!(
1480            m.language,
1481            crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1482        ) {
1483            files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1484        }
1485        files
1486    };
1487    match m.language {
1488        crate::lang::Lang::Go => {
1489            // The wrapper package takes its name and types from the original sources: without
1490            // them it would be written under a wrong name beside the old one.
1491            if crate::codegen_go::unit_sources(m).is_empty() {
1492                bail!(
1493                    "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1494                    m.unit,
1495                    m.root.display()
1496                );
1497            }
1498            files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1499            files.push((
1500                format!("go/{}.go", crate::codegen_go::package_name(m)),
1501                crate::codegen_go::wrapper(m, api),
1502            ));
1503        }
1504        crate::lang::Lang::Ruby => {
1505            files.push((
1506                crate::harness_ruby::wrapper_path(m),
1507                crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1508            ));
1509        }
1510        crate::lang::Lang::Php => {
1511            files.push((
1512                crate::codegen_php::wrapper_path(m),
1513                crate::codegen_php::wrapper(m),
1514            ));
1515        }
1516        crate::lang::Lang::Csharp => {
1517            files.push((
1518                crate::codegen_csharp::wrapper_path(m),
1519                crate::codegen_csharp::wrapper(m),
1520            ));
1521        }
1522        crate::lang::Lang::Powershell => {
1523            files.push((
1524                crate::codegen_powershell::wrapper_path(m),
1525                crate::codegen_powershell::wrapper(m),
1526            ));
1527        }
1528        crate::lang::Lang::Java | crate::lang::Lang::Kotlin => {
1529            files.extend(crate::codegen_java::wrappers(m, api));
1530            files.extend(
1531                crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1532            );
1533            files.push((
1534                format!(
1535                    "java/rustanything/{}.java",
1536                    crate::codegen_ffi::java_native_class(m)
1537                ),
1538                crate::codegen_java::native_class(m, api),
1539            ));
1540            files.push((
1541                "java/rustanything/RustAnythingJson.java".into(),
1542                crate::codegen_java::JSON_JAVA.into(),
1543            ));
1544            files.push((
1545                "java/rustanything/RustAnythingWire.java".into(),
1546                crate::codegen_java::WIRE_JAVA.into(),
1547            ));
1548            files.push((
1549                "java/rustanything/RustAnythingError.java".into(),
1550                crate::codegen_java::ERROR_JAVA.into(),
1551            ));
1552        }
1553        other => bail!("no wrapper generator for {}", other.name()),
1554    }
1555    Ok(files)
1556}
1557
1558fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1559    let port = codegen::port_rs(manifest);
1560    let api = codegen::parse_port(&port);
1561    let mut files = vec![
1562        (
1563            "Cargo.toml".to_string(),
1564            with_rayon(
1565                manifest,
1566                if manifest.language == crate::lang::Lang::Ruby {
1567                    crate::codegen_ruby::cargo_toml(manifest)
1568                } else {
1569                    crate::codegen_ffi::cargo_toml(manifest)
1570                },
1571            )?,
1572        ),
1573        ("src/port.rs".into(), port),
1574        (
1575            ".gitignore".into(),
1576            "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(),
1577        ),
1578        ("README.md".into(), readme(manifest)),
1579        (
1580            MANIFEST.into(),
1581            serde_json::to_string_pretty(manifest)? + "\n",
1582        ),
1583    ];
1584    files.extend(ffi_bindings(manifest, &api)?);
1585    write_files(crate_dir, &files)?;
1586    format_rust(crate_dir);
1587    format_wrapper(crate_dir);
1588    let mut notes = vec![format!(
1589        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1590        crate_dir.display()
1591    )];
1592    for j in kept {
1593        notes.push(format!(
1594            "`{}` stays in {}: {}.",
1595            j.name,
1596            manifest.language.name(),
1597            j.reason
1598        ));
1599    }
1600    Ok(Outcome {
1601        crate_dir: crate_dir.to_path_buf(),
1602        kind: Kind::Ffi,
1603        files: files.into_iter().map(|(p, _)| p).collect(),
1604        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1605        notes,
1606    })
1607}
1608
1609fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1610    let mut files = vec![
1611        (
1612            "Cargo.toml".to_string(),
1613            crate::codegen_c::cargo_toml(manifest),
1614        ),
1615        ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1616        (
1617            ".gitignore".into(),
1618            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\n".into(),
1619        ),
1620        ("README.md".into(), readme(manifest)),
1621        (
1622            MANIFEST.into(),
1623            serde_json::to_string_pretty(manifest)? + "\n",
1624        ),
1625    ];
1626    let port = crate::codegen_c::port_rs(manifest);
1627    files.extend(c_bindings(manifest, &port));
1628    write_files(crate_dir, &files)?;
1629    format_rust(crate_dir);
1630    let mut notes = vec![
1631        format!(
1632            "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1633            crate_dir.display()
1634        ),
1635        format!(
1636            "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1637            manifest.lib_name(),
1638            manifest.lib_name()
1639        ),
1640    ];
1641    for j in kept {
1642        notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1643    }
1644    Ok(Outcome {
1645        crate_dir: crate_dir.to_path_buf(),
1646        kind: Kind::CAbi,
1647        files: files.into_iter().map(|(p, _)| p).collect(),
1648        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1649        notes,
1650    })
1651}
1652
1653fn readme(m: &Manifest) -> String {
1654    use crate::lang::Lang;
1655    let functions: String = m
1656        .exports
1657        .iter()
1658        .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1659        .collect();
1660    let original = match m.language {
1661        Lang::Ts => "TS",
1662        other => other.name(),
1663    };
1664    let module = match m.kind {
1665        Kind::Napi => "napi-rs module",
1666        Kind::Wasm => "wasm-bindgen module",
1667        Kind::Pyo3 => "PyO3 module",
1668        Kind::CAbi => "C library",
1669        Kind::Ffi => "shared library",
1670    };
1671    let shadow = match m.language {
1672        Lang::Php | Lang::Csharp | Lang::Powershell => String::new(),
1673        _ => "rust-anything shadow .   # run both in the app, log mismatches\n".into(),
1674    };
1675    let switch = match m.language {
1676        Lang::Php => format!(
1677            "\nPHP has no shadow module: once `diff` passes, require `{}` in place of the original files.\n",
1678            crate::codegen_php::wrapper_path(m)
1679        ),
1680        Lang::Powershell => format!(
1681            "\nPowerShell has no shadow module: once `diff` passes, `rust-anything enable .` \
1682             dot-sources `{}` at the end of the original file, so every caller (the module's own \
1683             functions too) gets Rust. Most slow PowerShell is the start-up of a new `pwsh` per \
1684             command, which no port fixes: keep one shell open and call into it.\n",
1685            crate::codegen_powershell::wrapper_path(m)
1686        ),
1687        Lang::Csharp => format!(
1688            "\nC# has no shadow module: once `diff` passes, compile `{}` into the project and call \
1689             the `<namespace>.Rust` classes, with the built library next to the app.\n",
1690            crate::codegen_csharp::wrapper_path(m)
1691        ),
1692        _ => String::new(),
1693    };
1694    format!(
1695        "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1696         ## Loop\n\n```sh\nrust-anything record .   # record what the {original} code does\nrust-anything build .    # build the {module}\n\
1697         rust-anything diff .     # run the recorded cases against Rust\n{shadow}\
1698         rust-anything gate .     # fmt, clippy, tests, unsafe, API, diff\n```\n{switch}",
1699        name = m.crate_name,
1700        unit = m.unit,
1701        kind = match m.kind {
1702            Kind::Napi => "napi-rs",
1703            Kind::Wasm => "wasm-bindgen",
1704            Kind::Pyo3 => "PyO3",
1705            Kind::CAbi => "the C ABI",
1706            Kind::Ffi => "a JSON dispatcher",
1707        },
1708    )
1709}
1710
1711const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1712//!
1713//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1714//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1715
1716#![forbid(unsafe_code)]
1717
1718/// The UTF-16 code units of `s`, as JS sees the string.
1719pub fn units(s: &str) -> Vec<u16> {
1720    s.encode_utf16().collect()
1721}
1722
1723/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1724pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1725    let end = end.min(units.len());
1726    let start = start.min(end);
1727    String::from_utf16_lossy(&units[start..end])
1728}
1729
1730/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1731pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1732    let from = from.min(haystack.len());
1733    if needle.is_empty() {
1734        return Some(from);
1735    }
1736    haystack[from..]
1737        .windows(needle.len())
1738        .position(|w| w == needle)
1739        .map(|i| i + from)
1740}
1741
1742/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1743pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1744    if needle.is_empty() {
1745        return Some(haystack.len());
1746    }
1747    haystack.windows(needle.len()).rposition(|w| w == needle)
1748}
1749
1750/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1751pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1752    let mut seen = 0;
1753    for (byte, c) in s.char_indices() {
1754        if seen >= utf16_offset {
1755            return byte;
1756        }
1757        seen += c.len_utf16();
1758    }
1759    s.len()
1760}
1761
1762/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1763pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1764    s[..byte_offset.min(s.len())].encode_utf16().count()
1765}
1766
1767#[cfg(test)]
1768mod tests {
1769    use super::*;
1770
1771    #[test]
1772    fn matches_js_indexing() {
1773        let s = units("a👍b");
1774        assert_eq!(s.len(), 4);
1775        assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1776        assert_eq!(last_index_of(&s, &units("a")), Some(0));
1777        assert_eq!(slice(&s, 3, 4), "b");
1778        assert_eq!(byte_offset("a👍b", 3), 5);
1779        assert_eq!(utf16_offset("a👍b", 5), 3);
1780    }
1781}
1782"#;
1783
1784#[cfg(test)]
1785mod tests {
1786    use super::*;
1787
1788    #[test]
1789    fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1790        let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1791        let _ = std::fs::remove_dir_all(&base);
1792        let crate_dir = base.join("repo/rust/x-rs");
1793        std::fs::create_dir_all(&crate_dir).unwrap();
1794        std::fs::write(
1795            crate_dir.join(MANIFEST),
1796            r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1797        )
1798        .unwrap();
1799        let m = Manifest::load(&crate_dir).unwrap();
1800        assert_eq!(m.root, base.join("repo").canonical().unwrap());
1801        assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1802        // Written back, the file keeps the relative root.
1803        let mut back = m.clone();
1804        if let Some(w) = back.root_written.clone() {
1805            back.root = w;
1806        }
1807        assert!(
1808            serde_json::to_string(&back)
1809                .unwrap()
1810                .contains(r#""root":"../..""#)
1811        );
1812        std::fs::remove_dir_all(&base).unwrap();
1813    }
1814
1815    #[test]
1816    fn maps_ts_types() {
1817        assert_eq!(RType::from_ts("string").rust(), "String");
1818        assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1819        assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1820        assert_eq!(
1821            RType::from_ts("string | undefined").rust(),
1822            "Option<String>"
1823        );
1824        assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1825        assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1826        assert_eq!(
1827            RType::from_ts("Map<string, number>").rust(),
1828            "serde_json::Value"
1829        );
1830        assert_eq!(
1831            RType::from_ts("string | number").rust(),
1832            "serde_json::Value"
1833        );
1834        assert_eq!(
1835            RType::from_ts("Record<string, string | number>").rust(),
1836            "serde_json::Value"
1837        );
1838        assert_eq!(
1839            RType::from_ts("(string | undefined)").rust(),
1840            "Option<String>"
1841        );
1842        assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
1843    }
1844
1845    #[test]
1846    fn keeps_unbridgeable_exports_in_js() {
1847        let source = "export interface LineIndex {\n  readonly lineCount: number\n  position(offset: number): number\n}\n\
1848            export interface Range { start: number, end: number }\n\
1849            export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
1850            export function globToRegExp(glob: string): RegExp { return /x/ }\n\
1851            export function createLineIndex(text: string): LineIndex { return null! }\n\
1852            export function* walk(tree: object) {}\n\
1853            export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
1854            export function contains(range: Range, offset: number): boolean { return true }\n";
1855        let types = local_types("a.ts", source);
1856        let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
1857            .iter()
1858            .map(|f| (f.name.clone(), js_only_reason(f, &types)))
1859            .collect();
1860        let js_only: Vec<&str> = reasons
1861            .iter()
1862            .filter(|(_, r)| r.is_some())
1863            .map(|(n, _)| n.as_str())
1864            .collect();
1865        assert_eq!(
1866            js_only,
1867            [
1868                "keyMatcher",
1869                "globToRegExp",
1870                "createLineIndex",
1871                "walk",
1872                "sortTree"
1873            ]
1874        );
1875    }
1876
1877    #[test]
1878    fn resolves_simple_aliases() {
1879        let types = local_types(
1880            "m.ts",
1881            "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
1882        );
1883        assert_eq!(
1884            resolve_aliases("readonly KeyString[]", &types),
1885            "readonly string[]"
1886        );
1887        assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
1888        assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
1889    }
1890
1891    #[test]
1892    fn substitutes_simple_constraints() {
1893        let found = exported_functions(
1894            "a.ts",
1895            "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
1896             export function pick<T>(x: T): T { return x }\n\
1897             export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
1898        );
1899        let mut fns = found;
1900        for f in &mut fns {
1901            substitute_constraints(f, &[]);
1902        }
1903        assert_eq!(fns[0].params[0].ts_type, "(string)");
1904        assert!(fns[0].type_params.is_empty());
1905        assert_eq!(fns[1].type_params, ["T"]);
1906        assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
1907        assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
1908    }
1909
1910    #[test]
1911    fn as_json_bridges_a_data_generic() {
1912        let mut fns = exported_functions(
1913            "a.ts",
1914            "export function paginate<T>(items: T[], page: number): { data: T[] } { return { data: items } }\n",
1915        );
1916        assert!(js_only_reason(&fns[0], &[]).is_some());
1917        substitute_json(&mut fns[0], &["T".to_string()]);
1918        assert!(fns[0].type_params.is_empty());
1919        assert_eq!(fns[0].params[0].ts_type, "unknown[]");
1920        assert_eq!(fns[0].returns, "{ data: unknown[] }");
1921        assert!(js_only_reason(&fns[0], &[]).is_none());
1922    }
1923
1924    #[test]
1925    fn readme_fits_the_language() {
1926        let manifest = |language: &str, kind: &str| -> Manifest {
1927            serde_json::from_str(&format!(
1928                r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "src/X.cs", "language": "{language}", "kind": "{kind}", "crate_name": "x-rs", "exports": []}}"#
1929            ))
1930            .unwrap()
1931        };
1932        let ts = readme(&manifest("ts", "napi"));
1933        assert!(ts.contains("what the TS code does") && ts.contains("build the napi-rs module"));
1934        assert!(ts.contains("rust-anything shadow ."));
1935        let c = readme(&manifest("c", "c-abi"));
1936        assert!(c.contains("what the C code does") && c.contains("build the C library"));
1937        let cs = readme(&manifest("csharp", "ffi"));
1938        assert!(cs.contains("what the C# code does") && cs.contains("build the shared library"));
1939        assert!(!cs.contains("rust-anything shadow") && cs.contains("C# has no shadow module"));
1940        let php = readme(&manifest("php", "ffi"));
1941        assert!(!php.contains("rust-anything shadow") && php.contains("PHP has no shadow module"));
1942    }
1943
1944    #[test]
1945    fn makes_rust_names() {
1946        assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
1947        assert_eq!(snake_case("type"), "r#type");
1948        assert_eq!(snake_case("toURL"), "to_url");
1949        assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
1950        assert_eq!(snake_case("box"), "r#box");
1951        assert_eq!(snake_case("yield"), "r#yield");
1952        assert_eq!(snake_case("try"), "r#try");
1953        assert_eq!(snake_case("self"), "self_");
1954        assert_eq!(snake_case("Super"), "super_");
1955    }
1956}