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