Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! Step 2: scaffold a Rust crate for one unit, with JS bindings and a manifest the later
//! steps read.
//!
//! The crate splits bindings from logic: `src/lib.rs` holds thin `#[napi]` or
//! `#[wasm_bindgen]` wrappers, `src/port.rs` holds the port in plain Rust with
//! `#![forbid(unsafe_code)]`, so it can be tested without a JS runtime.
use crate::walk::Canonical;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use crate::analyze::{self, Bridge, Status};
use crate::codegen;
use crate::risks::Risk;
use crate::ts::exports::{
ExportedClass, ExportedFn, LocalType, exported_classes, exported_functions, local_types,
};
pub const MANIFEST: &str = "rust-anything.json";
pub const SCHEMA: &str = "rust-anything/bridge@1";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
Napi,
Wasm,
Pyo3,
/// `extern "C"` functions with the original names: a drop-in replacement for C code.
#[serde(rename = "c-abi")]
CAbi,
/// A JSON dispatcher over the port, called from a generated Go, Ruby or Java wrapper.
Ffi,
}
impl Kind {
pub fn label(self) -> &'static str {
match self {
Kind::Napi => "napi-rs",
Kind::Wasm => "wasm-bindgen",
Kind::Pyo3 => "PyO3",
Kind::CAbi => "the C ABI",
Kind::Ffi => "a JSON dispatcher",
}
}
}
/// The global allocator of a crate with batches (`bridge --allocator`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
pub enum Allocator {
/// mimalloc, built from C with `cc`. Wasm crates keep Rust's default allocator.
#[default]
#[serde(rename = "mimalloc")]
#[value(name = "mimalloc")]
Mimalloc,
/// rusty_alloc, a pure-Rust remake of mimalloc: no C compiler, and wasm crates get it too.
#[serde(rename = "rusty_alloc")]
#[value(name = "rusty_alloc", alias = "rusty-alloc")]
RustyAlloc,
}
impl Allocator {
fn is_default(&self) -> bool {
*self == Self::default()
}
}
/// What a unit's bindings are for once the port is done (`bridge --end-state`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum EndState {
/// The Rust replaces the original, which is deleted after cut-over.
Replace,
/// Callers keep importing the unit through the bindings for good: they are public API.
Bindings,
/// The bindings are temporary and are deleted at cut-over.
Scaffold,
}
impl EndState {
pub fn name(self) -> &'static str {
match self {
Self::Replace => "replace",
Self::Bindings => "bindings",
Self::Scaffold => "scaffold",
}
}
/// What is left to do once the port matches, for people reading a report.
pub fn after_cut_over(self) -> &'static str {
match self {
Self::Replace => "delete the original once callers use the Rust",
Self::Bindings => "the bindings stay as public API: version and document them",
Self::Scaffold => "delete the bindings at cut-over",
}
}
}
/// Records the unit's end state in its manifest.
pub fn set_end_state(crate_dir: &Path, end_state: EndState) -> Result<()> {
let mut manifest = Manifest::load(crate_dir)?;
manifest.end_state = Some(end_state);
manifest.save(crate_dir)
}
/// How a crate folder inside `root` names the repository: `../..` for `<root>/rust/x-rs`.
/// `None` when the crate is outside it, where only an absolute path says where the repository
/// is (and ties the manifest to one machine).
fn relative_root(crate_dir: &Path, root: &Path) -> Option<PathBuf> {
let inside = crate_dir.strip_prefix(root).ok()?;
if !inside
.components()
.all(|c| matches!(c, std::path::Component::Normal(_)))
{
return None;
}
let depth = inside.components().count();
Some(if depth == 0 {
PathBuf::from(".")
} else {
PathBuf::from(vec![".."; depth].join("/"))
})
}
/// What `bridge` generated; every later step starts from it.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Manifest {
pub schema: String,
/// The repository root: absolute, or relative to the crate folder (so a crate kept inside
/// the repository it ports works in any clone). Resolved when the manifest is loaded.
pub root: PathBuf,
/// `root` as written in the file, when it was relative; written back instead of the resolved
/// path.
#[serde(skip)]
pub root_written: Option<PathBuf>,
pub unit: String,
#[serde(default)]
pub language: crate::lang::Lang,
pub kind: Kind,
pub crate_name: String,
/// Exports ported to Rust.
pub exports: Vec<ExportedFn>,
/// Exported classes ported to Rust: a struct with `new` and methods.
#[serde(default)]
pub classes: Vec<ExportedClass>,
/// Exports that cannot cross the bridge as they are; they stay in TS and the shadow module
/// re-exports them from the original.
#[serde(default)]
pub js_only: Vec<JsOnly>,
/// Functions run over many items kept in Rust (`--batch function:param`).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub batches: Vec<crate::codegen_batch::Batch>,
/// The global allocator when the crate has batches (`bridge --allocator`).
#[serde(default, skip_serializing_if = "Allocator::is_default")]
pub allocator: Allocator,
/// Floats match within this relative tolerance (`record --float-tolerance`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub float_tolerance: Option<f64>,
/// Objects match regardless of key order (`record --ignore-key-order`).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub ignore_key_order: bool,
/// Errors match on their message as well as their class (`record --messages`).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub messages: bool,
/// What the bindings are for once the port is done (`bridge --end-state`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_state: Option<EndState>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct JsOnly {
pub name: String,
pub file: String,
pub line: u32,
pub reason: String,
}
/// The local types by name, so that following a type's mentions is a lookup, not a scan of every
/// type in scope (a file importing generated code can have thousands).
struct TypesByName<'a> {
by_name: std::collections::HashMap<&'a str, &'a LocalType>,
}
// How many `walk` steps this thread ran: the count a timing test cannot give (issue #1058).
// Per thread, not per process: tests run in parallel, and other tests walk types of their own, so a
// shared counter would mix their steps into this one's.
#[cfg(test)]
thread_local! {
pub(crate) static WALK_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn take_walk_steps() -> usize {
WALK_STEPS.with(|steps| steps.replace(0))
}
impl<'a> TypesByName<'a> {
/// The first type of each name, which is the one a linear search finds.
fn new(types: &'a [LocalType]) -> Self {
let mut by_name = std::collections::HashMap::new();
for t in types {
by_name.entry(t.name.as_str()).or_insert(t);
}
Self { by_name }
}
/// Why `word`, a name in a type, is not known to be data: a capitalized name that is neither
/// a built-in data type nor declared in the project (`Logger`, a class, a library's type), or a
/// project type that mentions one. `None` for anything else, lowercase words included.
fn opaque(&self, word: &str) -> Option<String> {
self.opaque_in(word, &mut std::collections::HashSet::new())
.map(|name| {
if name == word {
format!(
"uses `{word}`, a type the bridge cannot see through: a class or library type crosses as a plain JSON object"
)
} else {
format!("uses `{word}`, which mentions `{name}`, a class or library type")
}
})
}
fn opaque_in(
&self,
word: &str,
seen: &mut std::collections::HashSet<String>,
) -> Option<String> {
if !word.starts_with(|c: char| c.is_ascii_uppercase()) || DATA_TYPES.contains(&word) {
return None;
}
let Some(t) = self.by_name.get(word) else {
return Some(word.to_string());
};
if !seen.insert(word.to_string()) {
return None;
}
// The type's own type parameters (`interface Box<T>`) are not mentions.
let header = t.text.lines().next().unwrap_or("");
let params: Vec<&str> = header
.split_once('<')
.and_then(|(_, rest)| rest.split_once('>'))
.map(|(p, _)| {
p.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
.filter(|w| !w.is_empty())
.collect()
})
.unwrap_or_default();
let body = without_literals(&t.text);
let mut rest = body.as_str();
while let Some(start) = rest.find(|c: char| c.is_ascii_uppercase()) {
rest = &rest[start..];
let end = rest
.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
.unwrap_or(rest.len());
let (name, after) = rest.split_at(end);
let before_ok = body[..body.len() - rest.len()]
.chars()
.next_back()
.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '$' || c == '.'));
let after = after.trim_start();
// A property called `Name:` or `Name?:` is a key, not a type.
let key = after.starts_with(':') || after.starts_with("?:");
rest = after_name(rest, end);
if before_ok
&& !key
&& name.len() > 2
&& name != word
&& !params.contains(&name)
&& let Some(found) = self.opaque_in(name, seen)
{
return Some(found);
}
}
None
}
/// Whether values of the local type `name` can hold functions: the type has a function or
/// method member, or extends or mentions a type that does.
fn has_functions(&self, name: &str) -> bool {
self.walk(name, &mut std::collections::HashSet::new())
}
fn walk<'s>(&'s self, name: &'s str, seen: &mut std::collections::HashSet<&'s str>) -> bool {
if !seen.insert(name) {
return false;
}
// A type is visited once, whatever the graph: an unwinding walk visits it again per edge,
// which is the quadratic shape this counts (issue #1058).
#[cfg(test)]
WALK_STEPS.with(|steps| steps.set(steps.get() + 1));
let Some(t) = self.by_name.get(name) else {
return false;
};
let text = &t.text;
// Members are split by line and by `;`, the declaration's own head (`interface A {`) is
// dropped, so a one-line `interface Svc { run(x: number): number }` is read too.
let body = text.split_once('{').map_or("", |(_, body)| body);
// A method or a call signature has a `(`: one scan rules out a type that has none, before
// the body is split into members.
let method = body.contains('(')
&& body.split(['\n', ';']).any(|l| {
let l = l.trim().trim_start_matches("readonly ").trim();
let Some((head, _)) = l.split_once('(') else {
return false;
};
// A call or construct signature (`(x: number): number`, `new (x: number): T`), or a
// method (`run(x)`, `map<T>(x: T)`, `m?(x)`).
let head = head.trim();
let generic_end = head.find('<').unwrap_or(head.len());
let name = head[..generic_end].trim_end_matches('?');
// `"run"(x: number): number`: a quoted method name is a method too.
let quoted =
name.len() > 1 && name.starts_with(['"', '\'']) && name.ends_with(['"', '\'']);
head.is_empty()
|| head == "new"
|| quoted
|| (!name.is_empty()
&& name
.chars()
.all(|c| c.is_alphanumeric() || c == '_' || c == '$'))
});
if text.contains("=>") || method {
return true;
}
text.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
.filter(|w| !w.is_empty() && *w != name)
.any(|w| self.walk(w, seen))
}
}
/// The exported functions of a TS/JS `file` with the types `bridge` judges them by: a sibling
/// `.d.ts` applied, aliases resolved and generic constraints substituted. `analyze` counts
/// bridgeable exports from the same list.
pub fn ts_functions(root: &Path, file: &str, text: &str, types: &[LocalType]) -> Vec<ExportedFn> {
let mut functions = exported_functions(file, text);
crate::ts::jsdoc::apply_declarations(root, file, &mut functions);
let aliases = AliasIndex::new(types);
for f in &mut functions {
for p in &mut f.params {
p.ts_type = resolve_aliases_with(&p.ts_type, &aliases);
}
f.returns = resolve_aliases_with(&f.returns, &aliases);
substitute_constraints(f, types);
}
functions
}
/// Why a class has to stay in the source language: its blocker, else the first method (and, for
/// TS/JS, the constructor) that cannot cross. `None` when it can be bridged.
pub fn class_reason(class: &ExportedClass, types: &[LocalType], ts: bool) -> Option<String> {
let constructor = ts.then(|| ExportedFn {
name: format!("{} constructor", class.name),
file: class.file.clone(),
line: class.line,
params: class.constructor.clone(),
returns: "void".into(),
..Default::default()
});
class.blocker.clone().or_else(|| {
constructor
.iter()
.chain(&class.methods)
.find_map(|m| signature_reason(m, types).map(|r| format!("`{}`: {r}", m.name)))
})
}
/// Why an export cannot cross a JS/Rust bridge unchanged, if it cannot.
///
/// Functions, iterators, RegExp objects and objects with function members are JS values a
/// Rust function can neither take nor return; porting them would change the public API.
pub fn js_only_reason(f: &ExportedFn, local_types: &[LocalType]) -> Option<String> {
signature_reason(f, local_types).or_else(|| unobserved_reason(f))
}
/// Why a top-level function cannot be checked by `record`, which compares return values only:
/// it returns nothing. (Printing and changing an argument in place are found by the language
/// plugins and arrive as the function's blocker.) C records its `out` and `buffer` arguments
/// back after the call, and a Go function that returns only an `error` returns that error.
fn unobserved_reason(f: &ExportedFn) -> Option<String> {
if !crate::lang::effects::returns_nothing(&f.returns) {
return None;
}
// TS/JS and Python record the arguments after the call and what it printed: a function that
// returns nothing but changes an argument or prints is seen through those.
if !f.mutates.is_empty() || f.prints {
return None;
}
let observed_args = f.prototype.is_some()
&& f.native_return.as_deref() == Some("void")
&& f.params
.iter()
.any(|p| p.ts_type == "buffer" || p.ts_type.starts_with("out"));
let go_error_only = f.native_return.as_deref() == Some("(error)");
(!observed_args && !go_error_only).then(|| crate::lang::effects::RETURNS_NOTHING.to_string())
}
/// The part of [`js_only_reason`] that judges the signature, which holds for a class's methods
/// as well: a method that returns nothing is seen through the calls that follow it.
fn signature_reason(f: &ExportedFn, local_types: &[LocalType]) -> Option<String> {
// A function type is the plainest reason, and the one a `.d.ts` or JSDoc gives an untyped
// function whose body only calls its parameter.
if f.params
.iter()
.map(|p| p.ts_type.as_str())
.chain(std::iter::once(f.returns.as_str()))
.any(|t| t.contains("=>"))
{
return Some("takes or returns a function".into());
}
if let Some(blocker) = &f.blocker {
return Some(blocker.clone());
}
if f.is_generator {
return Some("generator: returns a lazy iterator".into());
}
if f.uses_instanceof {
return Some("checks `instanceof`: class identity does not survive the bridge".into());
}
let types: Vec<&str> = f
.params
.iter()
.map(|p| p.ts_type.as_str())
.chain(std::iter::once(f.returns.as_str()))
.collect();
if types.iter().any(|t| t.contains("=>")) {
return Some("takes or returns a function".into());
}
let words = |t: &str| -> Vec<String> {
without_literals(t)
.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
.filter(|w| !w.is_empty())
.map(str::to_string)
.collect()
};
// A TS/JS type the bridge cannot see through (a class, an external or a library type) would
// cross as a plain JSON object: the port could not call its methods and a recording of it
// holds the flattened object or only throws. Types read from other languages are in the
// dialect, which has no such names.
let ts = crate::lang::Lang::Ts
.extensions()
.iter()
.any(|e| f.file.ends_with(&format!(".{e}")));
let mut by_name: Option<TypesByName> = None;
for t in &types {
let mut keys = property_key_counts(t);
for word in words(t) {
match word.as_str() {
"RegExp" => return Some("takes or returns a RegExp".into()),
"Generator" | "Iterator" | "IterableIterator" | "AsyncGenerator"
| "AsyncIterable" => {
return Some(format!("uses `{word}`, a lazy iterator"));
}
"Function" => return Some("takes or returns a function".into()),
_ => {}
}
if f.type_params.contains(&word) {
return Some(format!(
"generic over `{word}`: values of any shape, functions included"
));
}
if by_name
.get_or_insert_with(|| TypesByName::new(local_types))
.has_functions(&word)
{
return Some(format!("uses `{word}`, which has function members"));
}
// A property key (`{ Name: string }`) names no type: use up one key occurrence.
let is_key = keys.get_mut(&word).is_some_and(|n| {
let key = *n > 0;
*n = n.saturating_sub(1);
key
});
if ts
&& !is_key
&& let Some(why) = by_name
.get_or_insert_with(|| TypesByName::new(local_types))
.opaque(&word)
{
return Some(why);
}
}
}
None
}
fn after_name(rest: &str, end: usize) -> &str {
&rest[end..]
}
/// How many times each name in `t` is a property key (`{ Name: string }`, `Name?: number`) and so
/// names no type there.
fn property_key_counts(t: &str) -> std::collections::HashMap<String, usize> {
static KEY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let key =
KEY.get_or_init(|| regex::Regex::new(r"([A-Za-z_$][A-Za-z0-9_$]*)\s*\??\s*:").unwrap());
let mut counts = std::collections::HashMap::new();
for found in key.captures_iter(&without_literals(t)) {
*counts.entry(found[1].to_string()).or_insert(0) += 1;
}
counts
}
/// `t` with the insides of string literals blanked (`'A' | 'B'` names no type `A`).
fn without_literals(t: &str) -> String {
let mut out = String::with_capacity(t.len());
let mut quote = None;
for c in t.chars() {
match (quote, c) {
(None, '\'' | '"' | '`') => {
quote = Some(c);
out.push(' ');
}
(Some(q), c) if c == q => {
quote = None;
out.push(' ');
}
(Some(_), _) => out.push(' '),
(None, c) => out.push(c),
}
}
out
}
/// Types a bridge carries as data though they are not declared in the project.
const DATA_TYPES: &[&str] = &[
"Array",
"ReadonlyArray",
"Record",
"Partial",
"Required",
"Readonly",
"Pick",
"Omit",
"NonNullable",
"Exclude",
"Extract",
"Promise",
"Awaited",
"Map",
"Set",
"ReadonlyMap",
"ReadonlySet",
"Date",
"Uint8Array",
"Uint8ClampedArray",
"Int8Array",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array",
"BigInt64Array",
"BigUint64Array",
"ArrayBuffer",
"Buffer",
"Error",
"Object",
"String",
"Number",
"Boolean",
"BigInt",
"NaN",
"Infinity",
"Uppercase",
"Lowercase",
"Capitalize",
"Uncapitalize",
];
/// For each of a unit's functions, why it reaches state the original owns: it takes or returns an
/// object of a class, or calls a function of the unit that does, directly or through others
/// ("calls `instance`, which uses the class `Config`"). A port in Rust has no such object to call
/// it with, so a caller stays with it. A function kept for its signature alone (overloaded, takes
/// a callback) can be ported along with its caller and keeps no one.
pub fn state_through_calls(fns: &[ExportedFn]) -> Vec<Option<String>> {
state_through_calls_with(fns, &[])
}
/// [`state_through_calls`], with functions of other units that this one calls: they carry the reason the
/// chain continues with (`calls `X.y`, which reads app state (`Z.instance`)`).
pub fn state_through_calls_with(fns: &[ExportedFn], outside: &[ExportedFn]) -> Vec<Option<String>> {
// The outside functions join the same loop: they carry the reason the chain continues with.
let mut all: Vec<ExportedFn> = fns.to_vec();
all.extend(outside.iter().cloned());
// The unit's own reasons are the plugin's, filtered the way every other caller filters them; a
// collector's outside reason is already a chain (`calls `X.y`, which reads app state (…)`), so it is
// taken as it is.
let inside = fns.len();
let mut state: Vec<Option<String>> = all
.iter()
.enumerate()
.map(|(i, f)| {
f.blocker
.clone()
.filter(|b| i >= inside || crate::lang::holds_state(b))
})
.collect();
loop {
let before = state.clone();
for (i, f) in all.iter().enumerate() {
if state[i].is_some() {
continue;
}
state[i] = f.calls.iter().find_map(|call| {
all.iter()
.zip(&before)
.enumerate()
.find_map(|(j, (g, why))| {
let why = why.as_deref()?;
// The call as the plugin wrote it: `PostDataHelper.createQueryTV` names the
// helper the reader has to go and look at (issue #1042).
(j != i && (j < inside || call.contains('.')) && is_call_to(call, g))
.then(|| format!("calls `{call}`, which {why}"))
})
});
}
if state == before {
state.truncate(fns.len());
return state;
}
}
}
/// Every function of the repository's `lang` files that reaches state, with the reason as its
/// blocker, after following each file's own calls (`createQueryTV` -> `PostDataHelper.language` ->
/// `LocaleManager.instance`). The prototype the plugin wrote stays, so a call is matched against the
/// declaring class and its package (issue #1042).
pub fn outside_state(lang: crate::lang::Lang, root: &std::path::Path) -> Vec<ExportedFn> {
let mut out = Vec::new();
let walker = crate::walk::filtered(root, |_| true)
.hidden(true)
.require_git(false)
.build();
for entry in walker.flatten() {
if !entry.file_type().is_some_and(|t| t.is_file()) {
continue;
}
let path = entry.path();
if !path
.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| lang.extensions().contains(&e))
{
continue;
}
let Some((text, _)) = crate::analyze::read_source(path) else {
continue;
};
let file = path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
let (functions, _) = crate::lang::exports(lang, &file, &text);
let states = state_through_calls(&functions);
out.extend(functions.into_iter().zip(states).filter_map(|(f, why)| {
Some(ExportedFn {
blocker: Some(why?),
..f
})
}));
}
out
}
/// The functions of other units that `fns` call through an owner (`PostDataHelper.createQueryTV`),
/// from [`outside_state`]. The repository is read once, on the first unit that needs it, and kept in
/// `index` for the next.
pub fn outside_state_calls(
lang: crate::lang::Lang,
root: &std::path::Path,
index: &mut Option<Vec<ExportedFn>>,
fns: &[ExportedFn],
) -> Vec<ExportedFn> {
let wanted: std::collections::BTreeSet<&str> = fns
.iter()
.flat_map(|f| f.calls.iter())
.filter_map(|call| call.rsplit_once('.').map(|(_, name)| name))
.collect();
if wanted.is_empty() || lang == crate::lang::Lang::Ts {
return Vec::new();
}
index
.get_or_insert_with(|| outside_state(lang, root))
.iter()
.filter(|f| wanted.contains(f.name.as_str()))
.cloned()
.collect()
}
/// Whether `call`, as a plugin names it in [`ExportedFn::calls`], is a call to `f`: the bare
/// name, or `Owner.name` matching the end of the qualified name in the prototype.
fn is_call_to(call: &str, f: &ExportedFn) -> bool {
if !call.contains('.') {
return call == f.name;
}
let qualified = f
.prototype
.as_deref()
.and_then(|p| p.split('(').next())
.unwrap_or(&f.name);
qualified == call || qualified.ends_with(&format!(".{call}"))
}
/// The class a PHP static method belongs to (`Acme\Text\Words::count` -> `Acme\Text\Words`).
fn php_method_owner(f: &ExportedFn) -> Option<String> {
let head = f.prototype.as_deref()?.split('(').next()?.trim();
head.split_once("::").map(|(owner, _)| owner.to_string())
}
/// PHP wrappers replace a whole class, and PHP has no partial classes: when one method of a class
/// stays in PHP (a `void` return or `--keep`), its other methods stay too. A class with no method
/// that could bridge keeps each method's own reason.
fn keep_php_classes_together(planned: &mut [(ExportedFn, Option<String>)]) {
let mut class_stays: Vec<(String, String, String)> = Vec::new();
let mut class_has_export: Vec<String> = Vec::new();
for (f, kept) in planned.iter() {
let Some(owner) = php_method_owner(f) else {
continue;
};
if let Some(why) = kept.clone()
&& !class_stays.iter().any(|(seen, _, _)| seen == &owner)
{
class_stays.push((owner.clone(), f.name.clone(), why));
}
if kept.is_none() && !class_has_export.contains(&owner) {
class_has_export.push(owner);
}
}
for (f, kept) in planned.iter_mut() {
if kept.is_some() {
continue;
}
let Some(owner) = php_method_owner(f) else {
continue;
};
if !class_has_export.contains(&owner) {
continue;
}
let Some((_, name, why)) = class_stays.iter().find(|(seen, _, _)| seen == &owner) else {
continue;
};
let class = owner.rsplit('\\').next().unwrap_or(&owner);
*kept = Some(format!(
"`{class}` has a method that stays in PHP (`{name}`: {why}), so its static methods stay"
));
}
}
impl Manifest {
pub fn load(crate_dir: &Path) -> Result<Self> {
let path = crate_dir.join(MANIFEST);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(Self::missing(crate_dir));
}
Err(e) => {
return Err(anyhow::Error::new(e).context(format!(
"reading {} (run `rust-anything bridge` first)",
path.display()
)));
}
};
Self::parse(&text, crate_dir)
}
fn missing(crate_dir: &Path) -> anyhow::Error {
let dir = crate_dir.display();
if crate_dir.is_dir() {
anyhow::anyhow!("no {MANIFEST} in {dir} (run `rust-anything bridge` first)")
} else {
anyhow::anyhow!("no folder {dir} (run `rust-anything bridge` first)")
}
}
/// The manifest written in `text`, as found in `crate_dir`: `load` without the reading, for a
/// caller that opens the file itself.
pub fn parse(text: &str, crate_dir: &Path) -> Result<Self> {
let path = crate_dir.join(MANIFEST);
let mut manifest: Self =
serde_json::from_str(text).with_context(|| format!("parsing {}", path.display()))?;
if manifest.root.is_relative() {
let resolved = crate_dir.join(&manifest.root);
let resolved = resolved.canonical().unwrap_or(resolved);
manifest.root_written = Some(std::mem::replace(&mut manifest.root, resolved));
}
Ok(manifest)
}
/// Writes the manifest back, keeping a relative root relative.
pub fn save(&self, crate_dir: &Path) -> Result<()> {
let mut m = self.clone();
if let Some(written) = m.root_written.take() {
m.root = written;
}
let path = crate_dir.join(MANIFEST);
write_atomic(&path, &(serde_json::to_string_pretty(&m)? + "\n"))
.with_context(|| format!("writing {}", path.display()))
}
/// Rust library name: the crate name with `-` replaced.
pub fn lib_name(&self) -> String {
self.crate_name.replace('-', "_")
}
}
pub struct Options<'a> {
pub root: &'a Path,
pub unit: &'a str,
pub kind: Option<Kind>,
pub out: Option<PathBuf>,
pub name: Option<String>,
/// Bridge a unit the plan marks blocked or keep.
pub force: bool,
/// Exports to keep in TS, with an optional reason: `name` or `name: reason`.
pub keep: Vec<String>,
/// Source language; detected from the repository when `None`.
pub lang: Option<crate::lang::Lang>,
/// `function:param` pairs: batch classes running `function` over many `param` values.
pub batch: Vec<String>,
/// Type parameters the app only fills with data: bridged as JSON values instead of keeping
/// the export in TS.
pub as_json: Vec<String>,
/// The global allocator for crates with batches.
pub allocator: Allocator,
}
#[derive(Debug, Serialize)]
pub struct Outcome {
pub crate_dir: PathBuf,
pub kind: Kind,
pub files: Vec<String>,
pub exports: Vec<String>,
pub notes: Vec<String>,
}
/// A Rust type as seen by the port, from a TS type annotation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RType {
Str,
F64,
/// A whole number (`int` in the type dialect: Python, Go, Java and C have one; JS does not).
Int,
Bool,
/// A byte buffer (`bytes` in the type dialect): `Vec<u8>` in the port.
Bytes,
/// A `pathlib` path (`pypath` in the type dialect): `std::path::PathBuf` in the port.
Path,
Unit,
Vec(Box<RType>),
Opt(Box<RType>),
/// Anything structured: crosses the bridge as JSON.
Json,
}
impl RType {
pub fn from_ts(ts: &str) -> Self {
let ts = ts.trim().trim_start_matches("readonly ").trim();
// `(string | null)`: one parenthesized group around the whole type.
if let Some(inner) = ts.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
&& balanced(inner)
{
return Self::from_ts(inner);
}
if let Some(inner) = ts
.strip_prefix("Promise<")
.and_then(|t| t.strip_suffix('>'))
{
return Self::from_ts(inner);
}
let parts = split_top(ts, '|');
if parts.len() > 1 {
let (nullish, rest): (Vec<&str>, Vec<&str>) = parts
.iter()
.partition(|p| matches!(p.trim(), "undefined" | "null" | "void"));
if rest.iter().all(|p| is_string_literal(p)) {
return Self::wrap_opt(Self::Str, !nullish.is_empty());
}
if rest.len() == 1 {
return Self::wrap_opt(Self::from_ts(rest[0]), !nullish.is_empty());
}
return Self::Json;
}
if let Some(inner) = ts.strip_suffix("[]") {
return Self::Vec(Box::new(Self::from_ts(
inner.trim_start_matches('(').trim_end_matches(')'),
)));
}
for wrapper in ["Array<", "ReadonlyArray<"] {
if let Some(inner) = ts.strip_prefix(wrapper).and_then(|t| t.strip_suffix('>')) {
return Self::Vec(Box::new(Self::from_ts(inner)));
}
}
// `value is MessageLeaf`: a type predicate returns a boolean; `asserts x` returns nothing.
if ts.starts_with("asserts ") {
return Self::Unit;
}
if let Some((subject, _)) = ts.split_once(" is ")
&& subject
.trim()
.chars()
.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
{
return Self::Bool;
}
match ts {
"string" => Self::Str,
"number" => Self::F64,
"int" => Self::Int,
"boolean" => Self::Bool,
"pybytes" => Self::Bytes,
"pypath" => Self::Path,
"void" | "undefined" => Self::Unit,
_ if is_string_literal(ts) => Self::Str,
_ => Self::Json,
}
}
fn wrap_opt(t: Self, optional: bool) -> Self {
if optional { Self::Opt(Box::new(t)) } else { t }
}
pub fn rust(&self) -> String {
match self {
Self::Str => "String".into(),
Self::F64 => "f64".into(),
Self::Int => "i64".into(),
Self::Bool => "bool".into(),
Self::Bytes => "Vec<u8>".into(),
Self::Path => "std::path::PathBuf".into(),
Self::Unit => "()".into(),
Self::Vec(t) => format!("Vec<{}>", t.rust()),
Self::Opt(t) => format!("Option<{}>", t.rust()),
Self::Json => "serde_json::Value".into(),
}
}
pub fn contains_json(&self) -> bool {
match self {
Self::Json => true,
Self::Vec(t) | Self::Opt(t) => t.contains_json(),
_ => false,
}
}
}
fn is_string_literal(ts: &str) -> bool {
let ts = ts.trim();
ts.len() >= 2
&& ((ts.starts_with('\'') && ts.ends_with('\''))
|| (ts.starts_with('"') && ts.ends_with('"')))
}
fn balanced(ts: &str) -> bool {
let mut depth = 0i32;
for c in ts.chars() {
match c {
'(' => depth += 1,
')' => {
depth -= 1;
if depth < 0 {
return false;
}
}
_ => {}
}
}
depth == 0
}
/// Splits on `sep` outside brackets. The `>` of an arrow (`=>`) closes nothing.
fn split_top(ts: &str, sep: char) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0i32;
let mut start = 0;
let mut prev = None;
for (i, c) in ts.char_indices() {
let arrow = c == '>' && prev == Some('=');
prev = Some(c);
match c {
'>' if arrow => {}
'<' | '(' | '[' | '{' => depth += 1,
'>' | ')' | ']' | '}' => depth -= 1,
c if c == sep && depth == 0 => {
out.push(ts[start..i].trim());
start = i + c.len_utf8();
}
_ => {}
}
}
out.push(ts[start..].trim());
out.retain(|p| !p.is_empty());
out
}
/// A parameter's type for the port, rest and optional parameters included.
pub fn param_type(p: &crate::ts::exports::Param) -> RType {
let base = RType::from_ts(&p.ts_type);
let base = if p.rest {
match base {
RType::Vec(_) => base,
other => RType::Vec(Box::new(other)),
}
} else {
base
};
if p.optional && !matches!(base, RType::Opt(_)) {
RType::Opt(Box::new(base))
} else {
base
}
}
pub fn snake_case(name: &str) -> String {
let owned;
let src = if name.contains("::") {
owned = name.replace("::", "_");
owned.as_str()
} else {
name
};
let chars: Vec<char> = src.chars().collect();
let mut out = String::new();
for (i, &c) in chars.iter().enumerate() {
if c.is_uppercase() {
let prev = i.checked_sub(1).map(|j| chars[j]);
let next = chars.get(i + 1);
let boundary = prev.is_some_and(|p| p.is_lowercase() || p.is_ascii_digit())
|| (prev.is_some_and(char::is_uppercase) && next.is_some_and(|n| n.is_lowercase()));
if boundary {
out.push('_');
}
out.extend(c.to_lowercase());
} else if c.is_alphanumeric() {
out.push(c);
} else {
out.push('_');
}
}
rust_ident(&out)
}
/// Two exports with different names that become the same Rust function (`fooBar` and `foo_bar`,
/// `$id` and `_id`, `self` and `Self`): `port.rs` and the bindings would define it twice. The
/// first pair in source order, or `None`. A repeated source name is refused before this.
fn rust_name_clash(exports: &[ExportedFn]) -> Option<(&ExportedFn, &ExportedFn)> {
let mut named: Vec<(String, &ExportedFn)> =
exports.iter().map(|f| (snake_case(&f.name), f)).collect();
named.sort_by(|a, b| a.0.cmp(&b.0));
named
.windows(2)
.find(|w| w[0].0 == w[1].0)
.map(|w| (w[0].1, w[1].1))
}
const KEYWORDS: &[&str] = &[
"as", "break", "const", "continue", "else", "enum", "extern", "false", "fn", "for", "if",
"impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "static",
"struct", "trait", "true", "type", "unsafe", "use", "where", "while", "async", "await", "dyn",
"abstract", "become", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized",
"virtual", "yield", "try", "gen",
];
pub(crate) fn rust_ident(word: &str) -> String {
if matches!(word, "self" | "Self" | "super" | "crate" | "_") {
format!("{word}_")
} else if KEYWORDS.contains(&word) {
format!("r#{word}")
} else {
word.to_string()
}
}
/// Types declared in `file` and in the files it imports relatively (one level deep).
pub fn types_in_scope(root: &Path, file: &str, text: &str) -> Vec<LocalType> {
types_in_scope_cached(root, file, text, &mut TypeCache::default())
}
/// What `types_in_scope` needs of one file: its own types, and the files it imports or
/// re-exports that exist, root-relative and in import order.
struct ScopedFile {
types: Vec<LocalType>,
imports: Vec<String>,
}
/// The parsed files of one run of [`types_in_scope_cached`] calls. A file's import closure is
/// the same for every file that reaches it, so a run over many files (`analyze` over a package
/// that imports a barrel or another workspace package) parses each file once, not once per
/// importer. Keep one cache per run: it never notices a file changing.
#[derive(Default)]
pub struct TypeCache {
files: std::collections::HashMap<String, std::rc::Rc<ScopedFile>>,
packages: Option<std::collections::HashMap<String, String>>,
/// Files parsed, hits not counted: what the tests check the sharing against.
#[cfg(test)]
parses: usize,
}
impl TypeCache {
/// The parsed `file`, from `text` when the caller already has it, else read from disk;
/// `None` when it cannot be read.
fn file(
&mut self,
root: &Path,
file: &str,
text: Option<&str>,
) -> Option<std::rc::Rc<ScopedFile>> {
if let Some(hit) = self.files.get(file) {
return Some(hit.clone());
}
let read;
let text = match text {
Some(text) => text,
None => {
read = std::fs::read_to_string(root.join(file)).ok()?;
&read
}
};
let scoped = std::rc::Rc::new(ScopedFile {
types: local_types(file, text),
imports: imported_files(root, file, text, &mut self.packages),
});
#[cfg(test)]
{
self.parses += 1;
}
self.files.insert(file.to_string(), scoped.clone());
Some(scoped)
}
}
/// [`types_in_scope`] sharing the parsed files of `cache` with every other call that uses it.
pub fn types_in_scope_cached(
root: &Path,
file: &str,
text: &str,
cache: &mut TypeCache,
) -> Vec<LocalType> {
let mut types = Vec::new();
let mut seen = std::collections::HashSet::new();
collect_types(root, file, Some(text), 0, cache, &mut seen, &mut types);
types
}
/// Types of a file and of the files it imports or re-exports, a few levels deep
/// (`./types` -> `types/index.ts` -> `export * from './host'`).
fn collect_types(
root: &Path,
file: &str,
text: Option<&str>,
depth: usize,
cache: &mut TypeCache,
seen: &mut std::collections::HashSet<String>,
types: &mut Vec<LocalType>,
) {
if depth > 4 || !seen.insert(file.to_string()) {
return;
}
let Some(scoped) = cache.file(root, file, text) else {
return;
};
types.extend(scoped.types.iter().cloned());
for found in &scoped.imports {
collect_types(root, found, None, depth + 1, cache, seen, types);
}
}
/// The files `file` imports or re-exports that exist, root-relative and in import order.
fn imported_files(
root: &Path,
file: &str,
text: &str,
packages: &mut Option<std::collections::HashMap<String, String>>,
) -> Vec<String> {
let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
let mut found_files = Vec::new();
for import in crate::ts::scan::scan(file, text).imports {
let spec = import.specifier;
// Workspace packages (`@x18n/core`) are followed to their source entry.
let base = if spec.starts_with('.') {
let joined = if dir.is_empty() {
spec.clone()
} else {
format!("{dir}/{spec}")
};
match normalize_rel(&joined) {
Some(base) => base,
None => continue,
}
} else {
let name = crate::ts::deps::package_name(&spec);
let Some(pkg_dir) = packages
.get_or_insert_with(|| workspace_packages(root))
.get(name)
.cloned()
else {
continue;
};
let sub = spec[name.len()..].trim_start_matches('/');
let src = if root.join(&pkg_dir).join("src").is_dir() {
format!("{pkg_dir}/src")
} else {
pkg_dir
};
let src = src.trim_start_matches('/').to_string();
if sub.is_empty() {
format!("{src}/index")
} else {
format!("{src}/{sub}")
}
};
let stem = base.trim_end_matches(".js");
let candidates = [
format!("{stem}.ts"),
format!("{stem}.mts"),
format!("{stem}.d.ts"),
format!("{stem}/index.ts"),
base.clone(),
];
if let Some(found) = candidates.iter().find(|c| root.join(c).is_file()) {
found_files.push(found.clone());
}
}
found_files
}
/// Workspace package names and their root-relative folders.
fn workspace_packages(root: &Path) -> std::collections::HashMap<String, String> {
crate::ts::discover::discover(root)
.map(|ws| ws.packages.into_iter().map(|p| (p.name, p.dir)).collect())
.unwrap_or_default()
}
/// Collapses `.` and `..` in a root-relative path.
fn normalize_rel(path: &str) -> Option<String> {
let mut parts: Vec<&str> = Vec::new();
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop()?;
}
_ => parts.push(part),
}
}
Some(parts.join("/"))
}
/// `f<T extends string>(s: T)` takes a string: type parameters with a simple constraint are
/// replaced by it. The rest stay listed, and keep the function in TS.
pub fn substitute_constraints(f: &mut ExportedFn, types: &[LocalType]) {
let mut remaining = Vec::new();
let mut by_name: Option<TypesByName> = None;
for tp in std::mem::take(&mut f.type_params) {
let Some((name, constraint)) = tp.split_once(" extends ") else {
remaining.push(tp);
continue;
};
let constraint = resolve_aliases(constraint, types);
// Data constraints (`string`, `string | readonly string[]`) are substituted; anything that
// could hold a function keeps the type parameter, and the function stays in TS.
let open_ended = constraint.contains("=>")
|| constraint
.split(|c: char| !(c.is_alphanumeric() || c == '_'))
.any(|w| {
matches!(w, "Function" | "object" | "unknown" | "any")
|| by_name
.get_or_insert_with(|| TypesByName::new(types))
.has_functions(w)
});
if open_ended {
remaining.push(name.to_string());
continue;
}
let replacement = format!("({constraint})");
for p in &mut f.params {
p.ts_type = replace_word(&p.ts_type, name, &replacement);
}
f.returns = replace_word(&f.returns, name, &replacement);
}
f.type_params = remaining;
}
/// The name of a declared type parameter (`T` in `T extends object`).
fn type_param_name(tp: &str) -> &str {
tp.split_once(" extends ").map_or(tp, |(n, _)| n).trim()
}
/// The type parameters `file`'s exports declare, read as `ts_functions` reads them but before
/// `substitute_constraints` resolves a data-constrained one (`T extends string`) away, plus those
/// of bodyless overload signatures, which `exported_functions` skips.
fn declared_type_params(root: &Path, file: &str, text: &str) -> Vec<String> {
let mut functions = exported_functions(file, text);
crate::ts::jsdoc::apply_declarations(root, file, &mut functions);
functions
.iter()
.chain(&crate::ts::exports::declared_functions(file, text))
.flat_map(|f| {
f.type_params
.iter()
.map(|tp| type_param_name(tp).to_string())
})
.collect()
}
/// Turns the type parameters named in `names` into `unknown` (a JSON value on the Rust side).
pub fn substitute_json(f: &mut ExportedFn, names: &[String]) {
let mut remaining = Vec::new();
for tp in std::mem::take(&mut f.type_params) {
let name = type_param_name(&tp);
if !names.iter().any(|n| n == name) {
remaining.push(tp);
continue;
}
for p in &mut f.params {
p.ts_type = replace_word(&p.ts_type, name, "unknown");
}
f.returns = replace_word(&f.returns, name, "unknown");
}
f.type_params = remaining;
}
fn replace_word(text: &str, word: &str, with: &str) -> String {
let mut out = String::new();
let mut current = String::new();
for c in text.chars().chain(std::iter::once(' ')) {
if c.is_alphanumeric() || c == '_' || c == '$' {
current.push(c);
} else {
out.push_str(if current == word { with } else { ¤t });
current.clear();
out.push(c);
}
}
out.pop();
out
}
/// The `type X = …` aliases of a file, by name, so resolving a word is a lookup instead of a scan
/// of every type in scope (issue #1032: a closure with thousands of types paid that per word).
///
/// The first alias of a name wins, like the scan it replaces: a later duplicate never shadows it,
/// and a type that is not an alias is never in the map.
pub struct AliasIndex<'a> {
by_name: std::collections::HashMap<&'a str, &'a LocalType>,
}
impl<'a> AliasIndex<'a> {
pub fn new(types: &'a [LocalType]) -> Self {
let mut by_name = std::collections::HashMap::new();
for t in types {
if t.alias {
by_name.entry(t.name.as_str()).or_insert(t);
}
}
Self { by_name }
}
fn get(&self, word: &str) -> Option<&'a LocalType> {
self.by_name.get(word).copied()
}
/// How many names resolve; a test uses it to show that non-alias types are left out.
pub fn len(&self) -> usize {
self.by_name.len()
}
pub fn is_empty(&self) -> bool {
self.by_name.is_empty()
}
}
/// Replaces simple type aliases (`type KeyString = string`) by what they stand for.
///
/// Builds the index for one call; a caller that resolves many types against the same list (every
/// function of a file) should build `AliasIndex::new(types)` once and call `resolve_aliases_with`.
pub fn resolve_aliases(ts: &str, types: &[LocalType]) -> String {
resolve_aliases_with(ts, &AliasIndex::new(types))
}
/// `resolve_aliases` against an index built once, for the hot path.
pub fn resolve_aliases_with(ts: &str, index: &AliasIndex<'_>) -> String {
let mut out = ts.to_string();
for _ in 0..4 {
let mut changed = false;
let mut next = String::with_capacity(out.len());
let mut word = String::new();
let flush = |word: &mut String, next: &mut String, changed: &mut bool| {
if let Some(t) = index.get(word) {
let text = t.text.trim();
if text.contains('|') {
next.push('(');
next.push_str(text);
next.push(')');
} else {
next.push_str(text);
}
*changed = true;
} else {
next.push_str(word);
}
word.clear();
};
for c in out.chars() {
if c.is_alphanumeric() || c == '_' || c == '$' {
word.push(c);
} else {
flush(&mut word, &mut next, &mut changed);
next.push(c);
}
}
flush(&mut word, &mut next, &mut changed);
out = next;
if !changed {
break;
}
}
out
}
fn needs_js(api: &codegen::PortApi) -> bool {
api.needs_json()
}
/// The name and the reason of a `--keep name` or `--keep "name: reason"` entry, trimmed.
/// A `::` in a qualified name (e.g. `Str::length`) stays part of the name.
fn keep_entry(k: &str) -> (&str, &str) {
let bytes = k.as_bytes();
let split = bytes
.iter()
.enumerate()
.find(|&(i, &b)| {
b == b':'
&& bytes.get(i + 1) != Some(&b':')
&& i.checked_sub(1).and_then(|j| bytes.get(j)) != Some(&b':')
})
.map(|(i, _)| i);
match split {
Some(i) => (k[..i].trim(), k[i + 1..].trim()),
None => (k.trim(), ""),
}
}
/// Fails when a `--keep` entry names none of the unit's exports and classes (`names`), so a typo
/// does not bridge the export it meant to keep.
fn check_keep(keep: &[String], names: &[&str], unit: &str) -> Result<()> {
if let Some((name, _)) = keep
.iter()
.map(|k| keep_entry(k))
.find(|(name, _)| !names.contains(name))
{
let mut known = names.to_vec();
known.sort_unstable();
known.dedup();
bail!(
"--keep `{name}` is not an export of `{unit}` (exports: {})",
known.join(", ")
);
}
Ok(())
}
/// Refuses an `--as-json` name that no export declares as a type parameter, so a typo does not
/// leave the generic export in TS without a word.
fn check_as_json(as_json: &[String], type_params: &[String], unit: &str) -> Result<()> {
if let Some(name) = as_json.iter().find(|n| !type_params.contains(n)) {
let mut known = type_params.to_vec();
known.sort_unstable();
known.dedup();
if known.is_empty() {
bail!("--as-json `{name}` is not a type parameter of `{unit}` (it has none)");
}
bail!(
"--as-json `{name}` is not a type parameter of `{unit}` (type parameters: {})",
known.join(", ")
);
}
Ok(())
}
/// The reason given with `--keep name` or `--keep "name: reason"`, if `name` is kept.
fn keep_reason(keep: &[String], name: &str) -> Option<String> {
keep.iter().find_map(|k| {
let (kept, reason) = keep_entry(k);
(kept == name).then(|| {
if reason.is_empty() {
"kept on request".to_string()
} else {
reason.to_string()
}
})
})
}
/// Formats the generated Rust, best effort: the gate checks formatting.
fn format_rust(crate_dir: &Path) {
let files: Vec<PathBuf> = std::fs::read_dir(crate_dir.join("src"))
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "rs"))
.collect();
let _ = std::process::Command::new("rustfmt")
.args(["--edition", "2024"])
.args(&files)
.output();
}
/// Formats a generated Go wrapper with `gofmt`, best effort.
fn format_wrapper(crate_dir: &Path) {
if crate_dir.join("go").is_dir() {
let _ = std::process::Command::new("gofmt")
.arg("-w")
.arg(crate_dir.join("go"))
.output();
}
}
/// `lib.rs` of a JS crate: the bindings, and the binary wire when functions use it.
fn js_lib_rs(m: &Manifest, api: &codegen::PortApi, modules: &codegen::Modules) -> Result<String> {
let mut lib = with_allocator(m, codegen::lib_rs(m, api, modules));
if m.kind != Kind::Pyo3 && !m.batches.is_empty() {
lib.push_str(&crate::codegen_batch::js_rs(m, api).map_err(anyhow::Error::msg)?);
}
if !crate::codegen_tswire::uses_wire(m, api) {
return Ok(lib);
}
Ok(lib.replacen(
"pub mod port;",
"pub mod port;\npub mod wire;\n\n#[allow(unused_imports)]\nuse serde_json::Value;",
1,
) + &crate::codegen_tswire::napi_rs(m, api))
}
fn parse_batches(specs: &[String]) -> Result<Vec<crate::codegen_batch::Batch>> {
specs
.iter()
.map(|s| {
crate::codegen_batch::Batch::parse(s)
.with_context(|| format!("`--batch {s}`: write it as function:param"))
})
.collect()
}
/// Fails when `lang` or `kind` has no batch generator yet, so `bridge` and `refresh --batch`
/// refuse `--batch` in one place with the same message.
fn ensure_batch_support(lang: crate::lang::Lang, kind: Kind) -> Result<()> {
use crate::lang::Lang;
let unsupported = match lang {
Lang::C | Lang::Php | Lang::Csharp | Lang::Powershell | Lang::Swift => Some(lang.name()),
_ if kind == Kind::CAbi => Some(Lang::C.name()),
_ => None,
};
if let Some(name) = unsupported {
bail!("`--batch` is not available for {name} units yet");
}
Ok(())
}
/// Adds batch classes to a bridged crate, then regenerates its bindings.
pub fn add_batches(crate_dir: &Path, specs: &[String]) -> Result<Refreshed> {
let path = crate_dir.join(MANIFEST);
let before = std::fs::read_to_string(&path).with_context(|| format!("{}", path.display()))?;
let mut manifest = Manifest::load(crate_dir)?;
if !specs.is_empty() {
ensure_batch_support(manifest.language, manifest.kind)?;
}
for b in parse_batches(specs)? {
if !manifest.batches.contains(&b) {
manifest.batches.push(b);
}
}
if let Some(written) = manifest.root_written.clone() {
manifest.root = written;
}
write_atomic(&path, &(serde_json::to_string_pretty(&manifest)? + "\n"))?;
// A batch the port cannot serve leaves the crate as it was.
refresh(crate_dir).inspect_err(|_| {
let _ = write_atomic(&path, &before);
})
}
/// Cargo.toml with the dependencies and library types today's bindings need, for crates
/// bridged by an older rust-anything; versions and features already set are kept.
fn with_template_deps(cargo: &str, template: &str) -> Result<String> {
let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
let template: toml_edit::DocumentMut = template.parse().context("Cargo.toml template")?;
if let Some(want) = template.get("dependencies").and_then(|d| d.as_table()) {
let deps = doc["dependencies"].or_insert(toml_edit::table());
for (name, item) in want {
if deps.get(name).is_none() {
deps[name] = item.clone();
}
}
}
if let Some(want) = template.get("features").and_then(|d| d.as_table()) {
let features = doc["features"].or_insert(toml_edit::table());
for (name, item) in want {
if features.get(name).is_none() {
features[name] = item.clone();
}
}
}
if let Some(kinds) = template.get("lib").and_then(|l| l.get("crate-type")) {
doc["lib"]["crate-type"] = kinds.clone();
}
Ok(doc.to_string())
}
/// The global allocator of a crate, if it sets one: crates with batches allocate from all cores
/// at once (the system allocator serializes them: 1.6x on 4 cores instead of 3.2x). mimalloc
/// leaves wasm alone, which runs on one thread; rusty_alloc also replaces Rust's wasm allocator.
/// Only Rust code uses this heap; every buffer that crosses the bridge is copied or freed by Rust.
fn global_allocator(m: &Manifest) -> Option<Allocator> {
if m.batches.is_empty() {
return None;
}
match m.allocator {
Allocator::Mimalloc if m.kind == Kind::Wasm => None,
a => Some(a),
}
}
/// `lib.rs` with the [`global_allocator`].
fn with_allocator(m: &Manifest, lib: String) -> String {
let line = match global_allocator(m) {
None => return lib,
Some(Allocator::Mimalloc) => {
"/// Batches allocate on all cores at once; mimalloc keeps that from serializing.\n\
#[global_allocator]\nstatic GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;\n"
}
Some(Allocator::RustyAlloc) => {
"/// Batches allocate on all cores at once; rusty_alloc keeps that from serializing.\n\
#[global_allocator]\n\
static GLOBAL: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;\n"
}
};
lib.replacen("pub mod port;", &format!("pub mod port;\n\n{line}"), 1)
}
/// Cargo.toml with rayon (and the global allocator) when batches run on all cores.
fn with_rayon(m: &Manifest, cargo: String) -> Result<String> {
let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
let deps = doc["dependencies"].or_insert(toml_edit::table());
// Batch methods take their other parameters as napi values; structured ones need serde.
if m.kind == Kind::Napi
&& !m.batches.is_empty()
&& let Some(napi) = deps.get_mut("napi")
{
let mut table = toml_edit::InlineTable::new();
match napi {
toml_edit::Item::Value(toml_edit::Value::String(v)) => {
table.insert("version", v.value().clone().into());
}
toml_edit::Item::Value(toml_edit::Value::InlineTable(t)) => table = t.clone(),
_ => {}
}
let mut features = table
.get("features")
.and_then(|f| f.as_array())
.cloned()
.unwrap_or_default();
if !features.iter().any(|f| f.as_str() == Some("serde-json")) {
features.push("serde-json");
}
table.insert("features", toml_edit::Value::Array(features));
*napi = toml_edit::value(table);
}
if !crate::codegen_batch::needs_rayon(m) {
return Ok(doc.to_string());
}
if deps.get("rayon").is_none() {
deps["rayon"] = toml_edit::value("1");
}
let allocator = match global_allocator(m) {
Some(Allocator::Mimalloc) => Some(("mimalloc", "0.1")),
Some(Allocator::RustyAlloc) => Some(("rusty_alloc-api", "2.6")),
None => None,
};
if let Some((name, version)) = allocator
&& deps.get(name).is_none()
{
deps[name] = toml_edit::value(version);
}
Ok(doc.to_string())
}
/// The language-side loader: `index.cjs` for JS, the wrapper package for Python.
fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
match m.kind {
Kind::Pyo3 => (
format!("python/{}/__init__.py", m.lib_name()),
crate::codegen_py::package_init(m, api),
),
_ => (
"index.cjs".into(),
codegen::index_cjs(m, api)
+ &crate::codegen_tswire::index_cjs(m, api)
+ &crate::codegen_batch::index_cjs(m, api)
+ &codegen::guard_cjs(api, &crate::codegen_tswire::wired(m, api)),
),
}
}
/// A port function whose doc line does not name an export (`/// Port of \`Integer.toString\``)
/// takes the name of the export it was generated for, matched by its Rust name. One that matches
/// no export and has no doc name keeps its Rust name in Python and Ruby, whose callers write
/// snake_case, instead of the camelCase default. Python's loader has `_names` of its own, so a
/// helper named like one keeps the default there.
pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
let python = m.language == crate::lang::Lang::Python;
let snake = python || m.language == crate::lang::Lang::Ruby;
for f in &mut api.functions {
if m.exports.iter().any(|e| e.name == f.js_name) {
continue;
}
let rust = f.rust_name.trim_start_matches("r#");
if let Some(e) = m
.exports
.iter()
.find(|e| snake_case(&e.name).trim_start_matches("r#") == rust)
{
f.js_name = e.name.clone();
} else if snake
&& !api.doc_named.contains(&f.rust_name)
&& !(python && rust.starts_with('_'))
{
f.js_name = rust.to_string();
}
}
}
/// The Rust names of the port functions that match no export of the original.
fn not_exports(m: &Manifest, api: &codegen::PortApi) -> Vec<String> {
api.functions
.iter()
.filter(|f| !m.exports.iter().any(|e| e.name == f.js_name))
.map(|f| f.rust_name.clone())
.collect()
}
/// What `refresh` rewrote.
#[derive(Debug, Serialize)]
pub struct Refreshed {
pub functions: Vec<String>,
pub files: Vec<String>,
/// Bound functions that match no export of the original, by Rust name: a `pub` helper in
/// `port.rs` that is now part of the bridged API.
pub not_exports: Vec<String>,
}
/// Regenerates the binding layer (`lib.rs`, `index.cjs`, `js.rs`) from the signatures in
/// `port.rs`, and adds the dependencies they need to Cargo.toml. Never touches `port.rs`.
pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
let manifest = Manifest::load(crate_dir)?;
if manifest.kind == Kind::CAbi {
let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
.context("reading src/port.rs")?;
let mut files = c_bindings(&manifest, &port);
let cargo =
std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
files.push((
"Cargo.toml".into(),
with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
));
write_files(crate_dir, &files)?;
format_rust(crate_dir);
return Ok(Refreshed {
functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
files: files.into_iter().map(|(p, _)| p).collect(),
not_exports: Vec::new(),
});
}
if manifest.kind == Kind::Ffi {
let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
.context("reading src/port.rs")?;
let mut api = codegen::parse_port(&port);
match_export_names(&manifest, &mut api);
let mut files = ffi_bindings(&manifest, &api)?;
let cargo =
std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
let template = if manifest.language == crate::lang::Lang::Ruby {
crate::codegen_ruby::cargo_toml(&manifest)
} else {
crate::codegen_ffi::cargo_toml(&manifest)
};
let cargo = with_template_deps(&cargo, &template)?;
files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
write_files(crate_dir, &files)?;
format_rust(crate_dir);
format_wrapper(crate_dir);
return Ok(Refreshed {
functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
files: files.into_iter().map(|(p, _)| p).collect(),
not_exports: not_exports(&manifest, &api),
});
}
let port =
std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
let mut fns = codegen::parse_port(&port);
match_export_names(&manifest, &mut fns);
if fns.functions.is_empty() && fns.classes.is_empty() {
bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
}
let modules = codegen::Modules {
utf16: crate_dir.join("src/utf16.rs").exists(),
js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
};
let mut files: Vec<(String, String)> = vec![
("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
loader_file(&manifest, &fns),
];
if modules.js {
files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
}
if crate::codegen_tswire::uses_wire(&manifest, &fns) {
files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
}
let extension = manifest.kind == Kind::Pyo3
|| (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
if extension && !crate_dir.join("build.rs").exists() {
files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
}
if manifest.kind == Kind::Pyo3 && fns.needs_json() {
files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
}
let cargo_path = crate_dir.join("Cargo.toml");
let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns, modules.js)
.map_err(anyhow::Error::msg)?;
let cargo = with_rayon(&manifest, cargo)?;
files.push(("Cargo.toml".into(), cargo));
write_files(crate_dir, &files)?;
format_rust(crate_dir);
Ok(Refreshed {
functions: fns
.functions
.iter()
.map(|f| f.js_name.clone())
.chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
.collect(),
files: files.into_iter().map(|(p, _)| p).collect(),
not_exports: not_exports(&manifest, &fns),
})
}
/// `build.rs` for Python and Ruby extensions: on macOS the library (and its test binary) links
/// against symbols the interpreter provides only at load time.
pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
}
}
"#;
/// Rejects Cargo package names that would produce invalid `Cargo.toml` / Rust library names or
/// write outside `<root>/rust/` via path separators.
fn validate_crate_name(name: &str) -> Result<&str> {
const RUST_KEYWORDS: &[&str] = &[
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
"extern", "false", "fn", "for", "gen", "if", "impl", "in", "let", "loop", "match", "mod",
"move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super",
"trait", "true", "type", "unsafe", "use", "where", "while", "abstract", "become", "box",
"do", "final", "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
];
const WINDOWS_RESERVED: &[&str] = &[
"con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",
"com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
];
let first = name.bytes().next();
let valid_chars = first.is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
if !valid_chars {
bail!(
"invalid crate name `{name}`: must be non-empty, start with an ASCII letter or `_`, \
and use only ASCII letters, digits, `-` and `_`"
);
}
let lib = name.replace('-', "_");
if lib == "_" || RUST_KEYWORDS.contains(&lib.as_str()) {
bail!("invalid crate name `{name}`: `{lib}` is a reserved Rust keyword");
}
let lower = name.to_ascii_lowercase();
if WINDOWS_RESERVED.contains(&lower.as_str()) {
bail!("invalid crate name `{name}`: `{name}` is a reserved filename on Windows");
}
Ok(name)
}
/// Derives a valid Cargo crate name from a unit's file/folder stem.
fn default_crate_name(stem: &str) -> String {
let clean: String = stem
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
let trimmed = clean.trim_matches('-');
if trimmed.is_empty() {
"unit-rs".to_string()
} else if trimmed.as_bytes()[0].is_ascii_digit() {
format!("unit-{trimmed}-rs")
} else {
format!("{trimmed}-rs")
}
}
pub fn bridge(opts: &Options) -> Result<Outcome> {
let explicit_name = opts.name.as_deref().map(validate_crate_name).transpose()?;
let root = crate::walk::resolve_root(opts.root)?;
let lang = opts
.lang
.unwrap_or_else(|| crate::lang::Lang::detect(&root));
let report = analyze::analyze_lang(&root, lang)?;
let wanted = opts.unit.trim_start_matches("./");
let whole = report
.units
.iter()
.find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'));
let single = || {
report
.units
.iter()
.find(|u| u.files.iter().any(|f| f == wanted))
.map(|u| {
let mut one = u.clone();
one.id = wanted.to_string();
one.files = vec![wanted.to_string()];
// Only the selected file's own errors count when it is bridged on its own.
one.parse_errors = usize::from(u.parse_error_files.iter().any(|f| f == wanted));
one.parse_error_files.retain(|f| f == wanted);
one
})
};
let unit = match whole.cloned().or_else(single) {
Some(unit) => unit,
None => bail!(
"no unit or source file `{wanted}`; `rust-anything analyze` lists unit ids, and any \
source file inside a unit can be bridged on its own"
),
};
let unit = &unit;
if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
bail!(
"unit `{}` is {}: {}. Pass --force to bridge it anyway.",
unit.id,
unit.status.label(),
unit.notes.first().map_or("", String::as_str)
);
}
// A syntax error can hide the functions after it, or mangle one: the export list below would
// be shorter than the file's, and nothing else says so.
if unit.parse_errors > 0 && !opts.force {
bail!(
"unit `{}` has {} (a syntax error, or a file that is not UTF-8): its export list may \
miss functions that follow the error. Fix the syntax or save the file as UTF-8 (run \
`rust-anything analyze` to see where), or pass --force to bridge only what was read.",
unit.id,
crate::report::count(unit.parse_errors, "parse error"),
);
}
if let Some(k @ (Kind::Napi | Kind::Wasm)) = opts.kind
&& lang != crate::lang::Lang::Ts
{
bail!(
"--kind {} is for TS/JS units; {wanted} is {} and is bridged with {}",
if k == Kind::Napi { "napi" } else { "wasm" },
lang.name(),
Bridge::for_lang(lang).label()
);
}
let kind = opts.kind.unwrap_or(match unit.bridge {
Bridge::WasmBindgen => Kind::Wasm,
Bridge::Pyo3 => Kind::Pyo3,
Bridge::CAbi => Kind::CAbi,
Bridge::Cgo
| Bridge::Magnus
| Bridge::Jni
| Bridge::PhpFfi
| Bridge::DotnetFfi
| Bridge::PwshFfi
| Bridge::SwiftFfi => Kind::Ffi,
_ => Kind::Napi,
});
if !opts.batch.is_empty() {
ensure_batch_support(lang, kind)?;
}
let mut exports = Vec::new();
let mut classes = Vec::new();
let mut js_only = Vec::new();
// Type parameters the exports declare, so an `--as-json` name none of them uses is refused.
let mut type_params = Vec::new();
// Name and file of each overloaded function already kept, so its other overloads join it.
let mut kept_overloads = std::collections::HashSet::new();
if lang == crate::lang::Lang::C {
crate::lang::c::use_typedefs(&root);
}
if lang == crate::lang::Lang::Csharp {
crate::lang::csharp::use_shapes(&root);
}
let mut foreign = Vec::new();
let mut php_functions = Vec::new();
// The files of a unit share barrels and workspace packages: parse each once.
let mut type_cache = TypeCache::default();
for file in &unit.files {
if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
continue;
}
let text =
std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
if lang != crate::lang::Lang::Ts {
let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
if lang == crate::lang::Lang::Php {
php_functions.extend(functions);
} else {
foreign.extend(functions.iter().cloned());
for f in functions {
// The overloads of one name (Java, Kotlin, C#) stay in the original together:
// one name in one file, not two exports that would replace each other, whether
// they stay for being overloaded or because `--keep` names them.
let overload = f.blocker.as_deref() == Some(crate::lang::OVERLOADED);
match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
Some(_)
if overload
&& !kept_overloads.insert((f.name.clone(), f.file.clone())) => {}
Some(reason) => js_only.push(JsOnly {
name: f.name,
file: f.file,
line: f.line,
reason,
}),
None => exports.push(f),
}
}
}
for class in foreign_classes {
match keep_reason(&opts.keep, &class.name)
.or_else(|| class_reason(&class, &[], false))
{
Some(reason) => js_only.push(JsOnly {
name: class.name,
file: class.file,
line: class.line,
reason: format!("class: {reason}"),
}),
None => classes.push(class),
}
}
continue;
}
let types = types_in_scope_cached(&root, file, &text, &mut type_cache);
let aliases = AliasIndex::new(&types);
for mut class in exported_classes(file, &text) {
let kept = keep_reason(&opts.keep, &class.name);
match kept.or_else(|| class_reason(&class, &types, true)) {
Some(reason) => js_only.push(JsOnly {
name: class.name,
file: class.file,
line: class.line,
reason: format!("class: {reason}"),
}),
None => {
for p in &mut class.constructor {
p.ts_type = resolve_aliases_with(&p.ts_type, &aliases);
}
for m in &mut class.methods {
for p in &mut m.params {
p.ts_type = resolve_aliases_with(&p.ts_type, &aliases);
}
m.returns = resolve_aliases_with(&m.returns, &aliases);
}
classes.push(class);
}
}
}
type_params.extend(declared_type_params(&root, file, &text));
for mut f in ts_functions(&root, file, &text, &types) {
substitute_json(&mut f, &opts.as_json);
let kept = keep_reason(&opts.keep, &f.name);
match kept.or_else(|| js_only_reason(&f, &types)) {
Some(reason) => js_only.push(JsOnly {
name: f.name,
file: f.file,
line: f.line,
reason,
}),
None => exports.push(f),
}
}
}
if lang == crate::lang::Lang::Php {
crate::lang::php::qualify_clashing_methods(&mut php_functions);
foreign.extend(php_functions.iter().cloned());
// A PHP class lives in one file: its methods get their reasons together, so one method
// that stays keeps the whole class.
let mut planned: Vec<(ExportedFn, Option<String>)> = php_functions
.into_iter()
.map(|f| {
let reason = keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[]));
(f, reason)
})
.collect();
keep_php_classes_together(&mut planned);
for (f, reason) in planned {
match reason {
Some(reason) => js_only.push(JsOnly {
name: f.name,
file: f.file,
line: f.line,
reason,
}),
None => exports.push(f),
}
}
}
let outside = outside_state_calls(lang, &root, &mut None, &foreign);
for (f, reason) in foreign
.iter()
.zip(state_through_calls_with(&foreign, &outside))
{
let Some(reason) = reason else { continue };
if let Some(i) = exports
.iter()
.position(|e| e.name == f.name && e.file == f.file && e.line == f.line)
{
let f = exports.remove(i);
js_only.push(JsOnly {
name: f.name,
file: f.file,
line: f.line,
reason,
});
}
}
let mut defined: Vec<(&str, String)> = exports
.iter()
.map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
.chain(
classes
.iter()
.map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
)
.chain(
js_only
.iter()
.map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
)
.collect();
defined.sort();
check_keep(
&opts.keep,
&defined.iter().map(|(name, _)| *name).collect::<Vec<_>>(),
&unit.id,
)?;
if lang != crate::lang::Lang::Ts && !opts.as_json.is_empty() {
let tip = if lang == crate::lang::Lang::Python {
" The Python bridge already maps generic data to JSON values."
} else {
""
};
bail!(
"--as-json is for TS/JS units. {wanted} is {} and uses {}.{tip}",
lang.name(),
Bridge::for_lang(lang).label()
);
}
check_as_json(&opts.as_json, &type_params, &unit.id)?;
if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
bail!(
"`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
itself, so one would silently replace the other. Bridge the module you want on its \
own (`rust-anything bridge <root> <that file>`), or rename one of them",
pair[0].0,
unit.id,
pair[0].1,
pair[1].1
);
}
// The C ABI keeps the C names; every other kind names the port function `snake_case(name)`.
if kind != Kind::CAbi
&& let Some((a, b)) = rust_name_clash(&exports)
{
bail!(
"`{}` ({}:{}) and `{}` ({}:{}) both become `{}` in Rust, so the crate would define \
it twice. Keep one of them in {} with `--keep '{}'`, or bridge the file you want on its \
own (`rust-anything bridge <root> <that file>`)",
a.name,
a.file,
a.line,
b.name,
b.file,
b.line,
snake_case(&a.name),
lang.name(),
b.name
);
}
if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
bail!(
"every export of `{}` must stay in {}: {}",
unit.id,
lang.name(),
js_only
.iter()
.map(|j| format!("{} ({})", j.name, j.reason))
.collect::<Vec<_>>()
.join(", ")
);
}
if exports.is_empty() && classes.is_empty() {
bail!(
"unit `{}` exports no functions; bridge a unit with an exported function API",
unit.id
);
}
let stem = unit
.id
.trim_end_matches('/')
.rsplit('/')
.next()
.unwrap_or("unit")
.split('.')
.next()
.unwrap_or("unit");
let crate_name = explicit_name
.map(str::to_string)
.unwrap_or_else(|| default_crate_name(stem));
let crate_dir = opts
.out
.clone()
.unwrap_or_else(|| root.join("rust").join(&crate_name));
if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
bail!(
"{dir} already exists and is not empty; rust-anything never overwrites a port in \
progress. Run `rust-anything refresh {arg}` to regenerate the bindings, pass --out or \
--name for a new crate, or remove the folder to start over",
dir = crate_dir.display(),
arg = crate::app::cli_path(&crate_dir)
);
}
// UTF-16 helpers matter for JS strings only; Python indexes code points, like `chars()`.
let utf16 =
lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
let manifest = Manifest {
schema: SCHEMA.into(),
root: root.clone(),
root_written: None,
unit: unit.id.clone(),
language: lang,
kind,
crate_name: crate_name.clone(),
exports: exports.clone(),
classes: classes.clone(),
js_only: js_only.clone(),
batches: parse_batches(&opts.batch)?,
allocator: opts.allocator,
float_tolerance: None,
ignore_key_order: false,
messages: false,
end_state: None,
};
// A crate inside its repository names the root relatively, so the committed manifest is
// the same in every clone and holds no path of this machine.
let mut on_disk = manifest.clone();
let absolute_dir = std::path::absolute(&crate_dir).unwrap_or_else(|_| crate_dir.clone());
let canonical_dir = absolute_dir
.ancestors()
.find_map(|a| Some(a.canonical().ok()?.join(absolute_dir.strip_prefix(a).ok()?)))
.unwrap_or_else(|| absolute_dir.clone());
if let Some(relative) = relative_root(
&canonical_dir,
&root.canonical().unwrap_or_else(|_| root.clone()),
) {
on_disk.root = relative;
}
if kind == Kind::CAbi {
return bridge_c(&manifest, &on_disk, &crate_dir, &js_only)
.map(|outcome| with_parse_warning(outcome, unit.parse_errors));
}
if kind == Kind::Ffi {
return bridge_ffi(&manifest, &on_disk, &crate_dir, &js_only)
.map(|outcome| with_parse_warning(outcome, unit.parse_errors));
}
let port = codegen::port_rs(&manifest);
let fns = codegen::parse_port(&port);
let modules = codegen::Modules {
utf16,
js: needs_js(&fns),
};
let mut files: Vec<(String, String)> = vec![
(
"Cargo.toml".into(),
with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
),
("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
("src/port.rs".into(), port),
loader_file(&manifest, &fns),
(
".gitignore".into(),
"target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
),
("README.md".into(), readme(&manifest)),
(
MANIFEST.into(),
serde_json::to_string_pretty(&on_disk)? + "\n",
),
];
match kind {
Kind::Napi => files.push((
"build.rs".into(),
"fn main() {\n napi_build::setup();\n}\n".into(),
)),
Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
_ => {}
}
if utf16 {
files.push(("src/utf16.rs".into(), UTF16_RS.into()));
}
if modules.js {
files.push(("src/js.rs".into(), codegen::JS_RS.into()));
}
if crate::codegen_tswire::uses_wire(&manifest, &fns) {
files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
}
if manifest.kind == Kind::Pyo3 && fns.needs_json() {
files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
}
write_files(&crate_dir, &files)?;
format_rust(&crate_dir);
let mut notes = vec![format!(
"Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
crate::app::cli_path(&crate_dir)
)];
if unit.parse_errors > 0 {
notes.push(parse_warning(unit.parse_errors));
}
if utf16 {
notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing. A substring that can cut a surrogate pair goes back to JS as a `serde_json::Value` built by `js::utf16_string(utf16::slice_units(..))`, not a `String` (run `refresh` after changing the signature).".into());
}
for j in &js_only {
notes.push(format!(
"`{}` stays in {}: {}. The shadow module re-exports the original.",
j.name,
lang.name(),
j.reason
));
}
if exports.iter().any(codegen::is_async) {
notes.push(
"Async TS functions are `async fn` in the port; the bindings return promises.".into(),
);
}
Ok(Outcome {
crate_dir,
kind,
files: files.into_iter().map(|(p, _)| p).collect(),
exports: exports
.iter()
.map(|f| f.name.clone())
.chain(classes.iter().map(|c| format!("class {}", c.name)))
.collect(),
notes,
})
}
fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
for (path, text) in files {
let target = crate_dir.join(path);
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
write_atomic(&target, text).with_context(|| format!("writing {}", target.display()))?;
}
Ok(())
}
/// Writes `text` to `path` through a temporary file and a rename, so a reader (cargo, the shared
/// build cache) never sees a half-written file.
fn write_atomic(path: &Path, text: &str) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(format!(".rust-anything.{}.{seq}.tmp", std::process::id()));
let tmp = path.with_file_name(name);
std::fs::write(&tmp, text)
.and_then(|()| std::fs::rename(&tmp, path))
.inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})
}
/// The generated C-side files: the `extern "C"` layer and its header. C signatures are fixed
/// by the original, so they come from the manifest, not from `port.rs`.
fn c_bindings(m: &Manifest, port: &str) -> Vec<(String, String)> {
vec![
("src/lib.rs".into(), crate::codegen_c::lib_rs(m, port)),
(
format!("include/{}.h", m.lib_name()),
crate::codegen_c::header(m),
),
]
}
/// The generated layers of a JSON-dispatcher crate: `lib.rs` and the language-side wrapper.
fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
let mut files = if m.language == crate::lang::Lang::Ruby {
vec![
(
"src/lib.rs".to_string(),
with_allocator(
m,
crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
),
),
(
"src/rbconv.rs".to_string(),
crate::codegen_ruby::RBCONV_RS.to_string(),
),
("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
]
} else {
let mut lib = crate::codegen_ffi::lib_rs(m, api);
if matches!(
m.language,
crate::lang::Lang::Java | crate::lang::Lang::Kotlin
) {
lib.push_str(&crate::codegen_java::typed_rs(m, api));
}
if m.language == crate::lang::Lang::Go {
lib.push_str(&crate::codegen_go::typed_rs(m, api));
lib.push_str(&crate::codegen_go::wire_rs(m, api));
lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
}
if matches!(
m.language,
crate::lang::Lang::Java | crate::lang::Lang::Kotlin
) {
lib.push_str(&crate::codegen_java::wire_rs(m, api));
lib.push_str(
&crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
);
}
if matches!(
m.language,
crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
) {
lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
}
let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
if matches!(
m.language,
crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
) {
files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
}
files
};
match m.language {
crate::lang::Lang::Go => {
// The wrapper package takes its name and types from the original sources: without
// them it would be written under a wrong name beside the old one.
if crate::codegen_go::unit_sources(m).is_empty() {
bail!(
"cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
m.unit,
m.root.display()
);
}
files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
files.push((
format!("go/{}.go", crate::codegen_go::package_name(m)),
crate::codegen_go::wrapper(m, api),
));
}
crate::lang::Lang::Ruby => {
files.push((
crate::harness_ruby::wrapper_path(m),
crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
));
}
crate::lang::Lang::Php => {
files.push((
crate::codegen_php::wrapper_path(m),
crate::codegen_php::wrapper(m, api),
));
}
crate::lang::Lang::Csharp => {
files.push((
crate::codegen_csharp::wrapper_path(m),
crate::codegen_csharp::wrapper(m, api),
));
}
crate::lang::Lang::Powershell => {
files.push((
crate::codegen_powershell::wrapper_path(m),
crate::codegen_powershell::wrapper(m),
));
}
crate::lang::Lang::Swift => {
files.push((
crate::codegen_swift::wrapper_path(m),
crate::codegen_swift::wrapper(m),
));
files.extend(crate::codegen_swift::module_files(m));
}
crate::lang::Lang::Java | crate::lang::Lang::Kotlin => {
files.extend(crate::codegen_java::wrappers(m, api));
files.extend(
crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
);
files.push((
format!(
"java/rustanything/{}.java",
crate::codegen_ffi::java_native_class(m)
),
crate::codegen_java::native_class(m, api),
));
files.push((
"java/rustanything/RustAnythingJson.java".into(),
crate::codegen_java::JSON_JAVA.into(),
));
files.push((
"java/rustanything/RustAnythingWire.java".into(),
crate::codegen_java::WIRE_JAVA.into(),
));
files.push((
"java/rustanything/RustAnythingError.java".into(),
crate::codegen_java::ERROR_JAVA.into(),
));
}
other => bail!("no wrapper generator for {}", other.name()),
}
Ok(files)
}
fn bridge_ffi(
manifest: &Manifest,
on_disk: &Manifest,
crate_dir: &Path,
kept: &[JsOnly],
) -> Result<Outcome> {
let port = codegen::port_rs(manifest);
let api = codegen::parse_port(&port);
let mut files = vec![
(
"Cargo.toml".to_string(),
with_rayon(
manifest,
if manifest.language == crate::lang::Lang::Ruby {
crate::codegen_ruby::cargo_toml(manifest)
} else {
crate::codegen_ffi::cargo_toml(manifest)
},
)?,
),
("src/port.rs".into(), port),
(
".gitignore".into(),
"target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\ncs/*.so\ncs/*.dylib\ncs/*.dll\nps/*.so\nps/*.dylib\nps/*.dll\nswift/*.so\nswift/*.dylib\nswift/*.dll\n".into(),
),
("README.md".into(), readme(manifest)),
(
MANIFEST.into(),
serde_json::to_string_pretty(on_disk)? + "\n",
),
];
files.extend(ffi_bindings(manifest, &api)?);
write_files(crate_dir, &files)?;
format_rust(crate_dir);
format_wrapper(crate_dir);
let mut notes = vec![format!(
"Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
crate::app::cli_path(crate_dir)
)];
for j in kept {
notes.push(format!(
"`{}` stays in {}: {}.",
j.name,
manifest.language.name(),
j.reason
));
}
Ok(Outcome {
crate_dir: crate_dir.to_path_buf(),
kind: Kind::Ffi,
files: files.into_iter().map(|(p, _)| p).collect(),
exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
notes,
})
}
/// What a forced bridge of a unit with parse errors says: the export list may be short.
fn parse_warning(parse_errors: usize) -> String {
format!(
"Warning: this unit has {}, so the exports above are only the ones that were read: \
functions after the error may be missing.",
crate::report::count(parse_errors, "parse error")
)
}
/// `outcome` with the warning about a unit's parse errors, when it has any.
fn with_parse_warning(mut outcome: Outcome, parse_errors: usize) -> Outcome {
if parse_errors > 0 {
outcome.notes.push(parse_warning(parse_errors));
}
outcome
}
fn bridge_c(
manifest: &Manifest,
on_disk: &Manifest,
crate_dir: &Path,
kept: &[JsOnly],
) -> Result<Outcome> {
let mut files = vec![
(
"Cargo.toml".to_string(),
crate::codegen_c::cargo_toml(manifest),
),
("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
(
".gitignore".into(),
"target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\n".into(),
),
("README.md".into(), readme(manifest)),
(
MANIFEST.into(),
serde_json::to_string_pretty(on_disk)? + "\n",
),
];
let port = crate::codegen_c::port_rs(manifest);
files.extend(c_bindings(manifest, &port));
write_files(crate_dir, &files)?;
format_rust(crate_dir);
let mut notes = vec![
format!(
"Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
crate::app::cli_path(crate_dir)
),
format!(
"Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
manifest.lib_name(),
manifest.lib_name()
),
];
for j in kept {
notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
}
// Issue #1198: the library has the bridged functions only, and the C objects it replaces
// also hold what stays.
if let Some(note) = kept_cut_over(kept, "C", Some("link the Rust library")) {
notes.push(format!("{note}."));
}
Ok(Outcome {
crate_dir: crate_dir.to_path_buf(),
kind: Kind::CAbi,
files: files.into_iter().map(|(p, _)| p).collect(),
exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
notes,
})
}
/// `a`, `b` and `c`: each item once, in backticks, in the order given.
fn backticked(items: impl Iterator<Item = impl AsRef<str>>) -> (String, usize) {
let mut seen: Vec<String> = Vec::new();
for item in items {
let item = format!("`{}`", item.as_ref());
if !seen.contains(&item) {
seen.push(item);
}
}
let text = match seen.split_last() {
Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),
_ => seen.concat(),
};
(text, seen.len())
}
/// What to do about the functions that stay in the original language where the generated wrapper
/// (PHP, Swift) or library (C) takes the place of the original file: it defines the bridged
/// functions only, so what stays has to move out of that file first, or it is gone from the app
/// (issue #1198). `step` is what the user does next ("require `php/x.php`"); without one the
/// sentence ends in "first". Nothing kept gives `None`.
pub fn kept_cut_over(kept: &[JsOnly], original: &str, step: Option<&str>) -> Option<String> {
if kept.is_empty() {
return None;
}
let (names, count) = backticked(kept.iter().map(|j| &j.name));
let (files, file_count) = backticked(kept.iter().map(|j| &j.file));
let (stays, it) = if count == 1 {
("stays", "it")
} else {
("stay", "them")
};
let (a_file, place) = if file_count == 1 {
("a file", "its place")
} else {
("files", "their place")
};
let end = match step {
Some(step) => format!("before you {step} in {place}"),
None => "first".into(),
};
Some(format!(
"{names} {stays} in {original}: move {it} out of {files} into {a_file} you keep {end}"
))
}
/// The line a PHP or Swift wrapper's header gets for [`kept_cut_over`]: the names that stay in
/// the original, so it is visible in the file that replaces it. Empty when nothing stays.
pub fn kept_header(kept: &[JsOnly], original: &str) -> String {
if kept.is_empty() {
return String::new();
}
let (names, _) = backticked(kept.iter().map(|j| &j.name));
format!(
"// Kept in {original} and not defined here: {names}. Move what is kept out of the original \
before this file replaces it.\n"
)
}
fn readme(m: &Manifest) -> String {
use crate::lang::Lang;
let section = |heading: &str, items: Vec<(&str, &str, u32)>| -> String {
if items.is_empty() {
return String::new();
}
let list: String = items
.iter()
.map(|(name, file, line)| format!("- `{name}` (`{file}:{line}`)\n"))
.collect();
format!("## {heading}\n\n{list}\n")
};
let listing = section(
"Functions",
m.exports
.iter()
.map(|f| (f.name.as_str(), f.file.as_str(), f.line))
.collect(),
) + §ion(
"Classes",
m.classes
.iter()
.map(|c| (c.name.as_str(), c.file.as_str(), c.line))
.collect(),
);
let original = match m.language {
Lang::Ts => "TS",
other => other.name(),
};
let kept: String = m
.js_only
.iter()
.map(|j| format!("- `{}` (`{}:{}`): {}\n", j.name, j.file, j.line, j.reason))
.collect();
let listing = if kept.is_empty() {
listing
} else {
format!("{listing}## Kept in {original}\n\n{kept}\n")
};
let module = match m.kind {
Kind::Napi => "napi-rs module",
Kind::Wasm => "wasm-bindgen module",
Kind::Pyo3 => "PyO3 module",
Kind::CAbi => "C library",
Kind::Ffi => "shared library",
};
let shadow = match m.language {
Lang::Php | Lang::Csharp | Lang::Powershell | Lang::Swift => String::new(),
_ => "rust-anything shadow . # run both in the app, log mismatches\n".into(),
};
// Issue #1198: the wrapper replaces the original file, so what stays there has to move first.
let kept_step = |step: &str| -> String {
kept_cut_over(&m.js_only, original, Some(step))
.map(|note| format!("{note}.\n"))
.unwrap_or_default()
};
let switch = match m.language {
Lang::Php => format!(
"\nPHP has no shadow module: once `diff` passes, require `{}` in place of the original files.\n{}",
crate::codegen_php::wrapper_path(m),
kept_step(&format!(
"require `{}`",
crate::codegen_php::wrapper_path(m)
))
),
Lang::Powershell => format!(
"\nPowerShell has no shadow module: once `diff` passes, `rust-anything enable .` \
dot-sources `{}` at the end of the original file, so every caller (the module's own \
functions too) gets Rust. Most slow PowerShell is the start-up of a new `pwsh` per \
command, which no port fixes: keep one shell open and call into it.\n",
crate::codegen_powershell::wrapper_path(m)
),
Lang::Csharp => format!(
"\nC# has no shadow module: once `diff` passes, compile `{}` into the project and call \
the {} classes, with the built library next to the app.\n",
crate::codegen_csharp::wrapper_path(m),
crate::codegen_csharp::rust_namespaces_text(m)
),
Lang::Swift => format!(
"\nSwift has no shadow module: once `diff` passes, compile `{}` into the target in place \
of the original file, with `swift/` on the import path (`-I swift`) and the built \
library on the link path (`-L swift`). A Rust panic stops the program, as a Swift \
trap does.\n{}",
crate::codegen_swift::wrapper_path(m),
kept_step(&format!(
"compile `{}`",
crate::codegen_swift::wrapper_path(m)
))
),
_ => String::new(),
};
format!(
"# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n{listing}\
## Loop\n\n```sh\nrust-anything record . # record what the {original} code does\nrust-anything build . # build the {module}\n\
rust-anything diff . # run the recorded cases against Rust\n{shadow}\
rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n```\n{switch}",
name = m.crate_name,
unit = m.unit,
kind = m.kind.label(),
)
}
const UTF16_RS: &str = r#"//! JS string indexing in Rust.
//!
//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
#![forbid(unsafe_code)]
/// The UTF-16 code units of `s`, as JS sees the string.
pub fn units(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
/// The string `units[start..end]` decodes to. Unlike JS `slice`, a cut surrogate pair becomes
/// U+FFFD: to hand a substring back to JS exactly, keep `slice_units` and return it through
/// `js::utf16_string` (a `serde_json::Value`), which carries a lone surrogate as JS has it.
pub fn slice(units: &[u16], start: usize, end: usize) -> String {
String::from_utf16_lossy(slice_units(units, start, end))
}
/// JS `slice` on code units, exactly: `units[start..end]`, clamped to the string, a lone
/// surrogate kept.
pub fn slice_units(units: &[u16], start: usize, end: usize) -> &[u16] {
let end = end.min(units.len());
let start = start.min(end);
&units[start..end]
}
/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
let from = from.min(haystack.len());
if needle.is_empty() {
return Some(from);
}
haystack[from..]
.windows(needle.len())
.position(|w| w == needle)
.map(|i| i + from)
}
/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
if needle.is_empty() {
return Some(haystack.len());
}
haystack.windows(needle.len()).rposition(|w| w == needle)
}
/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
let mut seen = 0;
for (byte, c) in s.char_indices() {
if seen >= utf16_offset {
return byte;
}
seen += c.len_utf16();
}
s.len()
}
/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
s[..byte_offset.min(s.len())].encode_utf16().count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_js_indexing() {
let s = units("a👍b");
assert_eq!(s.len(), 4);
assert_eq!(index_of(&s, &units("b"), 0), Some(3));
assert_eq!(last_index_of(&s, &units("a")), Some(0));
assert_eq!(slice(&s, 3, 4), "b");
// A cut surrogate pair: JS keeps the half, `slice_units` too, `slice` cannot.
assert_eq!(slice_units(&units("😀"), 0, 1), &[0xD83D]);
assert_eq!(slice(&units("😀"), 0, 1), "\u{FFFD}");
assert_eq!(byte_offset("a👍b", 3), 5);
assert_eq!(utf16_offset("a👍b", 5), 3);
}
}
"#;
#[cfg(test)]
mod tests {
use super::*;
fn manifest_json(extra: &str) -> String {
format!(
r#"{{"schema":"{SCHEMA}","root":".","unit":"u","kind":"napi","crate_name":"u-rs","exports":[]{extra}}}"#
)
}
#[test]
fn a_manifest_written_before_end_states_has_none() {
let dir = std::env::temp_dir().join(format!("ra-end-none-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(MANIFEST), manifest_json("")).unwrap();
let m = Manifest::load(&dir).unwrap();
assert_eq!(m.end_state, None);
m.save(&dir).unwrap();
let saved = std::fs::read_to_string(dir.join(MANIFEST)).unwrap();
assert!(!saved.contains("end_state"), "{saved}");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn set_end_state_keeps_the_rest_of_the_manifest() {
let dir = std::env::temp_dir().join(format!("ra-end-set-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(MANIFEST),
manifest_json(r#","float_tolerance":0.001"#),
)
.unwrap();
set_end_state(&dir, EndState::Scaffold).unwrap();
let saved = std::fs::read_to_string(dir.join(MANIFEST)).unwrap();
assert!(saved.contains(r#""end_state": "scaffold""#), "{saved}");
assert!(saved.contains(r#""root": ".""#), "{saved}");
let m = Manifest::load(&dir).unwrap();
assert_eq!(m.end_state, Some(EndState::Scaffold));
assert_eq!(m.float_tolerance, Some(0.001));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn kind_labels_match_documentation() {
assert_eq!(Kind::Napi.label(), "napi-rs");
assert_eq!(Kind::Wasm.label(), "wasm-bindgen");
assert_eq!(Kind::Pyo3.label(), "PyO3");
assert_eq!(Kind::CAbi.label(), "the C ABI");
assert_eq!(Kind::Ffi.label(), "a JSON dispatcher");
}
#[test]
fn keep_entries_are_trimmed() {
let keep = |k: &[&str]| k.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(
keep_reason(&keep(&["add"]), "add").as_deref(),
Some("kept on request")
);
assert_eq!(
keep_reason(&keep(&[" add "]), "add").as_deref(),
Some("kept on request")
);
assert_eq!(
keep_reason(&keep(&[" add : slow in Rust "]), "add").as_deref(),
Some("slow in Rust")
);
assert_eq!(
keep_reason(&keep(&["add:"]), "add").as_deref(),
Some("kept on request")
);
assert_eq!(keep_reason(&keep(&["add"]), "sub"), None);
}
#[test]
fn unknown_keep_names_are_refused() {
let keep = |k: &str| vec![k.to_string()];
assert!(check_keep(&keep(" add : reason"), &["add", "Point"], "src/add.ts").is_ok());
assert!(check_keep(&keep("Point"), &["add", "Point"], "src/add.ts").is_ok());
let err = check_keep(&keep("nope"), &["sub", "add"], "src/add.ts")
.unwrap_err()
.to_string();
assert_eq!(
err,
"--keep `nope` is not an export of `src/add.ts` (exports: add, sub)"
);
}
#[test]
fn bridge_refuses_unknown_keep_name() {
let dir = crate::app::temp_dir("bridge-keep").unwrap();
std::fs::write(
dir.join("package.json"),
r#"{"name":"demo","version":"1.0.0"}"#,
)
.unwrap();
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(
dir.join("src/add.ts"),
"export function add(a: number, b: number): number { return a + b; }\n",
)
.unwrap();
let out = dir.join("rust/add-rs");
let err = bridge(&Options {
root: &dir,
unit: "src/add.ts",
kind: Some(Kind::Napi),
out: Some(out.clone()),
name: None,
force: false,
lang: None,
keep: vec!["nope".into()],
batch: vec![],
allocator: Allocator::default(),
as_json: vec![],
})
.unwrap_err();
assert!(
format!("{err:#}")
.contains("--keep `nope` is not an export of `src/add.ts` (exports: add)"),
"{err:#}"
);
assert!(!out.exists());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn bridge_refuses_as_json_for_python_units() {
let dir = crate::app::temp_dir("bridge-python-as-json").unwrap();
std::fs::write(
dir.join("gen.py"),
"from typing import TypeVar\nT = TypeVar('T')\n\
def first(xs: list[T]) -> T:\n return xs[0]\n",
)
.unwrap();
let run = |as_json, keep| {
bridge(&Options {
root: &dir,
unit: "gen.py",
kind: None,
out: None,
name: None,
force: false,
lang: None,
keep,
batch: vec![],
allocator: Allocator::default(),
as_json,
})
};
let refused = run(vec!["T".into()], vec![]);
let bad_keep = run(vec!["T".into()], vec!["missing".into()]);
let wrote_rust = dir.join("rust").exists();
let default = run(vec![], vec![]);
let port = std::fs::read_to_string(dir.join("rust/gen-rs/src/port.rs"));
std::fs::remove_dir_all(dir).unwrap();
let err = format!("{:#}", refused.unwrap_err());
assert!(err.contains("--as-json is for TS/JS units"), "{err}");
assert!(err.contains("gen.py is Python"), "{err}");
assert!(err.contains("JSON values"), "{err}");
assert!(!wrote_rust);
let err = format!("{:#}", bad_keep.unwrap_err());
assert!(err.contains("--keep `missing`"), "{err}");
assert!(default.is_ok(), "{default:?}");
assert!(port.unwrap().contains("Vec<serde_json::Value>"));
}
#[test]
fn bridge_refuses_an_as_json_name_that_is_not_a_type_parameter() {
let dir = crate::app::temp_dir("bridge-as-json").unwrap();
std::fs::write(
dir.join("package.json"),
r#"{"name":"demo","version":"1.0.0"}"#,
)
.unwrap();
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(
dir.join("src/math.ts"),
"export function add(a: number, b: number): number { return a + b; }\n\
export function first<T>(items: T[]): T { return items[0]; }\n",
)
.unwrap();
let out = dir.join("rust/math-rs");
let err = bridge(&Options {
root: &dir,
unit: "src/math.ts",
kind: Some(Kind::Napi),
out: Some(out.clone()),
name: None,
force: false,
lang: None,
keep: vec![],
batch: vec![],
allocator: Allocator::default(),
as_json: vec!["Q".into()],
})
.unwrap_err();
assert!(
format!("{err:#}").contains(
"--as-json `Q` is not a type parameter of `src/math.ts` (type parameters: T)"
),
"{err:#}"
);
assert!(!out.exists());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn as_json_counts_type_parameters_declared_on_overload_signatures() {
let root = std::env::temp_dir();
let names = declared_type_params(
&root,
"src/id.ts",
"export function identity<T>(x: T): T;\n\
export function identity(x: unknown): unknown { return x; }\n",
);
assert_eq!(names, vec!["T".to_string()]);
}
#[test]
fn bridge_accepts_as_json_for_a_type_parameter_its_constraint_resolved() {
// `T extends string` is resolved to `string` before the bridge sees the export, but the
// export still declares `T`, so naming it is not a typo.
let dir = crate::app::temp_dir("bridge-as-json-constrained").unwrap();
std::fs::write(
dir.join("package.json"),
r#"{"name":"demo","version":"1.0.0"}"#,
)
.unwrap();
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(
dir.join("src/id.ts"),
"export function identity<T extends string>(x: T): T { return x; }\n",
)
.unwrap();
let outcome = bridge(&Options {
root: &dir,
unit: "src/id.ts",
kind: Some(Kind::Napi),
out: Some(dir.join("rust/id-rs")),
name: None,
force: false,
lang: None,
keep: vec![],
batch: vec![],
allocator: Allocator::default(),
as_json: vec!["T".into()],
})
.unwrap();
assert!(
outcome.exports.iter().any(|e| e == "identity"),
"{:?}",
outcome.exports
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_crate_inside_its_repository_names_the_root_relatively() {
let root = Path::new("/work/repo");
let relative = |crate_dir: &str| relative_root(Path::new(crate_dir), root);
assert_eq!(
relative("/work/repo/rust/x-rs"),
Some(PathBuf::from("../.."))
);
assert_eq!(relative("/work/repo/x-rs"), Some(PathBuf::from("..")));
assert_eq!(
relative("/work/repo/a/b/c-rs"),
Some(PathBuf::from("../../.."))
);
// At the root itself, and outside it, there is nothing portable to write.
assert_eq!(relative("/work/repo"), Some(PathBuf::from(".")));
assert_eq!(relative("/elsewhere/x-rs"), None);
assert_eq!(relative("/work/repo-two/x-rs"), None);
assert_eq!(relative("/work/repo/../x-rs"), None);
}
#[test]
fn c_and_ffi_crates_inside_their_repository_name_the_root_relatively() {
let dir = crate::app::temp_dir("bridge-c-ffi-root").unwrap();
std::fs::write(
dir.join("add.c"),
"int add(int a, int b) { return a + b; }\n",
)
.unwrap();
std::fs::write(dir.join("go.mod"), "module example.com/pkg\n\ngo 1.22\n").unwrap();
std::fs::write(
dir.join("main.go"),
"package main\n\nfunc Add(a, b int) int { return a + b }\n",
)
.unwrap();
for (unit, lang, kind, out) in [
("add.c", crate::lang::Lang::C, Kind::CAbi, "rust/add-rs"),
(
"main.go",
crate::lang::Lang::Go,
Kind::Ffi,
"rust/go/main-rs",
),
] {
let outcome = bridge(&Options {
root: &dir,
unit,
kind: Some(kind),
out: Some(dir.join(out)),
name: None,
force: true,
lang: Some(lang),
keep: vec![],
batch: vec![],
allocator: Allocator::default(),
as_json: vec![],
})
.unwrap();
assert_eq!(outcome.kind, kind);
let written: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(dir.join(out).join(MANIFEST)).unwrap(),
)
.unwrap();
let depth = Path::new(out).components().count();
assert_eq!(written["root"], vec![".."; depth].join("/"), "{unit}");
}
std::fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
#[test]
fn saving_a_manifest_replaces_the_file_instead_of_truncating_it() {
let dir = crate::app::temp_dir("bridge-save-atomic").unwrap();
std::fs::write(
dir.join(MANIFEST),
r#"{"schema": "rust-anything/bridge@1", "root": ".", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
)
.unwrap();
let before = std::fs::read_to_string(dir.join(MANIFEST)).unwrap();
let mut reader = std::fs::File::open(dir.join(MANIFEST)).unwrap();
let mut m = Manifest::load(&dir).unwrap();
m.unit = "src/y.ts".into();
m.save(&dir).unwrap();
let mut seen = String::new();
std::io::Read::read_to_string(&mut reader, &mut seen).unwrap();
assert_eq!(seen, before, "a reader of the old file sees all of it");
assert!(
std::fs::read_to_string(dir.join(MANIFEST))
.unwrap()
.contains("src/y.ts")
);
let left: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().collect();
assert_eq!(left.len(), 1, "no temporary file is left");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_workspace_package_added_later_is_followed_by_the_next_run() {
let root = crate::app::temp_dir("bridge-ws-later").unwrap();
let write = |path: &str, text: &str| {
let path = root.join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
write("package.json", r#"{"name":"app","version":"1.0.0"}"#);
let text =
"import { Opts } from '@x/opts'\nexport function f(o: Opts): number { return o.n }\n";
write("src/f.ts", text);
let names = || -> Vec<String> {
types_in_scope(&root, "src/f.ts", text)
.into_iter()
.map(|t| t.name)
.collect()
};
assert!(names().is_empty());
write(
"packages/opts/package.json",
r#"{"name":"@x/opts","version":"1.0.0"}"#,
);
write(
"packages/opts/src/index.ts",
"export interface Opts { n: number }\n",
);
assert_eq!(names(), ["Opts"]);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let crate_dir = base.join("repo/rust/x-rs");
std::fs::create_dir_all(&crate_dir).unwrap();
std::fs::write(
crate_dir.join(MANIFEST),
r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
)
.unwrap();
let m = Manifest::load(&crate_dir).unwrap();
assert_eq!(m.root, base.join("repo").canonical().unwrap());
assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
// Written back, the file keeps the relative root.
let mut back = m.clone();
if let Some(w) = back.root_written.clone() {
back.root = w;
}
assert!(
serde_json::to_string(&back)
.unwrap()
.contains(r#""root":"../..""#)
);
std::fs::remove_dir_all(&base).unwrap();
}
#[test]
fn maps_ts_types() {
assert_eq!(RType::from_ts("string").rust(), "String");
assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
assert_eq!(
RType::from_ts("string | undefined").rust(),
"Option<String>"
);
assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
assert_eq!(
RType::from_ts("Map<string, number>").rust(),
"serde_json::Value"
);
assert_eq!(
RType::from_ts("string | number").rust(),
"serde_json::Value"
);
assert_eq!(
RType::from_ts("Record<string, string | number>").rust(),
"serde_json::Value"
);
assert_eq!(
RType::from_ts("(string | undefined)").rust(),
"Option<String>"
);
assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
}
#[test]
fn balanced_wants_parentheses_closed_in_order() {
assert!(balanced(""));
assert!(balanced("string | null"));
assert!(balanced("(a) | (b)"));
assert!(balanced("(() => void)"));
assert!(!balanced("(a))("));
assert!(!balanced("(a"));
}
#[test]
fn split_top_splits_outside_brackets_only() {
assert_eq!(split_top("string | null", '|'), ["string", "null"]);
assert_eq!(
split_top("Map<string, number> | null", '|'),
["Map<string, number>", "null"]
);
assert_eq!(
split_top("Map<string, number>, [a, b], {c: d}", ','),
["Map<string, number>", "[a, b]", "{c: d}"]
);
assert_eq!(split_top(" | a || ", '|'), ["a"]);
}
#[test]
fn split_top_does_not_close_a_bracket_at_an_arrow() {
assert_eq!(
split_top("(() => void) | null", '|'),
["(() => void)", "null"]
);
assert_eq!(
split_top("Map<string, () => number> | undefined", '|'),
["Map<string, () => number>", "undefined"]
);
assert_eq!(
RType::from_ts("(() => void) | null").rust(),
"Option<serde_json::Value>"
);
}
#[test]
fn rust_ident_escapes_keywords() {
for word in ["self", "Self", "super", "crate", "_"] {
assert_eq!(rust_ident(word), format!("{word}_"));
}
assert_eq!(rust_ident("type"), "r#type");
assert_eq!(rust_ident("async"), "r#async");
assert_eq!(rust_ident("name"), "name");
}
#[test]
fn keeps_unbridgeable_exports_in_js() {
let source = "export interface LineIndex {\n readonly lineCount: number\n position(offset: number): number\n}\n\
export interface Range { start: number, end: number }\n\
export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
export function globToRegExp(glob: string): RegExp { return /x/ }\n\
export function createLineIndex(text: string): LineIndex { return null! }\n\
export function* walk(tree: object) {}\n\
export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
export function contains(range: Range, offset: number): boolean { return true }\n";
let types = local_types("a.ts", source);
let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
.iter()
.map(|f| (f.name.clone(), js_only_reason(f, &types)))
.collect();
let js_only: Vec<&str> = reasons
.iter()
.filter(|(_, r)| r.is_some())
.map(|(n, _)| n.as_str())
.collect();
assert_eq!(
js_only,
[
"keyMatcher",
"globToRegExp",
"createLineIndex",
"walk",
"sortTree"
]
);
}
/// The scan `resolve_aliases` used to run: kept so a test can prove the index answers the same.
fn resolve_aliases_by_scan(ts: &str, types: &[LocalType]) -> String {
let mut out = ts.to_string();
for _ in 0..4 {
let mut changed = false;
let mut next = String::with_capacity(out.len());
let mut word = String::new();
let flush = |word: &mut String, next: &mut String, changed: &mut bool| {
if let Some(t) = types.iter().find(|t| t.alias && t.name == *word) {
let text = t.text.trim();
if text.contains('|') {
next.push('(');
next.push_str(text);
next.push(')');
} else {
next.push_str(text);
}
*changed = true;
} else {
next.push_str(word);
}
word.clear();
};
for c in out.chars() {
if c.is_alphanumeric() || c == '_' || c == '$' {
word.push(c);
} else {
flush(&mut word, &mut next, &mut changed);
next.push(c);
}
}
flush(&mut word, &mut next, &mut changed);
out = next;
if !changed {
break;
}
}
out
}
#[test]
fn the_index_answers_exactly_like_the_scan_it_replaces() {
// Issue #1032: the lookup has to stay the first alias of a name, over the same four passes,
// and must never substitute a type that is not an alias.
let types = local_types(
"m.ts",
"export type KeyString = string\n export type Leaf = string | null\n export type Wrapped = Leaf\n export type Chain = Wrapped\n export type Dup = number\n export type Dup = string\n export interface NotAlias { a: string }\n export type Gen<T> = T\n",
);
let index = AliasIndex::new(&types);
for ts in [
"KeyString",
"readonly KeyString[]",
"Leaf",
"(Leaf | KeyString)",
"Chain",
"Wrapped | Chain",
"Dup",
"NotAlias",
"Gen<KeyString>",
"unknown",
"",
"a.b.KeyString",
] {
assert_eq!(
resolve_aliases_with(ts, &index),
resolve_aliases_by_scan(ts, &types),
"{ts}"
);
}
// The index holds the aliases only, and a duplicated name once (the first one wins).
assert_eq!(index.len(), 5, "five alias names, `Dup` counted once");
assert!(!index.is_empty(), "the index is not empty for aliases");
assert!(AliasIndex::new(&[]).is_empty(), "and empty for none");
assert_eq!(
resolve_aliases_with("Dup", &index),
"number",
"the first `Dup` wins"
);
assert_eq!(resolve_aliases_with("NotAlias", &index), "NotAlias");
}
#[test]
fn resolves_simple_aliases() {
let types = local_types(
"m.ts",
"export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
);
assert_eq!(
resolve_aliases("readonly KeyString[]", &types),
"readonly string[]"
);
assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
}
#[test]
fn substitutes_simple_constraints() {
let found = exported_functions(
"a.ts",
"export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
export function pick<T>(x: T): T { return x }\n\
export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
);
let mut fns = found;
for f in &mut fns {
substitute_constraints(f, &[]);
}
assert_eq!(fns[0].params[0].ts_type, "(string)");
assert!(fns[0].type_params.is_empty());
assert_eq!(fns[1].type_params, ["T"]);
assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
}
#[test]
fn unknown_as_json_names_are_refused() {
let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert!(check_as_json(&names(&["T"]), &names(&["U", "T"]), "src/a.ts").is_ok());
let err = check_as_json(&names(&["Q"]), &names(&["U", "T", "T"]), "src/a.ts")
.unwrap_err()
.to_string();
assert_eq!(
err,
"--as-json `Q` is not a type parameter of `src/a.ts` (type parameters: T, U)"
);
let err = check_as_json(&names(&["T"]), &[], "src/a.ts")
.unwrap_err()
.to_string();
assert_eq!(
err,
"--as-json `T` is not a type parameter of `src/a.ts` (it has none)"
);
}
#[test]
fn as_json_bridges_a_data_generic() {
let mut fns = exported_functions(
"a.ts",
"export function paginate<T>(items: T[], page: number): { data: T[] } { return { data: items } }\n",
);
assert!(js_only_reason(&fns[0], &[]).is_some());
substitute_json(&mut fns[0], &["T".to_string()]);
assert!(fns[0].type_params.is_empty());
assert_eq!(fns[0].params[0].ts_type, "unknown[]");
assert_eq!(fns[0].returns, "{ data: unknown[] }");
assert!(js_only_reason(&fns[0], &[]).is_none());
}
#[test]
fn readme_fits_the_language() {
let manifest = |language: &str, kind: &str| -> Manifest {
serde_json::from_str(&format!(
r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "src/X.cs", "language": "{language}", "kind": "{kind}", "crate_name": "x-rs", "exports": []}}"#
))
.unwrap()
};
let ts = readme(&manifest("ts", "napi"));
assert!(ts.contains("what the TS code does") && ts.contains("build the napi-rs module"));
assert!(ts.contains("rust-anything shadow ."));
let c = readme(&manifest("c", "c-abi"));
assert!(c.contains("what the C code does") && c.contains("build the C library"));
let cs = readme(&manifest("csharp", "ffi"));
assert!(cs.contains("what the C# code does") && cs.contains("build the shared library"));
assert!(!cs.contains("rust-anything shadow") && cs.contains("C# has no shadow module"));
let php = readme(&manifest("php", "ffi"));
assert!(!php.contains("rust-anything shadow") && php.contains("PHP has no shadow module"));
}
#[test]
fn the_cut_over_line_names_what_stays_in_the_original() {
// Issue #1198: the wrapper replaces the original file, so a function kept there goes with it.
let manifest = |language: &str, unit: &str, kept: &[(&str, &str)]| -> Manifest {
let js_only: Vec<String> = kept
.iter()
.map(|(name, file)| {
format!(
r#"{{"name": "{name}", "file": "{file}", "line": 3, "reason": "variadic"}}"#
)
})
.collect();
serde_json::from_str(&format!(
r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "{unit}", "language": "{language}", "kind": "ffi", "crate_name": "text-rs", "exports": [], "js_only": [{}]}}"#,
js_only.join(", ")
))
.unwrap()
};
let php = readme(&manifest(
"php",
"src/text.php",
&[("total", "src/text.php")],
));
assert!(
php.contains(
"`total` stays in PHP: move it out of `src/text.php` into a file you keep before \
you require `php/text_rs.php` in its place.\n"
),
"{php}"
);
let swift = readme(&manifest(
"swift",
"Sources/Text",
&[
("total", "Sources/Text/Calc.swift"),
("mean", "Sources/Text/Calc.swift"),
("join", "Sources/Text/Words.swift"),
],
));
assert!(
swift.contains(
"`total`, `mean` and `join` stay in Swift: move them out of \
`Sources/Text/Calc.swift` and `Sources/Text/Words.swift` into files you keep \
before you compile `swift/TextRs.swift` in their place.\n"
),
"{swift}"
);
// Nothing kept: the line is as it was.
for (language, unit) in [("php", "src/text.php"), ("swift", "Sources/Text")] {
let plain = readme(&manifest(language, unit, &[]));
assert!(plain.contains("has no shadow module"), "{plain}");
assert!(!plain.contains("move"), "{plain}");
}
// A language with a shadow module re-exports what stays, so it gets no such line.
let ts = readme(&manifest("ts", "src/text.ts", &[("total", "src/text.ts")]));
assert!(ts.contains("## Kept in TS") && !ts.contains("move"), "{ts}");
}
fn local_type(name: &str, text: &str) -> LocalType {
LocalType {
name: name.into(),
text: text.into(),
alias: false,
}
}
#[test]
fn a_type_that_reaches_a_function_member_has_functions() {
let types = [
local_type("Plain", "interface Plain {\n id: number\n}"),
local_type(
"WithMethod",
"interface WithMethod {\n run(x: number): void\n}",
),
local_type(
"WithArrow",
"interface WithArrow {\n cb: (x: number) => void\n}",
),
// Mentions reach through other types, and a cycle ends.
local_type("Outer", "interface Outer {\n inner: Middle\n}"),
local_type(
"Middle",
"interface Middle {\n back: Outer\n leaf: WithMethod\n}",
),
local_type("LoopA", "interface LoopA {\n b: LoopB\n}"),
local_type("LoopB", "interface LoopB {\n a: LoopA\n self: LoopB\n}"),
// The first type of a name is the one that counts.
local_type("Twice", "interface Twice {\n id: number\n}"),
local_type("Twice", "interface Twice {\n run(): void\n}"),
];
let by_name = TypesByName::new(&types);
for (name, expected) in [
("Plain", false),
("WithMethod", true),
("WithArrow", true),
("Outer", true),
("Middle", true),
("LoopA", false),
("LoopB", false),
("Twice", false),
("string", false),
("Unknown", false),
] {
assert_eq!(by_name.has_functions(name), expected, "{name}");
}
}
#[test]
fn the_walk_counter_belongs_to_the_thread_that_walked() {
// Issue #1058's review: the count has to be per thread, and the test has to show it even when
// the storage is shared — so the main thread leaves its count pending while the child walks.
let types = vec![local_type("T0", "interface T0 {\n f: number\n}")];
let by_name = TypesByName::new(&types);
// How many steps this fixture costs in the main thread.
take_walk_steps();
assert!(!by_name.has_functions("T0"));
let mine = take_walk_steps();
assert!(mine > 0, "the fixture walks something");
// Start again and leave the counter pending: a shared counter would then hold the child's
// steps as well, and the final read would be larger than `mine`.
take_walk_steps();
assert!(!by_name.has_functions("T0"));
let child = std::thread::scope(|scope| {
scope
.spawn(|| {
take_walk_steps();
assert!(!by_name.has_functions("T0"));
take_walk_steps()
})
.join()
.unwrap()
});
assert!(child > 0, "the child counts its own steps");
assert_eq!(
take_walk_steps(),
mine,
"the main thread's count is its own: the child's {child} steps are not in it"
);
}
#[test]
fn has_functions_walks_each_type_once_per_size() {
let steps = |count: usize| {
let names: Vec<String> = (0..count).map(|i| format!("T{i}")).collect();
let types: Vec<LocalType> = names
.iter()
.map(|n| {
let body: Vec<String> = names.iter().map(|m| format!(" f{m}: {m}")).collect();
local_type(n, &format!("interface {n} {{\n{}\n}}", body.join("\n")))
})
.collect();
let by_name = TypesByName::new(&types);
take_walk_steps();
assert!(
!by_name.has_functions("T0"),
"no type has a function member"
);
take_walk_steps()
};
let small = steps(250);
let large = steps(1_000);
assert!(small >= 250, "250 types took only {small} steps");
assert!(small <= 3 * 250, "250 types took {small} steps");
assert!(large <= 3 * 1_000, "1,000 types took {large} steps");
assert!(
large <= 6 * small,
"1,000 types took {large} steps against {small} for 250: that is not linear"
);
}
#[test]
fn readme_lists_classes_and_writes_no_empty_heading() {
let export = r#"{"name": "add", "file": "a.ts", "line": 3, "params": [], "returns": "number", "is_async": false, "is_generator": false, "type_params": [], "uses_instanceof": false}"#;
let class = r#"{"name": "Counter", "file": "counter.ts", "line": 1, "constructor": [], "methods": [], "blocker": null}"#;
let readme_of = |exports: &str, classes: &str| {
readme(
&serde_json::from_str::<Manifest>(&format!(
r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "a.ts", "language": "ts", "kind": "napi", "crate_name": "a-rs", "exports": [{exports}], "classes": [{classes}]}}"#
))
.unwrap(),
)
};
// Exports only: what the README was.
let fns = readme_of(export, "");
assert!(
fns.contains("## Functions\n\n- `add` (`a.ts:3`)\n\n## Loop"),
"{fns}"
);
assert!(!fns.contains("## Classes"), "{fns}");
// A class-only unit used to get `## Functions` with nothing under it.
let only = readme_of("", class);
assert!(
only.contains("## Classes\n\n- `Counter` (`counter.ts:1`)\n\n## Loop"),
"{only}"
);
assert!(!only.contains("## Functions"), "{only}");
// Both are listed.
let both = readme_of(export, class);
assert!(
both.contains("## Functions\n\n- `add` (`a.ts:3`)\n\n## Classes\n\n- `Counter`"),
"{both}"
);
// Neither: no heading with nothing under it.
let none = readme_of("", "");
assert!(
!none.contains("## Functions") && !none.contains("## Classes"),
"{none}"
);
assert!(none.contains("## Loop"), "{none}");
}
#[test]
fn files_sharing_an_import_closure_parse_it_once_and_get_the_same_types() {
let root = std::env::temp_dir().join(format!("ra-type-cache-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("src/types")).unwrap();
let write = |path: &str, text: &str| std::fs::write(root.join(path), text).unwrap();
// A barrel over two type files, and three files that import the barrel.
write(
"src/types/index.ts",
"export * from './a'\nexport * from './b'\n",
);
write("src/types/a.ts", "export interface A { x: number }\n");
write("src/types/b.ts", "export interface B { y: string }\n");
let importers = ["src/c1.ts", "src/c2.ts", "src/c3.ts"];
for file in importers {
write(
file,
"import { A } from './types'\nexport function f(a: A): number { return a.x }\n",
);
}
let mut cache = TypeCache::default();
for file in importers {
let text = std::fs::read_to_string(root.join(file)).unwrap();
let cached = types_in_scope_cached(&root, file, &text, &mut cache);
// Same types, in the same order, as without sharing.
assert_eq!(cached, types_in_scope(&root, file, &text), "{file}");
let names: Vec<&str> = cached.iter().map(|t| t.name.as_str()).collect();
assert_eq!(names, ["A", "B"], "{file}");
}
// Three importers, the barrel and its two files: six files, each parsed once. Parsing
// the closure per importer would make it twelve.
assert_eq!(cache.parses, 6);
assert_eq!(cache.files.len(), 6);
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn makes_rust_names() {
assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
assert_eq!(snake_case("type"), "r#type");
assert_eq!(snake_case("toURL"), "to_url");
assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
assert_eq!(snake_case("box"), "r#box");
assert_eq!(snake_case("yield"), "r#yield");
assert_eq!(snake_case("try"), "r#try");
assert_eq!(snake_case("self"), "self_");
assert_eq!(snake_case("Super"), "super_");
assert_eq!(snake_case("Str::length"), "str_length");
assert_eq!(snake_case("Arr::length"), "arr_length");
assert_eq!(snake_case("HTTPClient::getURL"), "http_client_get_url");
}
#[test]
fn validates_crate_names() {
for good in ["add-rs", "my_crate", "_helper", "Foo2", "a-1_b"] {
assert_eq!(validate_crate_name(good).unwrap(), good, "{good}");
}
for bad in [
"",
" ",
" add-rs ",
"foo bar",
"123-rs",
"-foo",
"../escape",
"a/b",
"a\\b",
"a\"b",
"café",
"_",
"fn",
"type",
"self",
"Self",
"gen",
"con",
"NUL",
] {
assert!(
validate_crate_name(bad).is_err(),
"expected error for {bad:?}"
);
}
}
#[test]
fn default_crate_name_is_always_valid_for_cargo() {
assert_eq!(default_crate_name("add"), "add-rs");
assert_eq!(default_crate_name("my_util"), "my-util-rs");
assert_eq!(default_crate_name("123"), "unit-123-rs");
assert_eq!(default_crate_name("---"), "unit-rs");
assert_eq!(default_crate_name(""), "unit-rs");
for stem in ["add", "my_util", "123", "---", "", "00-index", "café"] {
let name = default_crate_name(stem);
assert!(
validate_crate_name(&name).is_ok(),
"{stem:?} -> {name:?} should be a valid crate name"
);
}
}
fn php_method(name: &str, prototype: &str, reason: Option<&str>) -> ExportedFn {
ExportedFn {
name: name.into(),
prototype: Some(prototype.into()),
blocker: reason.map(str::to_string),
..Default::default()
}
}
#[test]
fn php_keeps_a_whole_class_when_one_method_stays() {
let count = |reason: Option<&str>| {
(
php_method("count", "App\\Words::count(int $x)", None),
reason.map(str::to_string),
)
};
let reset = |reason: Option<&str>| {
(
php_method("reset", "App\\Words::reset()", None),
reason.map(str::to_string),
)
};
let mut planned = vec![count(None), reset(Some("returns nothing"))];
keep_php_classes_together(&mut planned);
assert_eq!(
planned[0].1.as_deref(),
Some(
"`Words` has a method that stays in PHP (`reset`: returns nothing), so its static methods stay"
)
);
// The method that caused the class to stay keeps its own reason.
assert_eq!(planned[1].1.as_deref(), Some("returns nothing"));
// A class whose methods all stay keeps each method's own reason.
let mut planned = vec![count(Some("first")), reset(Some("second"))];
keep_php_classes_together(&mut planned);
assert_eq!(planned[0].1.as_deref(), Some("first"));
assert_eq!(planned[1].1.as_deref(), Some("second"));
// `--keep` on one method keeps its class and keeps the user's reason there.
let mut planned = vec![count(Some("kept by `--keep`")), reset(None)];
keep_php_classes_together(&mut planned);
assert_eq!(planned[0].1.as_deref(), Some("kept by `--keep`"));
assert!(
planned[1]
.1
.as_deref()
.is_some_and(|why| why.contains("`count`: kept by `--keep`")),
"{planned:?}"
);
}
#[test]
fn bridge_refuses_invalid_name_before_writing_anything() {
let out = std::env::temp_dir().join(format!("ra-bridge-bad-name-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&out);
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
for bad in ["../escape", "123bad", "", "fn"] {
let err = bridge(&Options {
root: &root,
unit: "packages/a/src/util.ts",
kind: Some(Kind::Napi),
out: Some(out.clone()),
name: Some(bad.to_string()),
force: false,
keep: Vec::new(),
lang: None,
batch: Vec::new(),
as_json: Vec::new(),
allocator: Allocator::default(),
})
.unwrap_err();
assert!(
format!("{err:#}").contains("invalid crate name"),
"{bad:?}: {err:#}"
);
assert!(
!out.exists(),
"refused --name {bad:?} must not create folder"
);
}
}
#[test]
fn php_clashing_static_methods_qualify_across_unit_and_keep_collision_guard() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/php-static-clash");
let dir = std::env::temp_dir().join(format!("ra-php-clash-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let outcome = bridge(&Options {
root: &root,
unit: "src/",
kind: None,
out: Some(dir.clone()),
name: Some("clash-rs".into()),
force: false,
keep: Vec::new(),
lang: None,
batch: Vec::new(),
as_json: Vec::new(),
allocator: Allocator::default(),
})
.unwrap();
assert_eq!(outcome.exports, ["Arr::length", "Str::length"]);
let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
assert!(
port.contains("pub fn arr_length(s: String) -> Result<i64, String>"),
"{port}"
);
assert!(
port.contains("pub fn str_length(s: String) -> Result<i64, String>"),
"{port}"
);
let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
assert!(
lib.contains("\"Str::length\"") && lib.contains("port::str_length"),
"{lib}"
);
assert!(
lib.contains("\"Arr::length\"") && lib.contains("port::arr_length"),
"{lib}"
);
let manifest = Manifest::load(&dir).unwrap();
let wrapper =
std::fs::read_to_string(dir.join(crate::codegen_php::wrapper_path(&manifest))).unwrap();
assert_eq!(
wrapper
.matches("public static function length(string $s)")
.count(),
2,
"{wrapper}"
);
assert!(wrapper.contains("call('Arr::length', [$s])"), "{wrapper}");
assert!(wrapper.contains("call('Str::length', [$s])"), "{wrapper}");
// `--keep Str::length` keeps Str in PHP while bridging Arr::length.
let kept_dir =
std::env::temp_dir().join(format!("ra-php-clash-keep-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&kept_dir);
let kept = bridge(&Options {
root: &root,
unit: "src/",
kind: None,
out: Some(kept_dir.clone()),
name: Some("clash-keep-rs".into()),
force: false,
keep: vec!["Str::length".into()],
lang: None,
batch: Vec::new(),
as_json: Vec::new(),
allocator: Allocator::default(),
})
.unwrap();
assert_eq!(kept.exports, ["Arr::length"]);
let kept_manifest = Manifest::load(&kept_dir).unwrap();
assert_eq!(kept_manifest.js_only.len(), 1);
assert_eq!(kept_manifest.js_only[0].name, "Str::length");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&kept_dir);
// A real Rust-name clash (`Str::length` vs top-level `str_length`) is still refused.
let clash_root =
std::env::temp_dir().join(format!("ra-php-rust-clash-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&clash_root);
std::fs::create_dir_all(clash_root.join("src")).unwrap();
std::fs::write(
clash_root.join("composer.json"),
r#"{"name":"acme/clash","autoload":{"files":["src/Str.php","src/Arr.php","src/top.php"]}}"#,
)
.unwrap();
std::fs::write(
clash_root.join("src/Str.php"),
"<?php\nfinal class Str {\n public static function length(string $s): int { return strlen($s); }\n}\n",
)
.unwrap();
std::fs::write(
clash_root.join("src/Arr.php"),
"<?php\nfinal class Arr {\n public static function length(string $s): int { return str_word_count($s); }\n}\n",
)
.unwrap();
std::fs::write(
clash_root.join("src/top.php"),
"<?php\nfunction str_length(string $s): int { return strlen($s); }\n",
)
.unwrap();
let err = bridge(&Options {
root: &clash_root,
unit: "src/",
kind: None,
out: Some(clash_root.join("out")),
name: Some("rust-clash-rs".into()),
force: false,
keep: Vec::new(),
lang: None,
batch: Vec::new(),
as_json: Vec::new(),
allocator: Allocator::default(),
})
.unwrap_err();
let _ = std::fs::remove_dir_all(&clash_root);
assert!(
format!("{err:#}").contains("both become `str_length` in Rust"),
"{err:#}"
);
}
}