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 Unit,
293 Vec(Box<RType>),
294 Opt(Box<RType>),
295 Json,
297}
298
299impl RType {
300 pub fn from_ts(ts: &str) -> Self {
301 let ts = ts.trim().trim_start_matches("readonly ").trim();
302 if let Some(inner) = ts.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
304 && balanced(inner)
305 {
306 return Self::from_ts(inner);
307 }
308 if let Some(inner) = ts
309 .strip_prefix("Promise<")
310 .and_then(|t| t.strip_suffix('>'))
311 {
312 return Self::from_ts(inner);
313 }
314 let parts = split_top(ts, '|');
315 if parts.len() > 1 {
316 let (nullish, rest): (Vec<&str>, Vec<&str>) = parts
317 .iter()
318 .partition(|p| matches!(p.trim(), "undefined" | "null" | "void"));
319 if rest.iter().all(|p| is_string_literal(p)) {
320 return Self::wrap_opt(Self::Str, !nullish.is_empty());
321 }
322 if rest.len() == 1 {
323 return Self::wrap_opt(Self::from_ts(rest[0]), !nullish.is_empty());
324 }
325 return Self::Json;
326 }
327 if let Some(inner) = ts.strip_suffix("[]") {
328 return Self::Vec(Box::new(Self::from_ts(
329 inner.trim_start_matches('(').trim_end_matches(')'),
330 )));
331 }
332 for wrapper in ["Array<", "ReadonlyArray<"] {
333 if let Some(inner) = ts.strip_prefix(wrapper).and_then(|t| t.strip_suffix('>')) {
334 return Self::Vec(Box::new(Self::from_ts(inner)));
335 }
336 }
337 if ts.starts_with("asserts ") {
339 return Self::Unit;
340 }
341 if let Some((subject, _)) = ts.split_once(" is ")
342 && subject
343 .trim()
344 .chars()
345 .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
346 {
347 return Self::Bool;
348 }
349 match ts {
350 "string" => Self::Str,
351 "number" => Self::F64,
352 "int" => Self::Int,
353 "boolean" => Self::Bool,
354 "void" | "undefined" => Self::Unit,
355 _ if is_string_literal(ts) => Self::Str,
356 _ => Self::Json,
357 }
358 }
359
360 fn wrap_opt(t: Self, optional: bool) -> Self {
361 if optional { Self::Opt(Box::new(t)) } else { t }
362 }
363
364 pub fn rust(&self) -> String {
365 match self {
366 Self::Str => "String".into(),
367 Self::F64 => "f64".into(),
368 Self::Int => "i64".into(),
369 Self::Bool => "bool".into(),
370 Self::Unit => "()".into(),
371 Self::Vec(t) => format!("Vec<{}>", t.rust()),
372 Self::Opt(t) => format!("Option<{}>", t.rust()),
373 Self::Json => "serde_json::Value".into(),
374 }
375 }
376
377 pub fn contains_json(&self) -> bool {
378 match self {
379 Self::Json => true,
380 Self::Vec(t) | Self::Opt(t) => t.contains_json(),
381 _ => false,
382 }
383 }
384}
385
386fn is_string_literal(ts: &str) -> bool {
387 let ts = ts.trim();
388 ts.len() >= 2
389 && ((ts.starts_with('\'') && ts.ends_with('\''))
390 || (ts.starts_with('"') && ts.ends_with('"')))
391}
392
393fn balanced(ts: &str) -> bool {
394 let mut depth = 0i32;
395 for c in ts.chars() {
396 match c {
397 '(' => depth += 1,
398 ')' => {
399 depth -= 1;
400 if depth < 0 {
401 return false;
402 }
403 }
404 _ => {}
405 }
406 }
407 depth == 0
408}
409
410fn split_top(ts: &str, sep: char) -> Vec<&str> {
412 let mut out = Vec::new();
413 let mut depth = 0i32;
414 let mut start = 0;
415 for (i, c) in ts.char_indices() {
416 match c {
417 '<' | '(' | '[' | '{' => depth += 1,
418 '>' | ')' | ']' | '}' => depth -= 1,
419 c if c == sep && depth == 0 => {
420 out.push(ts[start..i].trim());
421 start = i + c.len_utf8();
422 }
423 _ => {}
424 }
425 }
426 out.push(ts[start..].trim());
427 out.retain(|p| !p.is_empty());
428 out
429}
430
431pub fn param_type(p: &crate::ts::exports::Param) -> RType {
433 let base = RType::from_ts(&p.ts_type);
434 let base = if p.rest {
435 match base {
436 RType::Vec(_) => base,
437 other => RType::Vec(Box::new(other)),
438 }
439 } else {
440 base
441 };
442 if p.optional && !matches!(base, RType::Opt(_)) {
443 RType::Opt(Box::new(base))
444 } else {
445 base
446 }
447}
448
449pub fn snake_case(name: &str) -> String {
450 let chars: Vec<char> = name.chars().collect();
451 let mut out = String::new();
452 for (i, &c) in chars.iter().enumerate() {
453 if c.is_uppercase() {
454 let prev = i.checked_sub(1).map(|j| chars[j]);
455 let next = chars.get(i + 1);
456 let boundary = prev.is_some_and(|p| p.is_lowercase() || p.is_ascii_digit())
457 || (prev.is_some_and(char::is_uppercase) && next.is_some_and(|n| n.is_lowercase()));
458 if boundary {
459 out.push('_');
460 }
461 out.extend(c.to_lowercase());
462 } else if c.is_alphanumeric() {
463 out.push(c);
464 } else {
465 out.push('_');
466 }
467 }
468 const KEYWORDS: &[&str] = &[
469 "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
470 "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
471 "return", "self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use",
472 "where", "while", "async", "await", "dyn", "gen",
473 ];
474 if KEYWORDS.contains(&out.as_str()) {
475 format!("r#{out}")
476 } else {
477 out
478 }
479}
480
481pub fn types_in_scope(root: &Path, file: &str, text: &str) -> Vec<LocalType> {
483 let mut types = Vec::new();
484 let mut seen = std::collections::HashSet::new();
485 collect_types(root, file, text, 0, &mut seen, &mut types);
486 types
487}
488
489fn collect_types(
492 root: &Path,
493 file: &str,
494 text: &str,
495 depth: usize,
496 seen: &mut std::collections::HashSet<String>,
497 types: &mut Vec<LocalType>,
498) {
499 if depth > 4 || !seen.insert(file.to_string()) {
500 return;
501 }
502 types.extend(local_types(file, text));
503 let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
504 for import in crate::ts::scan::scan(file, text).imports {
505 let spec = import.specifier;
506 let base = if spec.starts_with('.') {
508 let joined = if dir.is_empty() {
509 spec.clone()
510 } else {
511 format!("{dir}/{spec}")
512 };
513 match normalize_rel(&joined) {
514 Some(base) => base,
515 None => continue,
516 }
517 } else {
518 let name = crate::ts::deps::package_name(&spec);
519 let Some(pkg_dir) = workspace_packages(root).get(name).cloned() else {
520 continue;
521 };
522 let sub = spec[name.len()..].trim_start_matches('/');
523 let src = if root.join(&pkg_dir).join("src").is_dir() {
524 format!("{pkg_dir}/src")
525 } else {
526 pkg_dir
527 };
528 let src = src.trim_start_matches('/').to_string();
529 if sub.is_empty() {
530 format!("{src}/index")
531 } else {
532 format!("{src}/{sub}")
533 }
534 };
535 let stem = base.trim_end_matches(".js");
536 let candidates = [
537 format!("{stem}.ts"),
538 format!("{stem}.mts"),
539 format!("{stem}.d.ts"),
540 format!("{stem}/index.ts"),
541 base.clone(),
542 ];
543 if let Some(found) = candidates.iter().find(|c| root.join(c).is_file())
544 && let Ok(imported) = std::fs::read_to_string(root.join(found))
545 {
546 collect_types(root, found, &imported, depth + 1, seen, types);
547 }
548 }
549}
550
551fn workspace_packages(root: &Path) -> std::collections::HashMap<String, String> {
553 use std::sync::{Mutex, OnceLock};
554 static CACHE: OnceLock<
555 Mutex<std::collections::HashMap<PathBuf, std::collections::HashMap<String, String>>>,
556 > = OnceLock::new();
557 let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
558 let mut cache = cache
559 .lock()
560 .unwrap_or_else(std::sync::PoisonError::into_inner);
561 cache
562 .entry(root.to_path_buf())
563 .or_insert_with(|| {
564 crate::ts::discover::discover(root)
565 .map(|ws| ws.packages.into_iter().map(|p| (p.name, p.dir)).collect())
566 .unwrap_or_default()
567 })
568 .clone()
569}
570
571fn normalize_rel(path: &str) -> Option<String> {
573 let mut parts: Vec<&str> = Vec::new();
574 for part in path.split('/') {
575 match part {
576 "" | "." => {}
577 ".." => {
578 parts.pop()?;
579 }
580 _ => parts.push(part),
581 }
582 }
583 Some(parts.join("/"))
584}
585
586pub fn substitute_constraints(f: &mut ExportedFn, types: &[LocalType]) {
589 let mut remaining = Vec::new();
590 for tp in std::mem::take(&mut f.type_params) {
591 let Some((name, constraint)) = tp.split_once(" extends ") else {
592 remaining.push(tp);
593 continue;
594 };
595 let constraint = resolve_aliases(constraint, types);
596 let open_ended = constraint.contains("=>")
599 || constraint
600 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
601 .any(|w| {
602 matches!(w, "Function" | "object" | "unknown" | "any")
603 || has_functions(w, types, &mut Vec::new())
604 });
605 if open_ended {
606 remaining.push(name.to_string());
607 continue;
608 }
609 let replacement = format!("({constraint})");
610 for p in &mut f.params {
611 p.ts_type = replace_word(&p.ts_type, name, &replacement);
612 }
613 f.returns = replace_word(&f.returns, name, &replacement);
614 }
615 f.type_params = remaining;
616}
617
618pub fn substitute_json(f: &mut ExportedFn, names: &[String]) {
620 let mut remaining = Vec::new();
621 for tp in std::mem::take(&mut f.type_params) {
622 let name = tp
623 .split_once(" extends ")
624 .map_or(tp.as_str(), |(n, _)| n)
625 .trim();
626 if !names.iter().any(|n| n == name) {
627 remaining.push(tp);
628 continue;
629 }
630 for p in &mut f.params {
631 p.ts_type = replace_word(&p.ts_type, name, "unknown");
632 }
633 f.returns = replace_word(&f.returns, name, "unknown");
634 }
635 f.type_params = remaining;
636}
637
638fn replace_word(text: &str, word: &str, with: &str) -> String {
639 let mut out = String::new();
640 let mut current = String::new();
641 for c in text.chars().chain(std::iter::once(' ')) {
642 if c.is_alphanumeric() || c == '_' || c == '$' {
643 current.push(c);
644 } else {
645 out.push_str(if current == word { with } else { ¤t });
646 current.clear();
647 out.push(c);
648 }
649 }
650 out.pop();
651 out
652}
653
654pub fn resolve_aliases(ts: &str, types: &[LocalType]) -> String {
656 let mut out = ts.to_string();
657 for _ in 0..4 {
658 let mut changed = false;
659 let mut next = String::with_capacity(out.len());
660 let mut word = String::new();
661 let flush = |word: &mut String, next: &mut String, changed: &mut bool| {
662 if let Some(t) = types.iter().find(|t| t.alias && t.name == *word) {
663 let text = t.text.trim();
664 if text.contains('|') {
665 next.push('(');
666 next.push_str(text);
667 next.push(')');
668 } else {
669 next.push_str(text);
670 }
671 *changed = true;
672 } else {
673 next.push_str(word);
674 }
675 word.clear();
676 };
677 for c in out.chars() {
678 if c.is_alphanumeric() || c == '_' || c == '$' {
679 word.push(c);
680 } else {
681 flush(&mut word, &mut next, &mut changed);
682 next.push(c);
683 }
684 }
685 flush(&mut word, &mut next, &mut changed);
686 out = next;
687 if !changed {
688 break;
689 }
690 }
691 out
692}
693
694fn needs_js(api: &codegen::PortApi) -> bool {
695 api.needs_json()
696}
697
698fn keep_reason(keep: &[String], name: &str) -> Option<String> {
700 keep.iter().find_map(|k| {
701 let (kept, reason) = k
702 .split_once(':')
703 .map_or((k.as_str(), ""), |(n, r)| (n.trim(), r.trim()));
704 (kept == name).then(|| {
705 if reason.is_empty() {
706 "kept on request".to_string()
707 } else {
708 reason.to_string()
709 }
710 })
711 })
712}
713
714fn format_rust(crate_dir: &Path) {
716 let files: Vec<PathBuf> = std::fs::read_dir(crate_dir.join("src"))
717 .into_iter()
718 .flatten()
719 .flatten()
720 .map(|e| e.path())
721 .filter(|p| p.extension().is_some_and(|e| e == "rs"))
722 .collect();
723 let _ = std::process::Command::new("rustfmt")
724 .args(["--edition", "2024"])
725 .args(&files)
726 .output();
727}
728
729fn format_wrapper(crate_dir: &Path) {
731 if crate_dir.join("go").is_dir() {
732 let _ = std::process::Command::new("gofmt")
733 .arg("-w")
734 .arg(crate_dir.join("go"))
735 .output();
736 }
737}
738
739fn js_lib_rs(m: &Manifest, api: &codegen::PortApi, modules: &codegen::Modules) -> Result<String> {
741 let mut lib = with_allocator(m, codegen::lib_rs(m, api, modules));
742 if m.kind != Kind::Pyo3 && !m.batches.is_empty() {
743 lib.push_str(&crate::codegen_batch::js_rs(m, api).map_err(anyhow::Error::msg)?);
744 }
745 if !crate::codegen_tswire::uses_wire(m, api) {
746 return Ok(lib);
747 }
748 Ok(lib.replacen(
749 "pub mod port;",
750 "pub mod port;\npub mod wire;\n\n#[allow(unused_imports)]\nuse serde_json::Value;",
751 1,
752 ) + &crate::codegen_tswire::napi_rs(m, api))
753}
754
755fn parse_batches(specs: &[String]) -> Result<Vec<crate::codegen_batch::Batch>> {
756 specs
757 .iter()
758 .map(|s| {
759 crate::codegen_batch::Batch::parse(s)
760 .with_context(|| format!("`--batch {s}`: write it as function:param"))
761 })
762 .collect()
763}
764
765pub fn add_batches(crate_dir: &Path, specs: &[String]) -> Result<Refreshed> {
767 let path = crate_dir.join(MANIFEST);
768 let before = std::fs::read_to_string(&path).with_context(|| format!("{}", path.display()))?;
769 let mut manifest = Manifest::load(crate_dir)?;
770 for b in parse_batches(specs)? {
771 if !manifest.batches.contains(&b) {
772 manifest.batches.push(b);
773 }
774 }
775 if let Some(written) = manifest.root_written.clone() {
776 manifest.root = written;
777 }
778 std::fs::write(&path, serde_json::to_string_pretty(&manifest)? + "\n")?;
779 refresh(crate_dir).inspect_err(|_| {
781 let _ = std::fs::write(&path, &before);
782 })
783}
784
785fn with_template_deps(cargo: &str, template: &str) -> Result<String> {
788 let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
789 let template: toml_edit::DocumentMut = template.parse().context("Cargo.toml template")?;
790 if let Some(want) = template.get("dependencies").and_then(|d| d.as_table()) {
791 let deps = doc["dependencies"].or_insert(toml_edit::table());
792 for (name, item) in want {
793 if deps.get(name).is_none() {
794 deps[name] = item.clone();
795 }
796 }
797 }
798 if let Some(want) = template.get("features").and_then(|d| d.as_table()) {
799 let features = doc["features"].or_insert(toml_edit::table());
800 for (name, item) in want {
801 if features.get(name).is_none() {
802 features[name] = item.clone();
803 }
804 }
805 }
806 if let Some(kinds) = template.get("lib").and_then(|l| l.get("crate-type")) {
807 doc["lib"]["crate-type"] = kinds.clone();
808 }
809 Ok(doc.to_string())
810}
811
812fn global_allocator(m: &Manifest) -> Option<Allocator> {
817 if m.batches.is_empty() {
818 return None;
819 }
820 match m.allocator {
821 Allocator::Mimalloc if m.kind == Kind::Wasm => None,
822 a => Some(a),
823 }
824}
825
826fn with_allocator(m: &Manifest, lib: String) -> String {
828 let line = match global_allocator(m) {
829 None => return lib,
830 Some(Allocator::Mimalloc) => {
831 "/// Batches allocate on all cores at once; mimalloc keeps that from serializing.\n\
832 #[global_allocator]\nstatic GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;\n"
833 }
834 Some(Allocator::RustyAlloc) => {
835 "/// Batches allocate on all cores at once; rusty_alloc keeps that from serializing.\n\
836 #[global_allocator]\n\
837 static GLOBAL: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;\n"
838 }
839 };
840 lib.replacen("pub mod port;", &format!("pub mod port;\n\n{line}"), 1)
841}
842
843fn with_rayon(m: &Manifest, cargo: String) -> Result<String> {
845 let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
846 let deps = doc["dependencies"].or_insert(toml_edit::table());
847 if m.kind == Kind::Napi
849 && !m.batches.is_empty()
850 && let Some(napi) = deps.get_mut("napi")
851 {
852 let mut table = toml_edit::InlineTable::new();
853 match napi {
854 toml_edit::Item::Value(toml_edit::Value::String(v)) => {
855 table.insert("version", v.value().clone().into());
856 }
857 toml_edit::Item::Value(toml_edit::Value::InlineTable(t)) => table = t.clone(),
858 _ => {}
859 }
860 let mut features = table
861 .get("features")
862 .and_then(|f| f.as_array())
863 .cloned()
864 .unwrap_or_default();
865 if !features.iter().any(|f| f.as_str() == Some("serde-json")) {
866 features.push("serde-json");
867 }
868 table.insert("features", toml_edit::Value::Array(features));
869 *napi = toml_edit::value(table);
870 }
871 if !crate::codegen_batch::needs_rayon(m) {
872 return Ok(doc.to_string());
873 }
874 if deps.get("rayon").is_none() {
875 deps["rayon"] = toml_edit::value("1");
876 }
877 let allocator = match global_allocator(m) {
878 Some(Allocator::Mimalloc) => Some(("mimalloc", "0.1")),
879 Some(Allocator::RustyAlloc) => Some(("rusty_alloc-api", "2.6")),
880 None => None,
881 };
882 if let Some((name, version)) = allocator
883 && deps.get(name).is_none()
884 {
885 deps[name] = toml_edit::value(version);
886 }
887 Ok(doc.to_string())
888}
889
890fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
892 match m.kind {
893 Kind::Pyo3 => (
894 format!("python/{}/__init__.py", m.lib_name()),
895 crate::codegen_py::package_init(m, api),
896 ),
897 _ => (
898 "index.cjs".into(),
899 codegen::index_cjs(m, api)
900 + &crate::codegen_tswire::index_cjs(m, api)
901 + &crate::codegen_batch::index_cjs(m, api)
902 + &codegen::guard_cjs(api, &crate::codegen_tswire::wired(m, api)),
903 ),
904 }
905}
906
907pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
910 for f in &mut api.functions {
911 if m.exports.iter().any(|e| e.name == f.js_name) {
912 continue;
913 }
914 let rust = f.rust_name.trim_start_matches("r#");
915 if let Some(e) = m
916 .exports
917 .iter()
918 .find(|e| snake_case(&e.name).trim_start_matches("r#") == rust)
919 {
920 f.js_name = e.name.clone();
921 }
922 }
923}
924
925#[derive(Debug, Serialize)]
927pub struct Refreshed {
928 pub functions: Vec<String>,
929 pub files: Vec<String>,
930}
931
932pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
935 let manifest = Manifest::load(crate_dir)?;
936 if manifest.kind == Kind::CAbi {
937 let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
938 .context("reading src/port.rs")?;
939 let mut files = c_bindings(&manifest, &port);
940 let cargo =
941 std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
942 files.push((
943 "Cargo.toml".into(),
944 with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
945 ));
946 write_files(crate_dir, &files)?;
947 format_rust(crate_dir);
948 return Ok(Refreshed {
949 functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
950 files: files.into_iter().map(|(p, _)| p).collect(),
951 });
952 }
953 if manifest.kind == Kind::Ffi {
954 let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
955 .context("reading src/port.rs")?;
956 let mut api = codegen::parse_port(&port);
957 match_export_names(&manifest, &mut api);
958 let mut files = ffi_bindings(&manifest, &api)?;
959 let cargo =
960 std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
961 let template = if manifest.language == crate::lang::Lang::Ruby {
962 crate::codegen_ruby::cargo_toml(&manifest)
963 } else {
964 crate::codegen_ffi::cargo_toml(&manifest)
965 };
966 let cargo = with_template_deps(&cargo, &template)?;
967 files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
968 write_files(crate_dir, &files)?;
969 format_rust(crate_dir);
970 format_wrapper(crate_dir);
971 return Ok(Refreshed {
972 functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
973 files: files.into_iter().map(|(p, _)| p).collect(),
974 });
975 }
976 let port =
977 std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
978 let mut fns = codegen::parse_port(&port);
979 match_export_names(&manifest, &mut fns);
980 if fns.functions.is_empty() && fns.classes.is_empty() {
981 bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
982 }
983 let modules = codegen::Modules {
984 utf16: crate_dir.join("src/utf16.rs").exists(),
985 js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
986 };
987 let mut files: Vec<(String, String)> = vec![
988 ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
989 loader_file(&manifest, &fns),
990 ];
991 if modules.js {
992 files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
993 }
994 if crate::codegen_tswire::uses_wire(&manifest, &fns) {
995 files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
996 }
997 let extension = manifest.kind == Kind::Pyo3
998 || (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
999 if extension && !crate_dir.join("build.rs").exists() {
1000 files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
1001 }
1002 if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1003 files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1004 files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1005 }
1006 let cargo_path = crate_dir.join("Cargo.toml");
1007 let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
1008 let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns).map_err(anyhow::Error::msg)?;
1009 let cargo = with_rayon(&manifest, cargo)?;
1010 files.push(("Cargo.toml".into(), cargo));
1011 for (path, text) in &files {
1012 let target = crate_dir.join(path);
1013 if let Some(parent) = target.parent() {
1014 std::fs::create_dir_all(parent)?;
1015 }
1016 std::fs::write(&target, text).with_context(|| format!("writing {path}"))?;
1017 }
1018 format_rust(crate_dir);
1019 Ok(Refreshed {
1020 functions: fns
1021 .functions
1022 .iter()
1023 .map(|f| f.js_name.clone())
1024 .chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
1025 .collect(),
1026 files: files.into_iter().map(|(p, _)| p).collect(),
1027 })
1028}
1029
1030pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
1033 if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
1034 println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
1035 }
1036}
1037"#;
1038
1039pub fn bridge(opts: &Options) -> Result<Outcome> {
1040 let root = opts
1041 .root
1042 .canonical()
1043 .with_context(|| format!("resolving {}", opts.root.display()))?;
1044 let lang = opts
1045 .lang
1046 .unwrap_or_else(|| crate::lang::Lang::detect(&root));
1047 let report = analyze::analyze_lang(&root, lang)?;
1048 let wanted = opts.unit.trim_start_matches("./");
1049 let whole = report
1050 .units
1051 .iter()
1052 .find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'));
1053 let single = || {
1054 report
1055 .units
1056 .iter()
1057 .find(|u| u.files.iter().any(|f| f == wanted))
1058 .map(|u| {
1059 let mut one = u.clone();
1060 one.id = wanted.to_string();
1061 one.files = vec![wanted.to_string()];
1062 one
1063 })
1064 };
1065 let unit = match whole.cloned().or_else(single) {
1066 Some(unit) => unit,
1067 None => bail!(
1068 "no unit or source file `{wanted}`; `rust-anything analyze` lists unit ids, and any \
1069 source file inside a unit can be bridged on its own"
1070 ),
1071 };
1072 let unit = &unit;
1073 if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
1074 bail!(
1075 "unit `{}` is {:?}: {}. Pass --force to bridge it anyway.",
1076 unit.id,
1077 unit.status,
1078 unit.notes.first().map_or("", String::as_str)
1079 );
1080 }
1081 if unit.bridge == Bridge::PhpFfi {
1082 bail!(
1083 "bridging PHP units into Rust comes next (PHP FFI over a C ABI); for now a PHP app can \
1084 be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
1085 door (`app front-door`) that hands everything to the original"
1086 );
1087 }
1088 if unit.bridge == Bridge::DotnetFfi {
1089 bail!(
1090 "bridging C# units into Rust comes next (P/Invoke over a C ABI); for now a C# app can \
1091 be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
1092 door (`app front-door`) that hands everything to the original"
1093 );
1094 }
1095 let kind = opts.kind.unwrap_or(match unit.bridge {
1096 Bridge::WasmBindgen => Kind::Wasm,
1097 Bridge::Pyo3 => Kind::Pyo3,
1098 Bridge::CAbi => Kind::CAbi,
1099 Bridge::Cgo | Bridge::Fiddle | Bridge::Jni => Kind::Ffi,
1100 _ => Kind::Napi,
1101 });
1102
1103 let mut exports = Vec::new();
1104 let mut classes = Vec::new();
1105 let mut js_only = Vec::new();
1106 if lang == crate::lang::Lang::C {
1107 crate::lang::c::use_typedefs(&root);
1108 }
1109 for file in &unit.files {
1110 if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
1111 continue;
1112 }
1113 let text =
1114 std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
1115 if lang != crate::lang::Lang::Ts {
1116 let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
1117 for f in functions {
1118 match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
1119 Some(reason) => js_only.push(JsOnly {
1120 name: f.name,
1121 file: f.file,
1122 line: f.line,
1123 reason,
1124 }),
1125 None => exports.push(f),
1126 }
1127 }
1128 for class in foreign_classes {
1129 match keep_reason(&opts.keep, &class.name)
1130 .or_else(|| class_reason(&class, &[], false))
1131 {
1132 Some(reason) => js_only.push(JsOnly {
1133 name: class.name,
1134 file: class.file,
1135 line: class.line,
1136 reason: format!("class: {reason}"),
1137 }),
1138 None => classes.push(class),
1139 }
1140 }
1141 continue;
1142 }
1143 let types = types_in_scope(&root, file, &text);
1144 for mut class in exported_classes(file, &text) {
1145 let kept = keep_reason(&opts.keep, &class.name);
1146 match kept.or_else(|| class_reason(&class, &types, true)) {
1147 Some(reason) => js_only.push(JsOnly {
1148 name: class.name,
1149 file: class.file,
1150 line: class.line,
1151 reason: format!("class: {reason}"),
1152 }),
1153 None => {
1154 for p in &mut class.constructor {
1155 p.ts_type = resolve_aliases(&p.ts_type, &types);
1156 }
1157 for m in &mut class.methods {
1158 for p in &mut m.params {
1159 p.ts_type = resolve_aliases(&p.ts_type, &types);
1160 }
1161 m.returns = resolve_aliases(&m.returns, &types);
1162 }
1163 classes.push(class);
1164 }
1165 }
1166 }
1167 for mut f in ts_functions(&root, file, &text, &types) {
1168 substitute_json(&mut f, &opts.as_json);
1169 let kept = keep_reason(&opts.keep, &f.name);
1170 match kept.or_else(|| js_only_reason(&f, &types)) {
1171 Some(reason) => js_only.push(JsOnly {
1172 name: f.name,
1173 file: f.file,
1174 line: f.line,
1175 reason,
1176 }),
1177 None => exports.push(f),
1178 }
1179 }
1180 }
1181 let mut defined: Vec<(&str, String)> = exports
1182 .iter()
1183 .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1184 .chain(
1185 classes
1186 .iter()
1187 .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1188 )
1189 .chain(
1190 js_only
1191 .iter()
1192 .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1193 )
1194 .collect();
1195 defined.sort();
1196 if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1197 bail!(
1198 "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1199 itself, so one would silently replace the other. Bridge the module you want on its \
1200 own (`rust-anything bridge <root> <that file>`), or rename one of them",
1201 pair[0].0,
1202 unit.id,
1203 pair[0].1,
1204 pair[1].1
1205 );
1206 }
1207 if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1208 bail!(
1209 "every export of `{}` must stay in {}: {}",
1210 unit.id,
1211 lang.name(),
1212 js_only
1213 .iter()
1214 .map(|j| format!("{} ({})", j.name, j.reason))
1215 .collect::<Vec<_>>()
1216 .join(", ")
1217 );
1218 }
1219 if exports.is_empty() && classes.is_empty() {
1220 bail!(
1221 "unit `{}` exports no functions; bridge a unit with an exported function API",
1222 unit.id
1223 );
1224 }
1225
1226 let stem = unit
1227 .id
1228 .trim_end_matches('/')
1229 .rsplit('/')
1230 .next()
1231 .unwrap_or("unit")
1232 .split('.')
1233 .next()
1234 .unwrap_or("unit");
1235 let crate_name = opts.name.clone().unwrap_or_else(|| {
1236 let clean: String = stem
1237 .chars()
1238 .map(|c| {
1239 if c.is_ascii_alphanumeric() {
1240 c.to_ascii_lowercase()
1241 } else {
1242 '-'
1243 }
1244 })
1245 .collect();
1246 format!("{}-rs", clean.trim_matches('-'))
1247 });
1248 let crate_dir = opts
1249 .out
1250 .clone()
1251 .unwrap_or_else(|| root.join("rust").join(&crate_name));
1252 if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1253 bail!(
1254 "{} already exists and is not empty; rust-anything never overwrites a port in progress",
1255 crate_dir.display()
1256 );
1257 }
1258
1259 let utf16 =
1261 lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1262 let manifest = Manifest {
1263 schema: SCHEMA.into(),
1264 root: root.clone(),
1265 root_written: None,
1266 unit: unit.id.clone(),
1267 language: lang,
1268 kind,
1269 crate_name: crate_name.clone(),
1270 exports: exports.clone(),
1271 classes: classes.clone(),
1272 js_only: js_only.clone(),
1273 batches: parse_batches(&opts.batch)?,
1274 allocator: opts.allocator,
1275 float_tolerance: None,
1276 };
1277 if kind == Kind::CAbi {
1278 return bridge_c(&manifest, &crate_dir, &js_only);
1279 }
1280 if kind == Kind::Ffi {
1281 return bridge_ffi(&manifest, &crate_dir, &js_only);
1282 }
1283 let port = codegen::port_rs(&manifest);
1284 let fns = codegen::parse_port(&port);
1285 let modules = codegen::Modules {
1286 utf16,
1287 js: needs_js(&fns),
1288 };
1289 let mut files: Vec<(String, String)> = vec![
1290 (
1291 "Cargo.toml".into(),
1292 with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1293 ),
1294 ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1295 ("src/port.rs".into(), port),
1296 loader_file(&manifest, &fns),
1297 (
1298 ".gitignore".into(),
1299 "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1300 ),
1301 ("README.md".into(), readme(&manifest)),
1302 (
1303 MANIFEST.into(),
1304 serde_json::to_string_pretty(&manifest)? + "\n",
1305 ),
1306 ];
1307 match kind {
1308 Kind::Napi => files.push((
1309 "build.rs".into(),
1310 "fn main() {\n napi_build::setup();\n}\n".into(),
1311 )),
1312 Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1313 _ => {}
1314 }
1315 if utf16 {
1316 files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1317 }
1318 if modules.js {
1319 files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1320 }
1321 if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1322 files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1323 }
1324 if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1325 files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1326 files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1327 }
1328 for (path, text) in &files {
1329 let target = crate_dir.join(path);
1330 if let Some(parent) = target.parent() {
1331 std::fs::create_dir_all(parent)?;
1332 }
1333 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1334 }
1335
1336 format_rust(&crate_dir);
1337 let mut notes = vec![format!(
1338 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1339 crate_dir.display()
1340 )];
1341 if utf16 {
1342 notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1343 }
1344 for j in &js_only {
1345 notes.push(format!(
1346 "`{}` stays in {}: {}. The shadow module re-exports the original.",
1347 j.name,
1348 lang.name(),
1349 j.reason
1350 ));
1351 }
1352 if exports.iter().any(codegen::is_async) {
1353 notes.push(
1354 "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1355 );
1356 }
1357 Ok(Outcome {
1358 crate_dir,
1359 kind,
1360 files: files.into_iter().map(|(p, _)| p).collect(),
1361 exports: exports
1362 .iter()
1363 .map(|f| f.name.clone())
1364 .chain(classes.iter().map(|c| format!("class {}", c.name)))
1365 .collect(),
1366 notes,
1367 })
1368}
1369
1370fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1371 for (path, text) in files {
1372 let target = crate_dir.join(path);
1373 if let Some(parent) = target.parent() {
1374 std::fs::create_dir_all(parent)?;
1375 }
1376 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1377 }
1378 Ok(())
1379}
1380
1381fn c_bindings(m: &Manifest, port: &str) -> Vec<(String, String)> {
1384 vec![
1385 ("src/lib.rs".into(), crate::codegen_c::lib_rs(m, port)),
1386 (
1387 format!("include/{}.h", m.lib_name()),
1388 crate::codegen_c::header(m),
1389 ),
1390 ]
1391}
1392
1393fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1395 let mut files = if m.language == crate::lang::Lang::Ruby {
1396 vec![
1397 (
1398 "src/lib.rs".to_string(),
1399 with_allocator(
1400 m,
1401 crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1402 ),
1403 ),
1404 (
1405 "src/rbconv.rs".to_string(),
1406 crate::codegen_ruby::RBCONV_RS.to_string(),
1407 ),
1408 ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1409 ]
1410 } else {
1411 let mut lib = crate::codegen_ffi::lib_rs(m, api);
1412 if matches!(
1413 m.language,
1414 crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1415 ) {
1416 lib.push_str(&crate::codegen_java::typed_rs(m, api));
1417 }
1418 if m.language == crate::lang::Lang::Go {
1419 lib.push_str(&crate::codegen_go::typed_rs(m, api));
1420 lib.push_str(&crate::codegen_go::wire_rs(m, api));
1421 lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1422 }
1423 if matches!(
1424 m.language,
1425 crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1426 ) {
1427 lib.push_str(&crate::codegen_java::wire_rs(m, api));
1428 lib.push_str(
1429 &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1430 );
1431 }
1432 if matches!(
1433 m.language,
1434 crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1435 ) {
1436 lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1437 }
1438 let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1439 if matches!(
1440 m.language,
1441 crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1442 ) {
1443 files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1444 }
1445 files
1446 };
1447 match m.language {
1448 crate::lang::Lang::Go => {
1449 if crate::codegen_go::unit_sources(m).is_empty() {
1452 bail!(
1453 "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1454 m.unit,
1455 m.root.display()
1456 );
1457 }
1458 files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1459 files.push((
1460 format!("go/{}.go", crate::codegen_go::package_name(m)),
1461 crate::codegen_go::wrapper(m, api),
1462 ));
1463 }
1464 crate::lang::Lang::Ruby => {
1465 files.push((
1466 crate::harness_ruby::wrapper_path(m),
1467 crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1468 ));
1469 }
1470 crate::lang::Lang::Java | crate::lang::Lang::Kotlin => {
1471 files.extend(crate::codegen_java::wrappers(m, api));
1472 files.extend(
1473 crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1474 );
1475 files.push((
1476 format!(
1477 "java/rustanything/{}.java",
1478 crate::codegen_ffi::java_native_class(m)
1479 ),
1480 crate::codegen_java::native_class(m, api),
1481 ));
1482 files.push((
1483 "java/rustanything/RustAnythingJson.java".into(),
1484 crate::codegen_java::JSON_JAVA.into(),
1485 ));
1486 files.push((
1487 "java/rustanything/RustAnythingWire.java".into(),
1488 crate::codegen_java::WIRE_JAVA.into(),
1489 ));
1490 files.push((
1491 "java/rustanything/RustAnythingError.java".into(),
1492 crate::codegen_java::ERROR_JAVA.into(),
1493 ));
1494 }
1495 other => bail!("no wrapper generator for {}", other.name()),
1496 }
1497 Ok(files)
1498}
1499
1500fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1501 let port = codegen::port_rs(manifest);
1502 let api = codegen::parse_port(&port);
1503 let mut files = vec![
1504 (
1505 "Cargo.toml".to_string(),
1506 with_rayon(
1507 manifest,
1508 if manifest.language == crate::lang::Lang::Ruby {
1509 crate::codegen_ruby::cargo_toml(manifest)
1510 } else {
1511 crate::codegen_ffi::cargo_toml(manifest)
1512 },
1513 )?,
1514 ),
1515 ("src/port.rs".into(), port),
1516 (
1517 ".gitignore".into(),
1518 "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1519 ),
1520 ("README.md".into(), readme(manifest)),
1521 (
1522 MANIFEST.into(),
1523 serde_json::to_string_pretty(manifest)? + "\n",
1524 ),
1525 ];
1526 files.extend(ffi_bindings(manifest, &api)?);
1527 write_files(crate_dir, &files)?;
1528 format_rust(crate_dir);
1529 format_wrapper(crate_dir);
1530 let mut notes = vec![format!(
1531 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1532 crate_dir.display()
1533 )];
1534 for j in kept {
1535 notes.push(format!(
1536 "`{}` stays in {}: {}.",
1537 j.name,
1538 manifest.language.name(),
1539 j.reason
1540 ));
1541 }
1542 Ok(Outcome {
1543 crate_dir: crate_dir.to_path_buf(),
1544 kind: Kind::Ffi,
1545 files: files.into_iter().map(|(p, _)| p).collect(),
1546 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1547 notes,
1548 })
1549}
1550
1551fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1552 let mut files = vec![
1553 (
1554 "Cargo.toml".to_string(),
1555 crate::codegen_c::cargo_toml(manifest),
1556 ),
1557 ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1558 (
1559 ".gitignore".into(),
1560 "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1561 ),
1562 ("README.md".into(), readme(manifest)),
1563 (
1564 MANIFEST.into(),
1565 serde_json::to_string_pretty(manifest)? + "\n",
1566 ),
1567 ];
1568 let port = crate::codegen_c::port_rs(manifest);
1569 files.extend(c_bindings(manifest, &port));
1570 write_files(crate_dir, &files)?;
1571 format_rust(crate_dir);
1572 let mut notes = vec![
1573 format!(
1574 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1575 crate_dir.display()
1576 ),
1577 format!(
1578 "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1579 manifest.lib_name(),
1580 manifest.lib_name()
1581 ),
1582 ];
1583 for j in kept {
1584 notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1585 }
1586 Ok(Outcome {
1587 crate_dir: crate_dir.to_path_buf(),
1588 kind: Kind::CAbi,
1589 files: files.into_iter().map(|(p, _)| p).collect(),
1590 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1591 notes,
1592 })
1593}
1594
1595fn readme(m: &Manifest) -> String {
1596 let functions: String = m
1597 .exports
1598 .iter()
1599 .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1600 .collect();
1601 format!(
1602 "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1603 ## Loop\n\n```sh\nrust-anything record . # record what the TS code does\nrust-anything build . # build the {kind} module\n\
1604 rust-anything diff . # run the recorded cases against Rust\nrust-anything shadow . # run both in the app, log mismatches\n\
1605 rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n```\n",
1606 name = m.crate_name,
1607 unit = m.unit,
1608 kind = match m.kind {
1609 Kind::Napi => "napi-rs",
1610 Kind::Wasm => "wasm-bindgen",
1611 Kind::Pyo3 => "PyO3",
1612 Kind::CAbi => "the C ABI",
1613 Kind::Ffi => "a JSON dispatcher",
1614 },
1615 )
1616}
1617
1618const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1619//!
1620//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1621//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1622
1623#![forbid(unsafe_code)]
1624
1625/// The UTF-16 code units of `s`, as JS sees the string.
1626pub fn units(s: &str) -> Vec<u16> {
1627 s.encode_utf16().collect()
1628}
1629
1630/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1631pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1632 let end = end.min(units.len());
1633 let start = start.min(end);
1634 String::from_utf16_lossy(&units[start..end])
1635}
1636
1637/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1638pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1639 let from = from.min(haystack.len());
1640 if needle.is_empty() {
1641 return Some(from);
1642 }
1643 haystack[from..]
1644 .windows(needle.len())
1645 .position(|w| w == needle)
1646 .map(|i| i + from)
1647}
1648
1649/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1650pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1651 if needle.is_empty() {
1652 return Some(haystack.len());
1653 }
1654 haystack.windows(needle.len()).rposition(|w| w == needle)
1655}
1656
1657/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1658pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1659 let mut seen = 0;
1660 for (byte, c) in s.char_indices() {
1661 if seen >= utf16_offset {
1662 return byte;
1663 }
1664 seen += c.len_utf16();
1665 }
1666 s.len()
1667}
1668
1669/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1670pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1671 s[..byte_offset.min(s.len())].encode_utf16().count()
1672}
1673
1674#[cfg(test)]
1675mod tests {
1676 use super::*;
1677
1678 #[test]
1679 fn matches_js_indexing() {
1680 let s = units("a👍b");
1681 assert_eq!(s.len(), 4);
1682 assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1683 assert_eq!(last_index_of(&s, &units("a")), Some(0));
1684 assert_eq!(slice(&s, 3, 4), "b");
1685 assert_eq!(byte_offset("a👍b", 3), 5);
1686 assert_eq!(utf16_offset("a👍b", 5), 3);
1687 }
1688}
1689"#;
1690
1691#[cfg(test)]
1692mod tests {
1693 use super::*;
1694
1695 #[test]
1696 fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1697 let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1698 let _ = std::fs::remove_dir_all(&base);
1699 let crate_dir = base.join("repo/rust/x-rs");
1700 std::fs::create_dir_all(&crate_dir).unwrap();
1701 std::fs::write(
1702 crate_dir.join(MANIFEST),
1703 r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1704 )
1705 .unwrap();
1706 let m = Manifest::load(&crate_dir).unwrap();
1707 assert_eq!(m.root, base.join("repo").canonical().unwrap());
1708 assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1709 let mut back = m.clone();
1711 if let Some(w) = back.root_written.clone() {
1712 back.root = w;
1713 }
1714 assert!(
1715 serde_json::to_string(&back)
1716 .unwrap()
1717 .contains(r#""root":"../..""#)
1718 );
1719 std::fs::remove_dir_all(&base).unwrap();
1720 }
1721
1722 #[test]
1723 fn maps_ts_types() {
1724 assert_eq!(RType::from_ts("string").rust(), "String");
1725 assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1726 assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1727 assert_eq!(
1728 RType::from_ts("string | undefined").rust(),
1729 "Option<String>"
1730 );
1731 assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1732 assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1733 assert_eq!(
1734 RType::from_ts("Map<string, number>").rust(),
1735 "serde_json::Value"
1736 );
1737 assert_eq!(
1738 RType::from_ts("string | number").rust(),
1739 "serde_json::Value"
1740 );
1741 assert_eq!(
1742 RType::from_ts("Record<string, string | number>").rust(),
1743 "serde_json::Value"
1744 );
1745 assert_eq!(
1746 RType::from_ts("(string | undefined)").rust(),
1747 "Option<String>"
1748 );
1749 assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
1750 }
1751
1752 #[test]
1753 fn keeps_unbridgeable_exports_in_js() {
1754 let source = "export interface LineIndex {\n readonly lineCount: number\n position(offset: number): number\n}\n\
1755 export interface Range { start: number, end: number }\n\
1756 export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
1757 export function globToRegExp(glob: string): RegExp { return /x/ }\n\
1758 export function createLineIndex(text: string): LineIndex { return null! }\n\
1759 export function* walk(tree: object) {}\n\
1760 export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
1761 export function contains(range: Range, offset: number): boolean { return true }\n";
1762 let types = local_types("a.ts", source);
1763 let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
1764 .iter()
1765 .map(|f| (f.name.clone(), js_only_reason(f, &types)))
1766 .collect();
1767 let js_only: Vec<&str> = reasons
1768 .iter()
1769 .filter(|(_, r)| r.is_some())
1770 .map(|(n, _)| n.as_str())
1771 .collect();
1772 assert_eq!(
1773 js_only,
1774 [
1775 "keyMatcher",
1776 "globToRegExp",
1777 "createLineIndex",
1778 "walk",
1779 "sortTree"
1780 ]
1781 );
1782 }
1783
1784 #[test]
1785 fn resolves_simple_aliases() {
1786 let types = local_types(
1787 "m.ts",
1788 "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
1789 );
1790 assert_eq!(
1791 resolve_aliases("readonly KeyString[]", &types),
1792 "readonly string[]"
1793 );
1794 assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
1795 assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
1796 }
1797
1798 #[test]
1799 fn substitutes_simple_constraints() {
1800 let found = exported_functions(
1801 "a.ts",
1802 "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
1803 export function pick<T>(x: T): T { return x }\n\
1804 export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
1805 );
1806 let mut fns = found;
1807 for f in &mut fns {
1808 substitute_constraints(f, &[]);
1809 }
1810 assert_eq!(fns[0].params[0].ts_type, "(string)");
1811 assert!(fns[0].type_params.is_empty());
1812 assert_eq!(fns[1].type_params, ["T"]);
1813 assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
1814 assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
1815 }
1816
1817 #[test]
1818 fn as_json_bridges_a_data_generic() {
1819 let mut fns = exported_functions(
1820 "a.ts",
1821 "export function paginate<T>(items: T[], page: number): { data: T[] } { return { data: items } }\n",
1822 );
1823 assert!(js_only_reason(&fns[0], &[]).is_some());
1824 substitute_json(&mut fns[0], &["T".to_string()]);
1825 assert!(fns[0].type_params.is_empty());
1826 assert_eq!(fns[0].params[0].ts_type, "unknown[]");
1827 assert_eq!(fns[0].returns, "{ data: unknown[] }");
1828 assert!(js_only_reason(&fns[0], &[]).is_none());
1829 }
1830
1831 #[test]
1832 fn makes_rust_names() {
1833 assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
1834 assert_eq!(snake_case("type"), "r#type");
1835 assert_eq!(snake_case("toURL"), "to_url");
1836 assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
1837 }
1838}