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