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