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/// What `bridge` generated; every later step starts from it.
38#[derive(Clone, Debug, Serialize, Deserialize)]
39pub struct Manifest {
40    pub schema: String,
41    /// The repository root: absolute, or relative to the crate folder (so a crate kept inside
42    /// the repository it ports works in any clone). Resolved when the manifest is loaded.
43    pub root: PathBuf,
44    /// `root` as written in the file, when it was relative; written back instead of the resolved
45    /// path.
46    #[serde(skip)]
47    pub root_written: Option<PathBuf>,
48    pub unit: String,
49    #[serde(default)]
50    pub language: crate::lang::Lang,
51    pub kind: Kind,
52    pub crate_name: String,
53    /// Exports ported to Rust.
54    pub exports: Vec<ExportedFn>,
55    /// Exported classes ported to Rust: a struct with `new` and methods.
56    #[serde(default)]
57    pub classes: Vec<ExportedClass>,
58    /// Exports that cannot cross the bridge as they are; they stay in TS and the shadow module
59    /// re-exports them from the original.
60    #[serde(default)]
61    pub js_only: Vec<JsOnly>,
62    /// Functions run over many items kept in Rust (`--batch function:param`).
63    #[serde(default, skip_serializing_if = "Vec::is_empty")]
64    pub batches: Vec<crate::codegen_batch::Batch>,
65    /// Floats match within this relative tolerance (`record --float-tolerance`).
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub float_tolerance: Option<f64>,
68}
69
70#[derive(Clone, Debug, Serialize, Deserialize)]
71pub struct JsOnly {
72    pub name: String,
73    pub file: String,
74    pub line: u32,
75    pub reason: String,
76}
77
78/// Whether values of the local type `name` can hold functions: the type has a function or
79/// method member, or extends or mentions a type that does.
80fn has_functions(name: &str, local_types: &[LocalType], seen: &mut Vec<String>) -> bool {
81    if seen.iter().any(|s| s == name) {
82        return false;
83    }
84    seen.push(name.to_string());
85    let Some(t) = local_types.iter().find(|t| t.name == name) else {
86        return false;
87    };
88    let text = &t.text;
89    let method = text.lines().skip(1).any(|l| {
90        let l = l.trim().trim_start_matches("readonly ");
91        l.contains('(')
92            && l.split('(').next().is_some_and(|head| {
93                !head.is_empty()
94                    && head
95                        .chars()
96                        .all(|c| c.is_alphanumeric() || c == '_' || c == '?')
97            })
98    });
99    if text.contains("=>") || method {
100        return true;
101    }
102    text.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
103        .filter(|w| !w.is_empty() && *w != name)
104        .any(|w| has_functions(w, local_types, seen))
105}
106
107/// Why an export cannot cross a JS/Rust bridge unchanged, if it cannot.
108///
109/// Functions, iterators, RegExp objects and objects with function members are JS values a
110/// Rust function can neither take nor return; porting them would change the public API.
111pub fn js_only_reason(f: &ExportedFn, local_types: &[LocalType]) -> Option<String> {
112    if let Some(blocker) = &f.blocker {
113        return Some(blocker.clone());
114    }
115    if f.is_generator {
116        return Some("generator: returns a lazy iterator".into());
117    }
118    if f.uses_instanceof {
119        return Some("checks `instanceof`: class identity does not survive the bridge".into());
120    }
121    let types: Vec<&str> = f
122        .params
123        .iter()
124        .map(|p| p.ts_type.as_str())
125        .chain(std::iter::once(f.returns.as_str()))
126        .collect();
127    if types.iter().any(|t| t.contains("=>")) {
128        return Some("takes or returns a function".into());
129    }
130    let words = |t: &str| -> Vec<String> {
131        t.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
132            .filter(|w| !w.is_empty())
133            .map(str::to_string)
134            .collect()
135    };
136    for t in &types {
137        for word in words(t) {
138            match word.as_str() {
139                "RegExp" => return Some("takes or returns a RegExp".into()),
140                "Generator" | "Iterator" | "IterableIterator" | "AsyncGenerator"
141                | "AsyncIterable" => {
142                    return Some(format!("uses `{word}`, a lazy iterator"));
143                }
144                "Function" => return Some("takes or returns a function".into()),
145                _ => {}
146            }
147            if f.type_params.contains(&word) {
148                return Some(format!(
149                    "generic over `{word}`: values of any shape, functions included"
150                ));
151            }
152            if has_functions(&word, local_types, &mut Vec::new()) {
153                return Some(format!("uses `{word}`, which has function members"));
154            }
155        }
156    }
157    None
158}
159
160impl Manifest {
161    pub fn load(crate_dir: &Path) -> Result<Self> {
162        let path = crate_dir.join(MANIFEST);
163        let text = std::fs::read_to_string(&path).with_context(|| {
164            format!(
165                "reading {} (run `rust-anything bridge` first)",
166                path.display()
167            )
168        })?;
169        let mut manifest: Self =
170            serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
171        if manifest.root.is_relative() {
172            let resolved = crate_dir.join(&manifest.root);
173            let resolved = resolved.canonical().unwrap_or(resolved);
174            manifest.root_written = Some(std::mem::replace(&mut manifest.root, resolved));
175        }
176        Ok(manifest)
177    }
178
179    /// Writes the manifest back, keeping a relative root relative.
180    pub fn save(&self, crate_dir: &Path) -> Result<()> {
181        let mut m = self.clone();
182        if let Some(written) = m.root_written.take() {
183            m.root = written;
184        }
185        let path = crate_dir.join(MANIFEST);
186        std::fs::write(&path, serde_json::to_string_pretty(&m)? + "\n")
187            .with_context(|| format!("writing {}", path.display()))
188    }
189
190    /// Rust library name: the crate name with `-` replaced.
191    pub fn lib_name(&self) -> String {
192        self.crate_name.replace('-', "_")
193    }
194}
195
196pub struct Options<'a> {
197    pub root: &'a Path,
198    pub unit: &'a str,
199    pub kind: Option<Kind>,
200    pub out: Option<PathBuf>,
201    pub name: Option<String>,
202    /// Bridge a unit the plan marks blocked or keep.
203    pub force: bool,
204    /// Exports to keep in TS, with an optional reason: `name` or `name: reason`.
205    pub keep: Vec<String>,
206    /// Source language; detected from the repository when `None`.
207    pub lang: Option<crate::lang::Lang>,
208    /// `function:param` pairs: batch classes running `function` over many `param` values.
209    pub batch: Vec<String>,
210}
211
212#[derive(Debug, Serialize)]
213pub struct Outcome {
214    pub crate_dir: PathBuf,
215    pub kind: Kind,
216    pub files: Vec<String>,
217    pub exports: Vec<String>,
218    pub notes: Vec<String>,
219}
220
221/// A Rust type as seen by the port, from a TS type annotation.
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub enum RType {
224    Str,
225    F64,
226    /// A whole number (`int` in the type dialect: Python, Go, Java and C have one; JS does not).
227    Int,
228    Bool,
229    Unit,
230    Vec(Box<RType>),
231    Opt(Box<RType>),
232    /// Anything structured: crosses the bridge as JSON.
233    Json,
234}
235
236impl RType {
237    pub fn from_ts(ts: &str) -> Self {
238        let ts = ts.trim().trim_start_matches("readonly ").trim();
239        // `(string | null)`: one parenthesized group around the whole type.
240        if let Some(inner) = ts.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
241            && balanced(inner)
242        {
243            return Self::from_ts(inner);
244        }
245        if let Some(inner) = ts
246            .strip_prefix("Promise<")
247            .and_then(|t| t.strip_suffix('>'))
248        {
249            return Self::from_ts(inner);
250        }
251        let parts = split_top(ts, '|');
252        if parts.len() > 1 {
253            let (nullish, rest): (Vec<&str>, Vec<&str>) = parts
254                .iter()
255                .partition(|p| matches!(p.trim(), "undefined" | "null" | "void"));
256            if rest.iter().all(|p| is_string_literal(p)) {
257                return Self::wrap_opt(Self::Str, !nullish.is_empty());
258            }
259            if rest.len() == 1 {
260                return Self::wrap_opt(Self::from_ts(rest[0]), !nullish.is_empty());
261            }
262            return Self::Json;
263        }
264        if let Some(inner) = ts.strip_suffix("[]") {
265            return Self::Vec(Box::new(Self::from_ts(
266                inner.trim_start_matches('(').trim_end_matches(')'),
267            )));
268        }
269        for wrapper in ["Array<", "ReadonlyArray<"] {
270            if let Some(inner) = ts.strip_prefix(wrapper).and_then(|t| t.strip_suffix('>')) {
271                return Self::Vec(Box::new(Self::from_ts(inner)));
272            }
273        }
274        // `value is MessageLeaf`: a type predicate returns a boolean; `asserts x` returns nothing.
275        if ts.starts_with("asserts ") {
276            return Self::Unit;
277        }
278        if let Some((subject, _)) = ts.split_once(" is ")
279            && subject
280                .trim()
281                .chars()
282                .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
283        {
284            return Self::Bool;
285        }
286        match ts {
287            "string" => Self::Str,
288            "number" => Self::F64,
289            "int" => Self::Int,
290            "boolean" => Self::Bool,
291            "void" | "undefined" => Self::Unit,
292            _ if is_string_literal(ts) => Self::Str,
293            _ => Self::Json,
294        }
295    }
296
297    fn wrap_opt(t: Self, optional: bool) -> Self {
298        if optional { Self::Opt(Box::new(t)) } else { t }
299    }
300
301    pub fn rust(&self) -> String {
302        match self {
303            Self::Str => "String".into(),
304            Self::F64 => "f64".into(),
305            Self::Int => "i64".into(),
306            Self::Bool => "bool".into(),
307            Self::Unit => "()".into(),
308            Self::Vec(t) => format!("Vec<{}>", t.rust()),
309            Self::Opt(t) => format!("Option<{}>", t.rust()),
310            Self::Json => "serde_json::Value".into(),
311        }
312    }
313
314    pub fn contains_json(&self) -> bool {
315        match self {
316            Self::Json => true,
317            Self::Vec(t) | Self::Opt(t) => t.contains_json(),
318            _ => false,
319        }
320    }
321}
322
323fn is_string_literal(ts: &str) -> bool {
324    let ts = ts.trim();
325    ts.len() >= 2
326        && ((ts.starts_with('\'') && ts.ends_with('\''))
327            || (ts.starts_with('"') && ts.ends_with('"')))
328}
329
330fn balanced(ts: &str) -> bool {
331    let mut depth = 0i32;
332    for c in ts.chars() {
333        match c {
334            '(' => depth += 1,
335            ')' => {
336                depth -= 1;
337                if depth < 0 {
338                    return false;
339                }
340            }
341            _ => {}
342        }
343    }
344    depth == 0
345}
346
347/// Splits on `sep` outside brackets.
348fn split_top(ts: &str, sep: char) -> Vec<&str> {
349    let mut out = Vec::new();
350    let mut depth = 0i32;
351    let mut start = 0;
352    for (i, c) in ts.char_indices() {
353        match c {
354            '<' | '(' | '[' | '{' => depth += 1,
355            '>' | ')' | ']' | '}' => depth -= 1,
356            c if c == sep && depth == 0 => {
357                out.push(ts[start..i].trim());
358                start = i + c.len_utf8();
359            }
360            _ => {}
361        }
362    }
363    out.push(ts[start..].trim());
364    out.retain(|p| !p.is_empty());
365    out
366}
367
368/// A parameter's type for the port, rest and optional parameters included.
369pub fn param_type(p: &crate::ts::exports::Param) -> RType {
370    let base = RType::from_ts(&p.ts_type);
371    let base = if p.rest {
372        match base {
373            RType::Vec(_) => base,
374            other => RType::Vec(Box::new(other)),
375        }
376    } else {
377        base
378    };
379    if p.optional && !matches!(base, RType::Opt(_)) {
380        RType::Opt(Box::new(base))
381    } else {
382        base
383    }
384}
385
386pub fn snake_case(name: &str) -> String {
387    let chars: Vec<char> = name.chars().collect();
388    let mut out = String::new();
389    for (i, &c) in chars.iter().enumerate() {
390        if c.is_uppercase() {
391            let prev = i.checked_sub(1).map(|j| chars[j]);
392            let next = chars.get(i + 1);
393            let boundary = prev.is_some_and(|p| p.is_lowercase() || p.is_ascii_digit())
394                || (prev.is_some_and(char::is_uppercase) && next.is_some_and(|n| n.is_lowercase()));
395            if boundary {
396                out.push('_');
397            }
398            out.extend(c.to_lowercase());
399        } else if c.is_alphanumeric() {
400            out.push(c);
401        } else {
402            out.push('_');
403        }
404    }
405    const KEYWORDS: &[&str] = &[
406        "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
407        "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
408        "return", "self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use",
409        "where", "while", "async", "await", "dyn", "gen",
410    ];
411    if KEYWORDS.contains(&out.as_str()) {
412        format!("r#{out}")
413    } else {
414        out
415    }
416}
417
418/// Types declared in `file` and in the files it imports relatively (one level deep).
419pub fn types_in_scope(root: &Path, file: &str, text: &str) -> Vec<LocalType> {
420    let mut types = Vec::new();
421    let mut seen = std::collections::HashSet::new();
422    collect_types(root, file, text, 0, &mut seen, &mut types);
423    types
424}
425
426/// Types of a file and of the files it imports or re-exports, a few levels deep
427/// (`./types` -> `types/index.ts` -> `export * from './host'`).
428fn collect_types(
429    root: &Path,
430    file: &str,
431    text: &str,
432    depth: usize,
433    seen: &mut std::collections::HashSet<String>,
434    types: &mut Vec<LocalType>,
435) {
436    if depth > 4 || !seen.insert(file.to_string()) {
437        return;
438    }
439    types.extend(local_types(file, text));
440    let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
441    for import in crate::ts::scan::scan(file, text).imports {
442        let spec = import.specifier;
443        // Workspace packages (`@x18n/core`) are followed to their source entry.
444        let base = if spec.starts_with('.') {
445            let joined = if dir.is_empty() {
446                spec.clone()
447            } else {
448                format!("{dir}/{spec}")
449            };
450            match normalize_rel(&joined) {
451                Some(base) => base,
452                None => continue,
453            }
454        } else {
455            let name = crate::ts::deps::package_name(&spec);
456            let Some(pkg_dir) = workspace_packages(root).get(name).cloned() else {
457                continue;
458            };
459            let sub = spec[name.len()..].trim_start_matches('/');
460            let src = if root.join(&pkg_dir).join("src").is_dir() {
461                format!("{pkg_dir}/src")
462            } else {
463                pkg_dir
464            };
465            let src = src.trim_start_matches('/').to_string();
466            if sub.is_empty() {
467                format!("{src}/index")
468            } else {
469                format!("{src}/{sub}")
470            }
471        };
472        let stem = base.trim_end_matches(".js");
473        let candidates = [
474            format!("{stem}.ts"),
475            format!("{stem}.mts"),
476            format!("{stem}.d.ts"),
477            format!("{stem}/index.ts"),
478            base.clone(),
479        ];
480        if let Some(found) = candidates.iter().find(|c| root.join(c).is_file())
481            && let Ok(imported) = std::fs::read_to_string(root.join(found))
482        {
483            collect_types(root, found, &imported, depth + 1, seen, types);
484        }
485    }
486}
487
488/// Workspace package names and their root-relative folders, read once per root.
489fn workspace_packages(root: &Path) -> std::collections::HashMap<String, String> {
490    use std::sync::{Mutex, OnceLock};
491    static CACHE: OnceLock<
492        Mutex<std::collections::HashMap<PathBuf, std::collections::HashMap<String, String>>>,
493    > = OnceLock::new();
494    let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
495    let mut cache = cache
496        .lock()
497        .unwrap_or_else(std::sync::PoisonError::into_inner);
498    cache
499        .entry(root.to_path_buf())
500        .or_insert_with(|| {
501            crate::ts::discover::discover(root)
502                .map(|ws| ws.packages.into_iter().map(|p| (p.name, p.dir)).collect())
503                .unwrap_or_default()
504        })
505        .clone()
506}
507
508/// Collapses `.` and `..` in a root-relative path.
509fn normalize_rel(path: &str) -> Option<String> {
510    let mut parts: Vec<&str> = Vec::new();
511    for part in path.split('/') {
512        match part {
513            "" | "." => {}
514            ".." => {
515                parts.pop()?;
516            }
517            _ => parts.push(part),
518        }
519    }
520    Some(parts.join("/"))
521}
522
523/// `f<T extends string>(s: T)` takes a string: type parameters with a simple constraint are
524/// replaced by it. The rest stay listed, and keep the function in TS.
525pub fn substitute_constraints(f: &mut ExportedFn, types: &[LocalType]) {
526    let mut remaining = Vec::new();
527    for tp in std::mem::take(&mut f.type_params) {
528        let Some((name, constraint)) = tp.split_once(" extends ") else {
529            remaining.push(tp);
530            continue;
531        };
532        let constraint = resolve_aliases(constraint, types);
533        // Data constraints (`string`, `string | readonly string[]`) are substituted; anything that
534        // could hold a function keeps the type parameter, and the function stays in TS.
535        let open_ended = constraint.contains("=>")
536            || constraint
537                .split(|c: char| !(c.is_alphanumeric() || c == '_'))
538                .any(|w| {
539                    matches!(w, "Function" | "object" | "unknown" | "any")
540                        || has_functions(w, types, &mut Vec::new())
541                });
542        if open_ended {
543            remaining.push(name.to_string());
544            continue;
545        }
546        let replacement = format!("({constraint})");
547        for p in &mut f.params {
548            p.ts_type = replace_word(&p.ts_type, name, &replacement);
549        }
550        f.returns = replace_word(&f.returns, name, &replacement);
551    }
552    f.type_params = remaining;
553}
554
555fn replace_word(text: &str, word: &str, with: &str) -> String {
556    let mut out = String::new();
557    let mut current = String::new();
558    for c in text.chars().chain(std::iter::once(' ')) {
559        if c.is_alphanumeric() || c == '_' || c == '$' {
560            current.push(c);
561        } else {
562            out.push_str(if current == word { with } else { &current });
563            current.clear();
564            out.push(c);
565        }
566    }
567    out.pop();
568    out
569}
570
571/// Replaces simple type aliases (`type KeyString = string`) by what they stand for.
572pub fn resolve_aliases(ts: &str, types: &[LocalType]) -> String {
573    let mut out = ts.to_string();
574    for _ in 0..4 {
575        let mut changed = false;
576        let mut next = String::with_capacity(out.len());
577        let mut word = String::new();
578        let flush = |word: &mut String, next: &mut String, changed: &mut bool| {
579            if let Some(t) = types.iter().find(|t| t.alias && t.name == *word) {
580                let text = t.text.trim();
581                if text.contains('|') {
582                    next.push('(');
583                    next.push_str(text);
584                    next.push(')');
585                } else {
586                    next.push_str(text);
587                }
588                *changed = true;
589            } else {
590                next.push_str(word);
591            }
592            word.clear();
593        };
594        for c in out.chars() {
595            if c.is_alphanumeric() || c == '_' || c == '$' {
596                word.push(c);
597            } else {
598                flush(&mut word, &mut next, &mut changed);
599                next.push(c);
600            }
601        }
602        flush(&mut word, &mut next, &mut changed);
603        out = next;
604        if !changed {
605            break;
606        }
607    }
608    out
609}
610
611fn needs_js(api: &codegen::PortApi) -> bool {
612    api.needs_json()
613}
614
615/// The reason given with `--keep name` or `--keep "name: reason"`, if `name` is kept.
616fn keep_reason(keep: &[String], name: &str) -> Option<String> {
617    keep.iter().find_map(|k| {
618        let (kept, reason) = k
619            .split_once(':')
620            .map_or((k.as_str(), ""), |(n, r)| (n.trim(), r.trim()));
621        (kept == name).then(|| {
622            if reason.is_empty() {
623                "kept on request".to_string()
624            } else {
625                reason.to_string()
626            }
627        })
628    })
629}
630
631/// Formats the generated Rust, best effort: the gate checks formatting.
632fn format_rust(crate_dir: &Path) {
633    let files: Vec<PathBuf> = std::fs::read_dir(crate_dir.join("src"))
634        .into_iter()
635        .flatten()
636        .flatten()
637        .map(|e| e.path())
638        .filter(|p| p.extension().is_some_and(|e| e == "rs"))
639        .collect();
640    let _ = std::process::Command::new("rustfmt")
641        .args(["--edition", "2024"])
642        .args(&files)
643        .output();
644}
645
646/// Formats a generated Go wrapper with `gofmt`, best effort.
647fn format_wrapper(crate_dir: &Path) {
648    if crate_dir.join("go").is_dir() {
649        let _ = std::process::Command::new("gofmt")
650            .arg("-w")
651            .arg(crate_dir.join("go"))
652            .output();
653    }
654}
655
656/// `lib.rs` of a JS crate: the bindings, and the binary wire when functions use it.
657fn js_lib_rs(m: &Manifest, api: &codegen::PortApi, modules: &codegen::Modules) -> Result<String> {
658    let mut lib = with_allocator(m, codegen::lib_rs(m, api, modules));
659    if m.kind != Kind::Pyo3 && !m.batches.is_empty() {
660        lib.push_str(&crate::codegen_batch::js_rs(m, api).map_err(anyhow::Error::msg)?);
661    }
662    if !crate::codegen_tswire::uses_wire(m, api) {
663        return Ok(lib);
664    }
665    Ok(lib.replacen(
666        "pub mod port;",
667        "pub mod port;\npub mod wire;\n\n#[allow(unused_imports)]\nuse serde_json::Value;",
668        1,
669    ) + &crate::codegen_tswire::napi_rs(m, api))
670}
671
672fn parse_batches(specs: &[String]) -> Result<Vec<crate::codegen_batch::Batch>> {
673    specs
674        .iter()
675        .map(|s| {
676            crate::codegen_batch::Batch::parse(s)
677                .with_context(|| format!("`--batch {s}`: write it as function:param"))
678        })
679        .collect()
680}
681
682/// Adds batch classes to a bridged crate, then regenerates its bindings.
683pub fn add_batches(crate_dir: &Path, specs: &[String]) -> Result<Refreshed> {
684    let path = crate_dir.join(MANIFEST);
685    let before = std::fs::read_to_string(&path).with_context(|| format!("{}", path.display()))?;
686    let mut manifest = Manifest::load(crate_dir)?;
687    for b in parse_batches(specs)? {
688        if !manifest.batches.contains(&b) {
689            manifest.batches.push(b);
690        }
691    }
692    if let Some(written) = manifest.root_written.clone() {
693        manifest.root = written;
694    }
695    std::fs::write(&path, serde_json::to_string_pretty(&manifest)? + "\n")?;
696    // A batch the port cannot serve leaves the crate as it was.
697    refresh(crate_dir).inspect_err(|_| {
698        let _ = std::fs::write(&path, &before);
699    })
700}
701
702/// Cargo.toml with the dependencies and library types today's bindings need, for crates
703/// bridged by an older rust-anything; versions and features already set are kept.
704fn with_template_deps(cargo: &str, template: &str) -> Result<String> {
705    let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
706    let template: toml_edit::DocumentMut = template.parse().context("Cargo.toml template")?;
707    if let Some(want) = template.get("dependencies").and_then(|d| d.as_table()) {
708        let deps = doc["dependencies"].or_insert(toml_edit::table());
709        for (name, item) in want {
710            if deps.get(name).is_none() {
711                deps[name] = item.clone();
712            }
713        }
714    }
715    if let Some(want) = template.get("features").and_then(|d| d.as_table()) {
716        let features = doc["features"].or_insert(toml_edit::table());
717        for (name, item) in want {
718            if features.get(name).is_none() {
719                features[name] = item.clone();
720            }
721        }
722    }
723    if let Some(kinds) = template.get("lib").and_then(|l| l.get("crate-type")) {
724        doc["lib"]["crate-type"] = kinds.clone();
725    }
726    Ok(doc.to_string())
727}
728
729/// Whether the crate allocates with mimalloc: crates with batches, which allocate from all cores
730/// at once (the system allocator serializes them: 1.6x on 4 cores instead of 3.2x). Not wasm,
731/// which runs on one thread. Only Rust code uses this heap; every buffer that crosses the bridge
732/// is copied or freed by Rust.
733fn needs_mimalloc(m: &Manifest) -> bool {
734    !m.batches.is_empty() && m.kind != Kind::Wasm
735}
736
737/// `lib.rs` with mimalloc as the global allocator when [`needs_mimalloc`].
738fn with_allocator(m: &Manifest, lib: String) -> String {
739    if !needs_mimalloc(m) {
740        return lib;
741    }
742    lib.replacen(
743        "pub mod port;",
744        "pub mod port;\n\n/// Batches allocate on all cores at once; mimalloc keeps that from serializing.\n\
745         #[global_allocator]\nstatic GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;\n",
746        1,
747    )
748}
749
750/// Cargo.toml with rayon (and mimalloc) when batches run on all cores.
751fn with_rayon(m: &Manifest, cargo: String) -> Result<String> {
752    if !crate::codegen_batch::needs_rayon(m) {
753        return Ok(cargo);
754    }
755    let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
756    let deps = doc["dependencies"].or_insert(toml_edit::table());
757    if deps.get("rayon").is_none() {
758        deps["rayon"] = toml_edit::value("1");
759    }
760    if needs_mimalloc(m) && deps.get("mimalloc").is_none() {
761        deps["mimalloc"] = toml_edit::value("0.1");
762    }
763    Ok(doc.to_string())
764}
765
766/// The language-side loader: `index.cjs` for JS, the wrapper package for Python.
767fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
768    match m.kind {
769        Kind::Pyo3 => (
770            format!("python/{}/__init__.py", m.lib_name()),
771            crate::codegen_py::package_init(m, api),
772        ),
773        _ => (
774            "index.cjs".into(),
775            codegen::index_cjs(m, api)
776                + &crate::codegen_tswire::index_cjs(m, api)
777                + &codegen::guard_cjs(api),
778        ),
779    }
780}
781
782/// A port function whose doc line does not name an export (`/// Port of \`Integer.toString\``)
783/// takes the name of the export it was generated for, matched by its Rust name.
784pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
785    for f in &mut api.functions {
786        if m.exports.iter().any(|e| e.name == f.js_name) {
787            continue;
788        }
789        let rust = f.rust_name.trim_start_matches("r#");
790        if let Some(e) = m
791            .exports
792            .iter()
793            .find(|e| snake_case(&e.name).trim_start_matches("r#") == rust)
794        {
795            f.js_name = e.name.clone();
796        }
797    }
798}
799
800/// What `refresh` rewrote.
801#[derive(Debug, Serialize)]
802pub struct Refreshed {
803    pub functions: Vec<String>,
804    pub files: Vec<String>,
805}
806
807/// Regenerates the binding layer (`lib.rs`, `index.cjs`, `js.rs`) from the signatures in
808/// `port.rs`, and adds the dependencies they need to Cargo.toml. Never touches `port.rs`.
809pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
810    let manifest = Manifest::load(crate_dir)?;
811    if manifest.kind == Kind::CAbi {
812        let mut files = c_bindings(&manifest);
813        let cargo =
814            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
815        files.push((
816            "Cargo.toml".into(),
817            with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
818        ));
819        write_files(crate_dir, &files)?;
820        format_rust(crate_dir);
821        return Ok(Refreshed {
822            functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
823            files: files.into_iter().map(|(p, _)| p).collect(),
824        });
825    }
826    if manifest.kind == Kind::Ffi {
827        let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
828            .context("reading src/port.rs")?;
829        let mut api = codegen::parse_port(&port);
830        match_export_names(&manifest, &mut api);
831        let mut files = ffi_bindings(&manifest, &api)?;
832        let cargo =
833            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
834        let template = if manifest.language == crate::lang::Lang::Ruby {
835            crate::codegen_ruby::cargo_toml(&manifest)
836        } else {
837            crate::codegen_ffi::cargo_toml(&manifest)
838        };
839        let cargo = with_template_deps(&cargo, &template)?;
840        files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
841        write_files(crate_dir, &files)?;
842        format_rust(crate_dir);
843        format_wrapper(crate_dir);
844        return Ok(Refreshed {
845            functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
846            files: files.into_iter().map(|(p, _)| p).collect(),
847        });
848    }
849    let port =
850        std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
851    let mut fns = codegen::parse_port(&port);
852    match_export_names(&manifest, &mut fns);
853    if fns.functions.is_empty() && fns.classes.is_empty() {
854        bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
855    }
856    let modules = codegen::Modules {
857        utf16: crate_dir.join("src/utf16.rs").exists(),
858        js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
859    };
860    let mut files: Vec<(String, String)> = vec![
861        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
862        loader_file(&manifest, &fns),
863    ];
864    if modules.js {
865        files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
866    }
867    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
868        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
869    }
870    let extension = manifest.kind == Kind::Pyo3
871        || (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
872    if extension && !crate_dir.join("build.rs").exists() {
873        files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
874    }
875    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
876        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
877        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
878    }
879    let cargo_path = crate_dir.join("Cargo.toml");
880    let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
881    let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns).map_err(anyhow::Error::msg)?;
882    let cargo = with_rayon(&manifest, cargo)?;
883    files.push(("Cargo.toml".into(), cargo));
884    for (path, text) in &files {
885        let target = crate_dir.join(path);
886        if let Some(parent) = target.parent() {
887            std::fs::create_dir_all(parent)?;
888        }
889        std::fs::write(&target, text).with_context(|| format!("writing {path}"))?;
890    }
891    format_rust(crate_dir);
892    Ok(Refreshed {
893        functions: fns
894            .functions
895            .iter()
896            .map(|f| f.js_name.clone())
897            .chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
898            .collect(),
899        files: files.into_iter().map(|(p, _)| p).collect(),
900    })
901}
902
903/// `build.rs` for Python and Ruby extensions: on macOS the library (and its test binary) links
904/// against symbols the interpreter provides only at load time.
905pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
906    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
907        println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
908    }
909}
910"#;
911
912pub fn bridge(opts: &Options) -> Result<Outcome> {
913    let root = opts
914        .root
915        .canonical()
916        .with_context(|| format!("resolving {}", opts.root.display()))?;
917    let lang = opts
918        .lang
919        .unwrap_or_else(|| crate::lang::Lang::detect(&root));
920    let report = analyze::analyze_lang(&root, lang)?;
921    let wanted = opts.unit.trim_start_matches("./");
922    let whole = report
923        .units
924        .iter()
925        .find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'));
926    let single = || {
927        report
928            .units
929            .iter()
930            .find(|u| u.files.iter().any(|f| f == wanted))
931            .map(|u| {
932                let mut one = u.clone();
933                one.id = wanted.to_string();
934                one.files = vec![wanted.to_string()];
935                one
936            })
937    };
938    let unit = match whole.cloned().or_else(single) {
939        Some(unit) => unit,
940        None => bail!(
941            "no unit or source file `{wanted}`; `rust-anything analyze` lists unit ids, and any \
942             source file inside a unit can be bridged on its own"
943        ),
944    };
945    let unit = &unit;
946    if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
947        bail!(
948            "unit `{}` is {:?}: {}. Pass --force to bridge it anyway.",
949            unit.id,
950            unit.status,
951            unit.notes.first().map_or("", String::as_str)
952        );
953    }
954    if unit.bridge == Bridge::PhpFfi {
955        bail!(
956            "bridging PHP units into Rust comes next (PHP FFI over a C ABI); for now a PHP app can \
957             be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
958             door (`app front-door`) that hands everything to the original"
959        );
960    }
961    if unit.bridge == Bridge::DotnetFfi {
962        bail!(
963            "bridging C# units into Rust comes next (P/Invoke over a C ABI); for now a C# app can \
964             be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
965             door (`app front-door`) that hands everything to the original"
966        );
967    }
968    let kind = opts.kind.unwrap_or(match unit.bridge {
969        Bridge::WasmBindgen => Kind::Wasm,
970        Bridge::Pyo3 => Kind::Pyo3,
971        Bridge::CAbi => Kind::CAbi,
972        Bridge::Cgo | Bridge::Fiddle | Bridge::Jni => Kind::Ffi,
973        _ => Kind::Napi,
974    });
975
976    let mut exports = Vec::new();
977    let mut classes = Vec::new();
978    let mut js_only = Vec::new();
979    for file in &unit.files {
980        if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
981            continue;
982        }
983        let text =
984            std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
985        if lang != crate::lang::Lang::Ts {
986            let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
987            for f in functions {
988                match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
989                    Some(reason) => js_only.push(JsOnly {
990                        name: f.name,
991                        file: f.file,
992                        line: f.line,
993                        reason,
994                    }),
995                    None => exports.push(f),
996                }
997            }
998            for class in foreign_classes {
999                let method_reason = class
1000                    .methods
1001                    .iter()
1002                    .find_map(|m| js_only_reason(m, &[]).map(|r| format!("`{}`: {r}", m.name)));
1003                match keep_reason(&opts.keep, &class.name)
1004                    .or_else(|| class.blocker.clone())
1005                    .or(method_reason)
1006                {
1007                    Some(reason) => js_only.push(JsOnly {
1008                        name: class.name,
1009                        file: class.file,
1010                        line: class.line,
1011                        reason: format!("class: {reason}"),
1012                    }),
1013                    None => classes.push(class),
1014                }
1015            }
1016            continue;
1017        }
1018        let types = types_in_scope(&root, file, &text);
1019        for mut class in exported_classes(file, &text) {
1020            let kept = keep_reason(&opts.keep, &class.name);
1021            let constructor = ExportedFn {
1022                name: format!("{} constructor", class.name),
1023                file: class.file.clone(),
1024                line: class.line,
1025                params: class.constructor.clone(),
1026                returns: "void".into(),
1027                is_async: false,
1028                is_generator: false,
1029                type_params: Vec::new(),
1030                uses_instanceof: false,
1031                ..Default::default()
1032            };
1033            let method_reason = std::iter::once(&constructor)
1034                .chain(&class.methods)
1035                .find_map(|m| js_only_reason(m, &types).map(|r| format!("`{}`: {r}", m.name)));
1036            match kept.or_else(|| class.blocker.clone()).or(method_reason) {
1037                Some(reason) => js_only.push(JsOnly {
1038                    name: class.name,
1039                    file: class.file,
1040                    line: class.line,
1041                    reason: format!("class: {reason}"),
1042                }),
1043                None => {
1044                    for p in &mut class.constructor {
1045                        p.ts_type = resolve_aliases(&p.ts_type, &types);
1046                    }
1047                    for m in &mut class.methods {
1048                        for p in &mut m.params {
1049                            p.ts_type = resolve_aliases(&p.ts_type, &types);
1050                        }
1051                        m.returns = resolve_aliases(&m.returns, &types);
1052                    }
1053                    classes.push(class);
1054                }
1055            }
1056        }
1057        for mut f in exported_functions(file, &text) {
1058            for p in &mut f.params {
1059                p.ts_type = resolve_aliases(&p.ts_type, &types);
1060            }
1061            f.returns = resolve_aliases(&f.returns, &types);
1062            substitute_constraints(&mut f, &types);
1063            let kept = keep_reason(&opts.keep, &f.name);
1064            match kept.or_else(|| js_only_reason(&f, &types)) {
1065                Some(reason) => js_only.push(JsOnly {
1066                    name: f.name,
1067                    file: f.file,
1068                    line: f.line,
1069                    reason,
1070                }),
1071                None => exports.push(f),
1072            }
1073        }
1074    }
1075    let mut defined: Vec<(&str, String)> = exports
1076        .iter()
1077        .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1078        .chain(
1079            classes
1080                .iter()
1081                .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1082        )
1083        .chain(
1084            js_only
1085                .iter()
1086                .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1087        )
1088        .collect();
1089    defined.sort();
1090    if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1091        bail!(
1092            "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1093             itself, so one would silently replace the other. Bridge the module you want on its \
1094             own (`rust-anything bridge <root> <that file>`), or rename one of them",
1095            pair[0].0,
1096            unit.id,
1097            pair[0].1,
1098            pair[1].1
1099        );
1100    }
1101    if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1102        bail!(
1103            "every export of `{}` must stay in {}: {}",
1104            unit.id,
1105            lang.name(),
1106            js_only
1107                .iter()
1108                .map(|j| format!("{} ({})", j.name, j.reason))
1109                .collect::<Vec<_>>()
1110                .join(", ")
1111        );
1112    }
1113    if exports.is_empty() && classes.is_empty() {
1114        bail!(
1115            "unit `{}` exports no functions; bridge a unit with an exported function API",
1116            unit.id
1117        );
1118    }
1119
1120    let stem = unit
1121        .id
1122        .trim_end_matches('/')
1123        .rsplit('/')
1124        .next()
1125        .unwrap_or("unit")
1126        .split('.')
1127        .next()
1128        .unwrap_or("unit");
1129    let crate_name = opts.name.clone().unwrap_or_else(|| {
1130        let clean: String = stem
1131            .chars()
1132            .map(|c| {
1133                if c.is_ascii_alphanumeric() {
1134                    c.to_ascii_lowercase()
1135                } else {
1136                    '-'
1137                }
1138            })
1139            .collect();
1140        format!("{}-rs", clean.trim_matches('-'))
1141    });
1142    let crate_dir = opts
1143        .out
1144        .clone()
1145        .unwrap_or_else(|| root.join("rust").join(&crate_name));
1146    if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1147        bail!(
1148            "{} already exists and is not empty; rust-anything never overwrites a port in progress",
1149            crate_dir.display()
1150        );
1151    }
1152
1153    // UTF-16 helpers matter for JS strings only; Python indexes code points, like `chars()`.
1154    let utf16 =
1155        lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1156    let manifest = Manifest {
1157        schema: SCHEMA.into(),
1158        root: root.clone(),
1159        root_written: None,
1160        unit: unit.id.clone(),
1161        language: lang,
1162        kind,
1163        crate_name: crate_name.clone(),
1164        exports: exports.clone(),
1165        classes: classes.clone(),
1166        js_only: js_only.clone(),
1167        batches: parse_batches(&opts.batch)?,
1168        float_tolerance: None,
1169    };
1170    if kind == Kind::CAbi {
1171        return bridge_c(&manifest, &crate_dir, &js_only);
1172    }
1173    if kind == Kind::Ffi {
1174        return bridge_ffi(&manifest, &crate_dir, &js_only);
1175    }
1176    let port = codegen::port_rs(&manifest);
1177    let fns = codegen::parse_port(&port);
1178    let modules = codegen::Modules {
1179        utf16,
1180        js: needs_js(&fns),
1181    };
1182    let mut files: Vec<(String, String)> = vec![
1183        (
1184            "Cargo.toml".into(),
1185            with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1186        ),
1187        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1188        ("src/port.rs".into(), port),
1189        loader_file(&manifest, &fns),
1190        (
1191            ".gitignore".into(),
1192            "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1193        ),
1194        ("README.md".into(), readme(&manifest)),
1195        (
1196            MANIFEST.into(),
1197            serde_json::to_string_pretty(&manifest)? + "\n",
1198        ),
1199    ];
1200    match kind {
1201        Kind::Napi => files.push((
1202            "build.rs".into(),
1203            "fn main() {\n    napi_build::setup();\n}\n".into(),
1204        )),
1205        Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1206        _ => {}
1207    }
1208    if utf16 {
1209        files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1210    }
1211    if modules.js {
1212        files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1213    }
1214    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1215        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1216    }
1217    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1218        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1219        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1220    }
1221    for (path, text) in &files {
1222        let target = crate_dir.join(path);
1223        if let Some(parent) = target.parent() {
1224            std::fs::create_dir_all(parent)?;
1225        }
1226        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1227    }
1228
1229    format_rust(&crate_dir);
1230    let mut notes = vec![format!(
1231        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1232        crate_dir.display()
1233    )];
1234    if utf16 {
1235        notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1236    }
1237    for j in &js_only {
1238        notes.push(format!(
1239            "`{}` stays in {}: {}. The shadow module re-exports the original.",
1240            j.name,
1241            lang.name(),
1242            j.reason
1243        ));
1244    }
1245    if exports.iter().any(codegen::is_async) {
1246        notes.push(
1247            "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1248        );
1249    }
1250    Ok(Outcome {
1251        crate_dir,
1252        kind,
1253        files: files.into_iter().map(|(p, _)| p).collect(),
1254        exports: exports
1255            .iter()
1256            .map(|f| f.name.clone())
1257            .chain(classes.iter().map(|c| format!("class {}", c.name)))
1258            .collect(),
1259        notes,
1260    })
1261}
1262
1263fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1264    for (path, text) in files {
1265        let target = crate_dir.join(path);
1266        if let Some(parent) = target.parent() {
1267            std::fs::create_dir_all(parent)?;
1268        }
1269        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1270    }
1271    Ok(())
1272}
1273
1274/// The generated C-side files: the `extern "C"` layer and its header. C signatures are fixed
1275/// by the original, so they come from the manifest, not from `port.rs`.
1276fn c_bindings(m: &Manifest) -> Vec<(String, String)> {
1277    vec![
1278        ("src/lib.rs".into(), crate::codegen_c::lib_rs(m)),
1279        (
1280            format!("include/{}.h", m.lib_name()),
1281            crate::codegen_c::header(m),
1282        ),
1283    ]
1284}
1285
1286/// The generated layers of a JSON-dispatcher crate: `lib.rs` and the language-side wrapper.
1287fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1288    let mut files = if m.language == crate::lang::Lang::Ruby {
1289        vec![
1290            (
1291                "src/lib.rs".to_string(),
1292                with_allocator(
1293                    m,
1294                    crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1295                ),
1296            ),
1297            (
1298                "src/rbconv.rs".to_string(),
1299                crate::codegen_ruby::RBCONV_RS.to_string(),
1300            ),
1301            ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1302        ]
1303    } else {
1304        let mut lib = crate::codegen_ffi::lib_rs(m, api);
1305        if m.language == crate::lang::Lang::Java {
1306            lib.push_str(&crate::codegen_java::typed_rs(m, api));
1307        }
1308        if m.language == crate::lang::Lang::Go {
1309            lib.push_str(&crate::codegen_go::typed_rs(m, api));
1310            lib.push_str(&crate::codegen_go::wire_rs(m, api));
1311            lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1312        }
1313        if m.language == crate::lang::Lang::Java {
1314            lib.push_str(&crate::codegen_java::wire_rs(m, api));
1315            lib.push_str(
1316                &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1317            );
1318        }
1319        if matches!(m.language, crate::lang::Lang::Go | crate::lang::Lang::Java) {
1320            lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1321        }
1322        let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1323        if matches!(m.language, crate::lang::Lang::Go | crate::lang::Lang::Java) {
1324            files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1325        }
1326        files
1327    };
1328    match m.language {
1329        crate::lang::Lang::Go => {
1330            // The wrapper package takes its name and types from the original sources: without
1331            // them it would be written under a wrong name beside the old one.
1332            if crate::codegen_go::unit_sources(m).is_empty() {
1333                bail!(
1334                    "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1335                    m.unit,
1336                    m.root.display()
1337                );
1338            }
1339            files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1340            files.push((
1341                format!("go/{}.go", crate::codegen_go::package_name(m)),
1342                crate::codegen_go::wrapper(m, api),
1343            ));
1344        }
1345        crate::lang::Lang::Ruby => {
1346            files.push((
1347                crate::harness_ruby::wrapper_path(m),
1348                crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1349            ));
1350        }
1351        crate::lang::Lang::Java => {
1352            files.extend(crate::codegen_java::wrappers(m, api));
1353            files.extend(
1354                crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1355            );
1356            files.push((
1357                format!(
1358                    "java/rustanything/{}.java",
1359                    crate::codegen_ffi::java_native_class(m)
1360                ),
1361                crate::codegen_java::native_class(m, api),
1362            ));
1363            files.push((
1364                "java/rustanything/RustAnythingJson.java".into(),
1365                crate::codegen_java::JSON_JAVA.into(),
1366            ));
1367            files.push((
1368                "java/rustanything/RustAnythingWire.java".into(),
1369                crate::codegen_java::WIRE_JAVA.into(),
1370            ));
1371            files.push((
1372                "java/rustanything/RustAnythingError.java".into(),
1373                crate::codegen_java::ERROR_JAVA.into(),
1374            ));
1375        }
1376        other => bail!("no wrapper generator for {}", other.name()),
1377    }
1378    Ok(files)
1379}
1380
1381fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1382    let port = codegen::port_rs(manifest);
1383    let api = codegen::parse_port(&port);
1384    let mut files = vec![
1385        (
1386            "Cargo.toml".to_string(),
1387            with_rayon(
1388                manifest,
1389                if manifest.language == crate::lang::Lang::Ruby {
1390                    crate::codegen_ruby::cargo_toml(manifest)
1391                } else {
1392                    crate::codegen_ffi::cargo_toml(manifest)
1393                },
1394            )?,
1395        ),
1396        ("src/port.rs".into(), port),
1397        (
1398            ".gitignore".into(),
1399            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1400        ),
1401        ("README.md".into(), readme(manifest)),
1402        (
1403            MANIFEST.into(),
1404            serde_json::to_string_pretty(manifest)? + "\n",
1405        ),
1406    ];
1407    files.extend(ffi_bindings(manifest, &api)?);
1408    write_files(crate_dir, &files)?;
1409    format_rust(crate_dir);
1410    format_wrapper(crate_dir);
1411    let mut notes = vec![format!(
1412        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1413        crate_dir.display()
1414    )];
1415    for j in kept {
1416        notes.push(format!(
1417            "`{}` stays in {}: {}.",
1418            j.name,
1419            manifest.language.name(),
1420            j.reason
1421        ));
1422    }
1423    Ok(Outcome {
1424        crate_dir: crate_dir.to_path_buf(),
1425        kind: Kind::Ffi,
1426        files: files.into_iter().map(|(p, _)| p).collect(),
1427        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1428        notes,
1429    })
1430}
1431
1432fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1433    let mut files = vec![
1434        (
1435            "Cargo.toml".to_string(),
1436            crate::codegen_c::cargo_toml(manifest),
1437        ),
1438        ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1439        (
1440            ".gitignore".into(),
1441            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1442        ),
1443        ("README.md".into(), readme(manifest)),
1444        (
1445            MANIFEST.into(),
1446            serde_json::to_string_pretty(manifest)? + "\n",
1447        ),
1448    ];
1449    files.extend(c_bindings(manifest));
1450    write_files(crate_dir, &files)?;
1451    format_rust(crate_dir);
1452    let mut notes = vec![
1453        format!(
1454            "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1455            crate_dir.display()
1456        ),
1457        format!(
1458            "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1459            manifest.lib_name(),
1460            manifest.lib_name()
1461        ),
1462    ];
1463    for j in kept {
1464        notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1465    }
1466    Ok(Outcome {
1467        crate_dir: crate_dir.to_path_buf(),
1468        kind: Kind::CAbi,
1469        files: files.into_iter().map(|(p, _)| p).collect(),
1470        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1471        notes,
1472    })
1473}
1474
1475fn readme(m: &Manifest) -> String {
1476    let functions: String = m
1477        .exports
1478        .iter()
1479        .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1480        .collect();
1481    format!(
1482        "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1483         ## Loop\n\n```sh\nrust-anything record .   # record what the TS code does\nrust-anything build .    # build the {kind} module\n\
1484         rust-anything diff .     # run the recorded cases against Rust\nrust-anything shadow .   # run both in the app, log mismatches\n\
1485         rust-anything gate .     # fmt, clippy, tests, unsafe, API, diff\n```\n",
1486        name = m.crate_name,
1487        unit = m.unit,
1488        kind = match m.kind {
1489            Kind::Napi => "napi-rs",
1490            Kind::Wasm => "wasm-bindgen",
1491            Kind::Pyo3 => "PyO3",
1492            Kind::CAbi => "the C ABI",
1493            Kind::Ffi => "a JSON dispatcher",
1494        },
1495    )
1496}
1497
1498const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1499//!
1500//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1501//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1502
1503#![forbid(unsafe_code)]
1504
1505/// The UTF-16 code units of `s`, as JS sees the string.
1506pub fn units(s: &str) -> Vec<u16> {
1507    s.encode_utf16().collect()
1508}
1509
1510/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1511pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1512    let end = end.min(units.len());
1513    let start = start.min(end);
1514    String::from_utf16_lossy(&units[start..end])
1515}
1516
1517/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1518pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1519    let from = from.min(haystack.len());
1520    if needle.is_empty() {
1521        return Some(from);
1522    }
1523    haystack[from..]
1524        .windows(needle.len())
1525        .position(|w| w == needle)
1526        .map(|i| i + from)
1527}
1528
1529/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1530pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1531    if needle.is_empty() {
1532        return Some(haystack.len());
1533    }
1534    haystack.windows(needle.len()).rposition(|w| w == needle)
1535}
1536
1537/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1538pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1539    let mut seen = 0;
1540    for (byte, c) in s.char_indices() {
1541        if seen >= utf16_offset {
1542            return byte;
1543        }
1544        seen += c.len_utf16();
1545    }
1546    s.len()
1547}
1548
1549/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1550pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1551    s[..byte_offset.min(s.len())].encode_utf16().count()
1552}
1553
1554#[cfg(test)]
1555mod tests {
1556    use super::*;
1557
1558    #[test]
1559    fn matches_js_indexing() {
1560        let s = units("a👍b");
1561        assert_eq!(s.len(), 4);
1562        assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1563        assert_eq!(last_index_of(&s, &units("a")), Some(0));
1564        assert_eq!(slice(&s, 3, 4), "b");
1565        assert_eq!(byte_offset("a👍b", 3), 5);
1566        assert_eq!(utf16_offset("a👍b", 5), 3);
1567    }
1568}
1569"#;
1570
1571#[cfg(test)]
1572mod tests {
1573    use super::*;
1574
1575    #[test]
1576    fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1577        let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1578        let _ = std::fs::remove_dir_all(&base);
1579        let crate_dir = base.join("repo/rust/x-rs");
1580        std::fs::create_dir_all(&crate_dir).unwrap();
1581        std::fs::write(
1582            crate_dir.join(MANIFEST),
1583            r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1584        )
1585        .unwrap();
1586        let m = Manifest::load(&crate_dir).unwrap();
1587        assert_eq!(m.root, base.join("repo").canonical().unwrap());
1588        assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1589        // Written back, the file keeps the relative root.
1590        let mut back = m.clone();
1591        if let Some(w) = back.root_written.clone() {
1592            back.root = w;
1593        }
1594        assert!(
1595            serde_json::to_string(&back)
1596                .unwrap()
1597                .contains(r#""root":"../..""#)
1598        );
1599        std::fs::remove_dir_all(&base).unwrap();
1600    }
1601
1602    #[test]
1603    fn maps_ts_types() {
1604        assert_eq!(RType::from_ts("string").rust(), "String");
1605        assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1606        assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1607        assert_eq!(
1608            RType::from_ts("string | undefined").rust(),
1609            "Option<String>"
1610        );
1611        assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1612        assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1613        assert_eq!(
1614            RType::from_ts("Map<string, number>").rust(),
1615            "serde_json::Value"
1616        );
1617        assert_eq!(
1618            RType::from_ts("string | number").rust(),
1619            "serde_json::Value"
1620        );
1621        assert_eq!(
1622            RType::from_ts("Record<string, string | number>").rust(),
1623            "serde_json::Value"
1624        );
1625        assert_eq!(
1626            RType::from_ts("(string | undefined)").rust(),
1627            "Option<String>"
1628        );
1629        assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
1630    }
1631
1632    #[test]
1633    fn keeps_unbridgeable_exports_in_js() {
1634        let source = "export interface LineIndex {\n  readonly lineCount: number\n  position(offset: number): number\n}\n\
1635            export interface Range { start: number, end: number }\n\
1636            export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
1637            export function globToRegExp(glob: string): RegExp { return /x/ }\n\
1638            export function createLineIndex(text: string): LineIndex { return null! }\n\
1639            export function* walk(tree: object) {}\n\
1640            export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
1641            export function contains(range: Range, offset: number): boolean { return true }\n";
1642        let types = local_types("a.ts", source);
1643        let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
1644            .iter()
1645            .map(|f| (f.name.clone(), js_only_reason(f, &types)))
1646            .collect();
1647        let js_only: Vec<&str> = reasons
1648            .iter()
1649            .filter(|(_, r)| r.is_some())
1650            .map(|(n, _)| n.as_str())
1651            .collect();
1652        assert_eq!(
1653            js_only,
1654            [
1655                "keyMatcher",
1656                "globToRegExp",
1657                "createLineIndex",
1658                "walk",
1659                "sortTree"
1660            ]
1661        );
1662    }
1663
1664    #[test]
1665    fn resolves_simple_aliases() {
1666        let types = local_types(
1667            "m.ts",
1668            "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
1669        );
1670        assert_eq!(
1671            resolve_aliases("readonly KeyString[]", &types),
1672            "readonly string[]"
1673        );
1674        assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
1675        assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
1676    }
1677
1678    #[test]
1679    fn substitutes_simple_constraints() {
1680        let found = exported_functions(
1681            "a.ts",
1682            "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
1683             export function pick<T>(x: T): T { return x }\n\
1684             export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
1685        );
1686        let mut fns = found;
1687        for f in &mut fns {
1688            substitute_constraints(f, &[]);
1689        }
1690        assert_eq!(fns[0].params[0].ts_type, "(string)");
1691        assert!(fns[0].type_params.is_empty());
1692        assert_eq!(fns[1].type_params, ["T"]);
1693        assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
1694        assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
1695    }
1696
1697    #[test]
1698    fn makes_rust_names() {
1699        assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
1700        assert_eq!(snake_case("type"), "r#type");
1701        assert_eq!(snake_case("toURL"), "to_url");
1702        assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
1703    }
1704}