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.exports.iter().find(|e| snake_case(&e.name) == rust) {
791            f.js_name = e.name.clone();
792        }
793    }
794}
795
796/// What `refresh` rewrote.
797#[derive(Debug, Serialize)]
798pub struct Refreshed {
799    pub functions: Vec<String>,
800    pub files: Vec<String>,
801}
802
803/// Regenerates the binding layer (`lib.rs`, `index.cjs`, `js.rs`) from the signatures in
804/// `port.rs`, and adds the dependencies they need to Cargo.toml. Never touches `port.rs`.
805pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
806    let manifest = Manifest::load(crate_dir)?;
807    if manifest.kind == Kind::CAbi {
808        let mut files = c_bindings(&manifest);
809        let cargo =
810            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
811        files.push((
812            "Cargo.toml".into(),
813            with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
814        ));
815        write_files(crate_dir, &files)?;
816        format_rust(crate_dir);
817        return Ok(Refreshed {
818            functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
819            files: files.into_iter().map(|(p, _)| p).collect(),
820        });
821    }
822    if manifest.kind == Kind::Ffi {
823        let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
824            .context("reading src/port.rs")?;
825        let mut api = codegen::parse_port(&port);
826        match_export_names(&manifest, &mut api);
827        let mut files = ffi_bindings(&manifest, &api)?;
828        let cargo =
829            std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
830        let template = if manifest.language == crate::lang::Lang::Ruby {
831            crate::codegen_ruby::cargo_toml(&manifest)
832        } else {
833            crate::codegen_ffi::cargo_toml(&manifest)
834        };
835        let cargo = with_template_deps(&cargo, &template)?;
836        files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
837        write_files(crate_dir, &files)?;
838        format_rust(crate_dir);
839        format_wrapper(crate_dir);
840        return Ok(Refreshed {
841            functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
842            files: files.into_iter().map(|(p, _)| p).collect(),
843        });
844    }
845    let port =
846        std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
847    let mut fns = codegen::parse_port(&port);
848    match_export_names(&manifest, &mut fns);
849    if fns.functions.is_empty() && fns.classes.is_empty() {
850        bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
851    }
852    let modules = codegen::Modules {
853        utf16: crate_dir.join("src/utf16.rs").exists(),
854        js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
855    };
856    let mut files: Vec<(String, String)> = vec![
857        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
858        loader_file(&manifest, &fns),
859    ];
860    if modules.js {
861        files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
862    }
863    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
864        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
865    }
866    let extension = manifest.kind == Kind::Pyo3
867        || (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
868    if extension && !crate_dir.join("build.rs").exists() {
869        files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
870    }
871    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
872        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
873        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
874    }
875    let cargo_path = crate_dir.join("Cargo.toml");
876    let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
877    let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns).map_err(anyhow::Error::msg)?;
878    let cargo = with_rayon(&manifest, cargo)?;
879    files.push(("Cargo.toml".into(), cargo));
880    for (path, text) in &files {
881        let target = crate_dir.join(path);
882        if let Some(parent) = target.parent() {
883            std::fs::create_dir_all(parent)?;
884        }
885        std::fs::write(&target, text).with_context(|| format!("writing {path}"))?;
886    }
887    format_rust(crate_dir);
888    Ok(Refreshed {
889        functions: fns
890            .functions
891            .iter()
892            .map(|f| f.js_name.clone())
893            .chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
894            .collect(),
895        files: files.into_iter().map(|(p, _)| p).collect(),
896    })
897}
898
899/// `build.rs` for Python and Ruby extensions: on macOS the library (and its test binary) links
900/// against symbols the interpreter provides only at load time.
901pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
902    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
903        println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
904    }
905}
906"#;
907
908pub fn bridge(opts: &Options) -> Result<Outcome> {
909    let root = opts
910        .root
911        .canonical()
912        .with_context(|| format!("resolving {}", opts.root.display()))?;
913    let lang = opts
914        .lang
915        .unwrap_or_else(|| crate::lang::Lang::detect(&root));
916    let report = analyze::analyze_lang(&root, lang)?;
917    let wanted = opts.unit.trim_start_matches("./");
918    let whole = report
919        .units
920        .iter()
921        .find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'));
922    let single = || {
923        report
924            .units
925            .iter()
926            .find(|u| u.files.iter().any(|f| f == wanted))
927            .map(|u| {
928                let mut one = u.clone();
929                one.id = wanted.to_string();
930                one.files = vec![wanted.to_string()];
931                one
932            })
933    };
934    let unit = match whole.cloned().or_else(single) {
935        Some(unit) => unit,
936        None => bail!(
937            "no unit or source file `{wanted}`; `rust-anything analyze` lists unit ids, and any \
938             source file inside a unit can be bridged on its own"
939        ),
940    };
941    let unit = &unit;
942    if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
943        bail!(
944            "unit `{}` is {:?}: {}. Pass --force to bridge it anyway.",
945            unit.id,
946            unit.status,
947            unit.notes.first().map_or("", String::as_str)
948        );
949    }
950    if unit.bridge == Bridge::PhpFfi {
951        bail!(
952            "bridging PHP units into Rust comes next (PHP FFI over a C ABI); for now a PHP app can \
953             be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
954             door (`app front-door`) that hands everything to the original"
955        );
956    }
957    if unit.bridge == Bridge::DotnetFfi {
958        bail!(
959            "bridging C# units into Rust comes next (P/Invoke over a C ABI); for now a C# app can \
960             be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
961             door (`app front-door`) that hands everything to the original"
962        );
963    }
964    let kind = opts.kind.unwrap_or(match unit.bridge {
965        Bridge::WasmBindgen => Kind::Wasm,
966        Bridge::Pyo3 => Kind::Pyo3,
967        Bridge::CAbi => Kind::CAbi,
968        Bridge::Cgo | Bridge::Fiddle | Bridge::Jni => Kind::Ffi,
969        _ => Kind::Napi,
970    });
971
972    let mut exports = Vec::new();
973    let mut classes = Vec::new();
974    let mut js_only = Vec::new();
975    for file in &unit.files {
976        if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
977            continue;
978        }
979        let text =
980            std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
981        if lang != crate::lang::Lang::Ts {
982            let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
983            for f in functions {
984                match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
985                    Some(reason) => js_only.push(JsOnly {
986                        name: f.name,
987                        file: f.file,
988                        line: f.line,
989                        reason,
990                    }),
991                    None => exports.push(f),
992                }
993            }
994            for class in foreign_classes {
995                let method_reason = class
996                    .methods
997                    .iter()
998                    .find_map(|m| js_only_reason(m, &[]).map(|r| format!("`{}`: {r}", m.name)));
999                match keep_reason(&opts.keep, &class.name)
1000                    .or_else(|| class.blocker.clone())
1001                    .or(method_reason)
1002                {
1003                    Some(reason) => js_only.push(JsOnly {
1004                        name: class.name,
1005                        file: class.file,
1006                        line: class.line,
1007                        reason: format!("class: {reason}"),
1008                    }),
1009                    None => classes.push(class),
1010                }
1011            }
1012            continue;
1013        }
1014        let types = types_in_scope(&root, file, &text);
1015        for mut class in exported_classes(file, &text) {
1016            let kept = keep_reason(&opts.keep, &class.name);
1017            let constructor = ExportedFn {
1018                name: format!("{} constructor", class.name),
1019                file: class.file.clone(),
1020                line: class.line,
1021                params: class.constructor.clone(),
1022                returns: "void".into(),
1023                is_async: false,
1024                is_generator: false,
1025                type_params: Vec::new(),
1026                uses_instanceof: false,
1027                ..Default::default()
1028            };
1029            let method_reason = std::iter::once(&constructor)
1030                .chain(&class.methods)
1031                .find_map(|m| js_only_reason(m, &types).map(|r| format!("`{}`: {r}", m.name)));
1032            match kept.or_else(|| class.blocker.clone()).or(method_reason) {
1033                Some(reason) => js_only.push(JsOnly {
1034                    name: class.name,
1035                    file: class.file,
1036                    line: class.line,
1037                    reason: format!("class: {reason}"),
1038                }),
1039                None => {
1040                    for p in &mut class.constructor {
1041                        p.ts_type = resolve_aliases(&p.ts_type, &types);
1042                    }
1043                    for m in &mut class.methods {
1044                        for p in &mut m.params {
1045                            p.ts_type = resolve_aliases(&p.ts_type, &types);
1046                        }
1047                        m.returns = resolve_aliases(&m.returns, &types);
1048                    }
1049                    classes.push(class);
1050                }
1051            }
1052        }
1053        for mut f in exported_functions(file, &text) {
1054            for p in &mut f.params {
1055                p.ts_type = resolve_aliases(&p.ts_type, &types);
1056            }
1057            f.returns = resolve_aliases(&f.returns, &types);
1058            substitute_constraints(&mut f, &types);
1059            let kept = keep_reason(&opts.keep, &f.name);
1060            match kept.or_else(|| js_only_reason(&f, &types)) {
1061                Some(reason) => js_only.push(JsOnly {
1062                    name: f.name,
1063                    file: f.file,
1064                    line: f.line,
1065                    reason,
1066                }),
1067                None => exports.push(f),
1068            }
1069        }
1070    }
1071    let mut defined: Vec<(&str, String)> = exports
1072        .iter()
1073        .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1074        .chain(
1075            classes
1076                .iter()
1077                .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1078        )
1079        .chain(
1080            js_only
1081                .iter()
1082                .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1083        )
1084        .collect();
1085    defined.sort();
1086    if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1087        bail!(
1088            "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1089             itself, so one would silently replace the other. Bridge the module you want on its \
1090             own (`rust-anything bridge <root> <that file>`), or rename one of them",
1091            pair[0].0,
1092            unit.id,
1093            pair[0].1,
1094            pair[1].1
1095        );
1096    }
1097    if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1098        bail!(
1099            "every export of `{}` must stay in {}: {}",
1100            unit.id,
1101            lang.name(),
1102            js_only
1103                .iter()
1104                .map(|j| format!("{} ({})", j.name, j.reason))
1105                .collect::<Vec<_>>()
1106                .join(", ")
1107        );
1108    }
1109    if exports.is_empty() && classes.is_empty() {
1110        bail!(
1111            "unit `{}` exports no functions; bridge a unit with an exported function API",
1112            unit.id
1113        );
1114    }
1115
1116    let stem = unit
1117        .id
1118        .trim_end_matches('/')
1119        .rsplit('/')
1120        .next()
1121        .unwrap_or("unit")
1122        .split('.')
1123        .next()
1124        .unwrap_or("unit");
1125    let crate_name = opts.name.clone().unwrap_or_else(|| {
1126        let clean: String = stem
1127            .chars()
1128            .map(|c| {
1129                if c.is_ascii_alphanumeric() {
1130                    c.to_ascii_lowercase()
1131                } else {
1132                    '-'
1133                }
1134            })
1135            .collect();
1136        format!("{}-rs", clean.trim_matches('-'))
1137    });
1138    let crate_dir = opts
1139        .out
1140        .clone()
1141        .unwrap_or_else(|| root.join("rust").join(&crate_name));
1142    if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1143        bail!(
1144            "{} already exists and is not empty; rust-anything never overwrites a port in progress",
1145            crate_dir.display()
1146        );
1147    }
1148
1149    // UTF-16 helpers matter for JS strings only; Python indexes code points, like `chars()`.
1150    let utf16 =
1151        lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1152    let manifest = Manifest {
1153        schema: SCHEMA.into(),
1154        root: root.clone(),
1155        root_written: None,
1156        unit: unit.id.clone(),
1157        language: lang,
1158        kind,
1159        crate_name: crate_name.clone(),
1160        exports: exports.clone(),
1161        classes: classes.clone(),
1162        js_only: js_only.clone(),
1163        batches: parse_batches(&opts.batch)?,
1164        float_tolerance: None,
1165    };
1166    if kind == Kind::CAbi {
1167        return bridge_c(&manifest, &crate_dir, &js_only);
1168    }
1169    if kind == Kind::Ffi {
1170        return bridge_ffi(&manifest, &crate_dir, &js_only);
1171    }
1172    let port = codegen::port_rs(&manifest);
1173    let fns = codegen::parse_port(&port);
1174    let modules = codegen::Modules {
1175        utf16,
1176        js: needs_js(&fns),
1177    };
1178    let mut files: Vec<(String, String)> = vec![
1179        (
1180            "Cargo.toml".into(),
1181            with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1182        ),
1183        ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1184        ("src/port.rs".into(), port),
1185        loader_file(&manifest, &fns),
1186        (
1187            ".gitignore".into(),
1188            "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1189        ),
1190        ("README.md".into(), readme(&manifest)),
1191        (
1192            MANIFEST.into(),
1193            serde_json::to_string_pretty(&manifest)? + "\n",
1194        ),
1195    ];
1196    match kind {
1197        Kind::Napi => files.push((
1198            "build.rs".into(),
1199            "fn main() {\n    napi_build::setup();\n}\n".into(),
1200        )),
1201        Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1202        _ => {}
1203    }
1204    if utf16 {
1205        files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1206    }
1207    if modules.js {
1208        files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1209    }
1210    if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1211        files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1212    }
1213    if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1214        files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1215        files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1216    }
1217    for (path, text) in &files {
1218        let target = crate_dir.join(path);
1219        if let Some(parent) = target.parent() {
1220            std::fs::create_dir_all(parent)?;
1221        }
1222        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1223    }
1224
1225    format_rust(&crate_dir);
1226    let mut notes = vec![format!(
1227        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1228        crate_dir.display()
1229    )];
1230    if utf16 {
1231        notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1232    }
1233    for j in &js_only {
1234        notes.push(format!(
1235            "`{}` stays in {}: {}. The shadow module re-exports the original.",
1236            j.name,
1237            lang.name(),
1238            j.reason
1239        ));
1240    }
1241    if exports.iter().any(codegen::is_async) {
1242        notes.push(
1243            "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1244        );
1245    }
1246    Ok(Outcome {
1247        crate_dir,
1248        kind,
1249        files: files.into_iter().map(|(p, _)| p).collect(),
1250        exports: exports
1251            .iter()
1252            .map(|f| f.name.clone())
1253            .chain(classes.iter().map(|c| format!("class {}", c.name)))
1254            .collect(),
1255        notes,
1256    })
1257}
1258
1259fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1260    for (path, text) in files {
1261        let target = crate_dir.join(path);
1262        if let Some(parent) = target.parent() {
1263            std::fs::create_dir_all(parent)?;
1264        }
1265        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1266    }
1267    Ok(())
1268}
1269
1270/// The generated C-side files: the `extern "C"` layer and its header. C signatures are fixed
1271/// by the original, so they come from the manifest, not from `port.rs`.
1272fn c_bindings(m: &Manifest) -> Vec<(String, String)> {
1273    vec![
1274        ("src/lib.rs".into(), crate::codegen_c::lib_rs(m)),
1275        (
1276            format!("include/{}.h", m.lib_name()),
1277            crate::codegen_c::header(m),
1278        ),
1279    ]
1280}
1281
1282/// The generated layers of a JSON-dispatcher crate: `lib.rs` and the language-side wrapper.
1283fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1284    let mut files = if m.language == crate::lang::Lang::Ruby {
1285        vec![
1286            (
1287                "src/lib.rs".to_string(),
1288                with_allocator(
1289                    m,
1290                    crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1291                ),
1292            ),
1293            (
1294                "src/rbconv.rs".to_string(),
1295                crate::codegen_ruby::RBCONV_RS.to_string(),
1296            ),
1297            ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1298        ]
1299    } else {
1300        let mut lib = crate::codegen_ffi::lib_rs(m, api);
1301        if m.language == crate::lang::Lang::Java {
1302            lib.push_str(&crate::codegen_java::typed_rs(m, api));
1303        }
1304        if m.language == crate::lang::Lang::Go {
1305            lib.push_str(&crate::codegen_go::typed_rs(m, api));
1306            lib.push_str(&crate::codegen_go::wire_rs(m, api));
1307            lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1308        }
1309        if m.language == crate::lang::Lang::Java {
1310            lib.push_str(&crate::codegen_java::wire_rs(m, api));
1311            lib.push_str(
1312                &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1313            );
1314        }
1315        if matches!(m.language, crate::lang::Lang::Go | crate::lang::Lang::Java) {
1316            lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1317        }
1318        let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1319        if matches!(m.language, crate::lang::Lang::Go | crate::lang::Lang::Java) {
1320            files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1321        }
1322        files
1323    };
1324    match m.language {
1325        crate::lang::Lang::Go => {
1326            // The wrapper package takes its name and types from the original sources: without
1327            // them it would be written under a wrong name beside the old one.
1328            if crate::codegen_go::unit_sources(m).is_empty() {
1329                bail!(
1330                    "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1331                    m.unit,
1332                    m.root.display()
1333                );
1334            }
1335            files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1336            files.push((
1337                format!("go/{}.go", crate::codegen_go::package_name(m)),
1338                crate::codegen_go::wrapper(m, api),
1339            ));
1340        }
1341        crate::lang::Lang::Ruby => {
1342            files.push((
1343                crate::harness_ruby::wrapper_path(m),
1344                crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1345            ));
1346        }
1347        crate::lang::Lang::Java => {
1348            files.extend(crate::codegen_java::wrappers(m, api));
1349            files.extend(
1350                crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1351            );
1352            files.push((
1353                format!(
1354                    "java/rustanything/{}.java",
1355                    crate::codegen_ffi::java_native_class(m)
1356                ),
1357                crate::codegen_java::native_class(m, api),
1358            ));
1359            files.push((
1360                "java/rustanything/RustAnythingJson.java".into(),
1361                crate::codegen_java::JSON_JAVA.into(),
1362            ));
1363            files.push((
1364                "java/rustanything/RustAnythingWire.java".into(),
1365                crate::codegen_java::WIRE_JAVA.into(),
1366            ));
1367            files.push((
1368                "java/rustanything/RustAnythingError.java".into(),
1369                crate::codegen_java::ERROR_JAVA.into(),
1370            ));
1371        }
1372        other => bail!("no wrapper generator for {}", other.name()),
1373    }
1374    Ok(files)
1375}
1376
1377fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1378    let port = codegen::port_rs(manifest);
1379    let api = codegen::parse_port(&port);
1380    let mut files = vec![
1381        (
1382            "Cargo.toml".to_string(),
1383            with_rayon(
1384                manifest,
1385                if manifest.language == crate::lang::Lang::Ruby {
1386                    crate::codegen_ruby::cargo_toml(manifest)
1387                } else {
1388                    crate::codegen_ffi::cargo_toml(manifest)
1389                },
1390            )?,
1391        ),
1392        ("src/port.rs".into(), port),
1393        (
1394            ".gitignore".into(),
1395            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1396        ),
1397        ("README.md".into(), readme(manifest)),
1398        (
1399            MANIFEST.into(),
1400            serde_json::to_string_pretty(manifest)? + "\n",
1401        ),
1402    ];
1403    files.extend(ffi_bindings(manifest, &api)?);
1404    write_files(crate_dir, &files)?;
1405    format_rust(crate_dir);
1406    format_wrapper(crate_dir);
1407    let mut notes = vec![format!(
1408        "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1409        crate_dir.display()
1410    )];
1411    for j in kept {
1412        notes.push(format!(
1413            "`{}` stays in {}: {}.",
1414            j.name,
1415            manifest.language.name(),
1416            j.reason
1417        ));
1418    }
1419    Ok(Outcome {
1420        crate_dir: crate_dir.to_path_buf(),
1421        kind: Kind::Ffi,
1422        files: files.into_iter().map(|(p, _)| p).collect(),
1423        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1424        notes,
1425    })
1426}
1427
1428fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1429    let mut files = vec![
1430        (
1431            "Cargo.toml".to_string(),
1432            crate::codegen_c::cargo_toml(manifest),
1433        ),
1434        ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1435        (
1436            ".gitignore".into(),
1437            "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1438        ),
1439        ("README.md".into(), readme(manifest)),
1440        (
1441            MANIFEST.into(),
1442            serde_json::to_string_pretty(manifest)? + "\n",
1443        ),
1444    ];
1445    files.extend(c_bindings(manifest));
1446    write_files(crate_dir, &files)?;
1447    format_rust(crate_dir);
1448    let mut notes = vec![
1449        format!(
1450            "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1451            crate_dir.display()
1452        ),
1453        format!(
1454            "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1455            manifest.lib_name(),
1456            manifest.lib_name()
1457        ),
1458    ];
1459    for j in kept {
1460        notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1461    }
1462    Ok(Outcome {
1463        crate_dir: crate_dir.to_path_buf(),
1464        kind: Kind::CAbi,
1465        files: files.into_iter().map(|(p, _)| p).collect(),
1466        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1467        notes,
1468    })
1469}
1470
1471fn readme(m: &Manifest) -> String {
1472    let functions: String = m
1473        .exports
1474        .iter()
1475        .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1476        .collect();
1477    format!(
1478        "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1479         ## Loop\n\n```sh\nrust-anything record .   # record what the TS code does\nrust-anything build .    # build the {kind} module\n\
1480         rust-anything diff .     # run the recorded cases against Rust\nrust-anything shadow .   # run both in the app, log mismatches\n\
1481         rust-anything gate .     # fmt, clippy, tests, unsafe, API, diff\n```\n",
1482        name = m.crate_name,
1483        unit = m.unit,
1484        kind = match m.kind {
1485            Kind::Napi => "napi-rs",
1486            Kind::Wasm => "wasm-bindgen",
1487            Kind::Pyo3 => "PyO3",
1488            Kind::CAbi => "the C ABI",
1489            Kind::Ffi => "a JSON dispatcher",
1490        },
1491    )
1492}
1493
1494const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1495//!
1496//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1497//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1498
1499#![forbid(unsafe_code)]
1500
1501/// The UTF-16 code units of `s`, as JS sees the string.
1502pub fn units(s: &str) -> Vec<u16> {
1503    s.encode_utf16().collect()
1504}
1505
1506/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1507pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1508    let end = end.min(units.len());
1509    let start = start.min(end);
1510    String::from_utf16_lossy(&units[start..end])
1511}
1512
1513/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1514pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1515    let from = from.min(haystack.len());
1516    if needle.is_empty() {
1517        return Some(from);
1518    }
1519    haystack[from..]
1520        .windows(needle.len())
1521        .position(|w| w == needle)
1522        .map(|i| i + from)
1523}
1524
1525/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1526pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1527    if needle.is_empty() {
1528        return Some(haystack.len());
1529    }
1530    haystack.windows(needle.len()).rposition(|w| w == needle)
1531}
1532
1533/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1534pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1535    let mut seen = 0;
1536    for (byte, c) in s.char_indices() {
1537        if seen >= utf16_offset {
1538            return byte;
1539        }
1540        seen += c.len_utf16();
1541    }
1542    s.len()
1543}
1544
1545/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1546pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1547    s[..byte_offset.min(s.len())].encode_utf16().count()
1548}
1549
1550#[cfg(test)]
1551mod tests {
1552    use super::*;
1553
1554    #[test]
1555    fn matches_js_indexing() {
1556        let s = units("a👍b");
1557        assert_eq!(s.len(), 4);
1558        assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1559        assert_eq!(last_index_of(&s, &units("a")), Some(0));
1560        assert_eq!(slice(&s, 3, 4), "b");
1561        assert_eq!(byte_offset("a👍b", 3), 5);
1562        assert_eq!(utf16_offset("a👍b", 5), 3);
1563    }
1564}
1565"#;
1566
1567#[cfg(test)]
1568mod tests {
1569    use super::*;
1570
1571    #[test]
1572    fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1573        let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1574        let _ = std::fs::remove_dir_all(&base);
1575        let crate_dir = base.join("repo/rust/x-rs");
1576        std::fs::create_dir_all(&crate_dir).unwrap();
1577        std::fs::write(
1578            crate_dir.join(MANIFEST),
1579            r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1580        )
1581        .unwrap();
1582        let m = Manifest::load(&crate_dir).unwrap();
1583        assert_eq!(m.root, base.join("repo").canonicalize().unwrap());
1584        assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1585        // Written back, the file keeps the relative root.
1586        let mut back = m.clone();
1587        if let Some(w) = back.root_written.clone() {
1588            back.root = w;
1589        }
1590        assert!(
1591            serde_json::to_string(&back)
1592                .unwrap()
1593                .contains(r#""root":"../..""#)
1594        );
1595        std::fs::remove_dir_all(&base).unwrap();
1596    }
1597
1598    #[test]
1599    fn maps_ts_types() {
1600        assert_eq!(RType::from_ts("string").rust(), "String");
1601        assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1602        assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1603        assert_eq!(
1604            RType::from_ts("string | undefined").rust(),
1605            "Option<String>"
1606        );
1607        assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1608        assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1609        assert_eq!(
1610            RType::from_ts("Map<string, number>").rust(),
1611            "serde_json::Value"
1612        );
1613        assert_eq!(
1614            RType::from_ts("string | number").rust(),
1615            "serde_json::Value"
1616        );
1617        assert_eq!(
1618            RType::from_ts("Record<string, string | number>").rust(),
1619            "serde_json::Value"
1620        );
1621        assert_eq!(
1622            RType::from_ts("(string | undefined)").rust(),
1623            "Option<String>"
1624        );
1625        assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
1626    }
1627
1628    #[test]
1629    fn keeps_unbridgeable_exports_in_js() {
1630        let source = "export interface LineIndex {\n  readonly lineCount: number\n  position(offset: number): number\n}\n\
1631            export interface Range { start: number, end: number }\n\
1632            export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
1633            export function globToRegExp(glob: string): RegExp { return /x/ }\n\
1634            export function createLineIndex(text: string): LineIndex { return null! }\n\
1635            export function* walk(tree: object) {}\n\
1636            export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
1637            export function contains(range: Range, offset: number): boolean { return true }\n";
1638        let types = local_types("a.ts", source);
1639        let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
1640            .iter()
1641            .map(|f| (f.name.clone(), js_only_reason(f, &types)))
1642            .collect();
1643        let js_only: Vec<&str> = reasons
1644            .iter()
1645            .filter(|(_, r)| r.is_some())
1646            .map(|(n, _)| n.as_str())
1647            .collect();
1648        assert_eq!(
1649            js_only,
1650            [
1651                "keyMatcher",
1652                "globToRegExp",
1653                "createLineIndex",
1654                "walk",
1655                "sortTree"
1656            ]
1657        );
1658    }
1659
1660    #[test]
1661    fn resolves_simple_aliases() {
1662        let types = local_types(
1663            "m.ts",
1664            "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
1665        );
1666        assert_eq!(
1667            resolve_aliases("readonly KeyString[]", &types),
1668            "readonly string[]"
1669        );
1670        assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
1671        assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
1672    }
1673
1674    #[test]
1675    fn substitutes_simple_constraints() {
1676        let found = exported_functions(
1677            "a.ts",
1678            "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
1679             export function pick<T>(x: T): T { return x }\n\
1680             export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
1681        );
1682        let mut fns = found;
1683        for f in &mut fns {
1684            substitute_constraints(f, &[]);
1685        }
1686        assert_eq!(fns[0].params[0].ts_type, "(string)");
1687        assert!(fns[0].type_params.is_empty());
1688        assert_eq!(fns[1].type_params, ["T"]);
1689        assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
1690        assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
1691    }
1692
1693    #[test]
1694    fn makes_rust_names() {
1695        assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
1696        assert_eq!(snake_case("type"), "r#type");
1697        assert_eq!(snake_case("toURL"), "to_url");
1698        assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
1699    }
1700}