Skip to main content

rust_anything/
bridge.rs

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