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