Skip to main content

rust_anything/
bridge.rs

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