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 && !opts.batch.is_empty() {
1082 bail!("`--batch` is not available for PHP units yet");
1083 }
1084 if unit.bridge == Bridge::DotnetFfi && !opts.batch.is_empty() {
1085 bail!("`--batch` is not available for C# units yet");
1086 }
1087 let kind = opts.kind.unwrap_or(match unit.bridge {
1088 Bridge::WasmBindgen => Kind::Wasm,
1089 Bridge::Pyo3 => Kind::Pyo3,
1090 Bridge::CAbi => Kind::CAbi,
1091 Bridge::Cgo | Bridge::Fiddle | Bridge::Jni | Bridge::PhpFfi | Bridge::DotnetFfi => {
1092 Kind::Ffi
1093 }
1094 _ => Kind::Napi,
1095 });
1096
1097 let mut exports = Vec::new();
1098 let mut classes = Vec::new();
1099 let mut js_only = Vec::new();
1100 if lang == crate::lang::Lang::C {
1101 crate::lang::c::use_typedefs(&root);
1102 }
1103 if lang == crate::lang::Lang::Csharp {
1104 crate::lang::csharp::use_shapes(&root);
1105 }
1106 for file in &unit.files {
1107 if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
1108 continue;
1109 }
1110 let text =
1111 std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
1112 if lang != crate::lang::Lang::Ts {
1113 let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
1114 for f in functions {
1115 match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
1116 Some(reason) => js_only.push(JsOnly {
1117 name: f.name,
1118 file: f.file,
1119 line: f.line,
1120 reason,
1121 }),
1122 None => exports.push(f),
1123 }
1124 }
1125 for class in foreign_classes {
1126 match keep_reason(&opts.keep, &class.name)
1127 .or_else(|| class_reason(&class, &[], false))
1128 {
1129 Some(reason) => js_only.push(JsOnly {
1130 name: class.name,
1131 file: class.file,
1132 line: class.line,
1133 reason: format!("class: {reason}"),
1134 }),
1135 None => classes.push(class),
1136 }
1137 }
1138 continue;
1139 }
1140 let types = types_in_scope(&root, file, &text);
1141 for mut class in exported_classes(file, &text) {
1142 let kept = keep_reason(&opts.keep, &class.name);
1143 match kept.or_else(|| class_reason(&class, &types, true)) {
1144 Some(reason) => js_only.push(JsOnly {
1145 name: class.name,
1146 file: class.file,
1147 line: class.line,
1148 reason: format!("class: {reason}"),
1149 }),
1150 None => {
1151 for p in &mut class.constructor {
1152 p.ts_type = resolve_aliases(&p.ts_type, &types);
1153 }
1154 for m in &mut class.methods {
1155 for p in &mut m.params {
1156 p.ts_type = resolve_aliases(&p.ts_type, &types);
1157 }
1158 m.returns = resolve_aliases(&m.returns, &types);
1159 }
1160 classes.push(class);
1161 }
1162 }
1163 }
1164 for mut f in ts_functions(&root, file, &text, &types) {
1165 substitute_json(&mut f, &opts.as_json);
1166 let kept = keep_reason(&opts.keep, &f.name);
1167 match kept.or_else(|| js_only_reason(&f, &types)) {
1168 Some(reason) => js_only.push(JsOnly {
1169 name: f.name,
1170 file: f.file,
1171 line: f.line,
1172 reason,
1173 }),
1174 None => exports.push(f),
1175 }
1176 }
1177 }
1178 let mut defined: Vec<(&str, String)> = exports
1179 .iter()
1180 .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1181 .chain(
1182 classes
1183 .iter()
1184 .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1185 )
1186 .chain(
1187 js_only
1188 .iter()
1189 .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1190 )
1191 .collect();
1192 defined.sort();
1193 if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1194 bail!(
1195 "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1196 itself, so one would silently replace the other. Bridge the module you want on its \
1197 own (`rust-anything bridge <root> <that file>`), or rename one of them",
1198 pair[0].0,
1199 unit.id,
1200 pair[0].1,
1201 pair[1].1
1202 );
1203 }
1204 if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1205 bail!(
1206 "every export of `{}` must stay in {}: {}",
1207 unit.id,
1208 lang.name(),
1209 js_only
1210 .iter()
1211 .map(|j| format!("{} ({})", j.name, j.reason))
1212 .collect::<Vec<_>>()
1213 .join(", ")
1214 );
1215 }
1216 if exports.is_empty() && classes.is_empty() {
1217 bail!(
1218 "unit `{}` exports no functions; bridge a unit with an exported function API",
1219 unit.id
1220 );
1221 }
1222
1223 let stem = unit
1224 .id
1225 .trim_end_matches('/')
1226 .rsplit('/')
1227 .next()
1228 .unwrap_or("unit")
1229 .split('.')
1230 .next()
1231 .unwrap_or("unit");
1232 let crate_name = opts.name.clone().unwrap_or_else(|| {
1233 let clean: String = stem
1234 .chars()
1235 .map(|c| {
1236 if c.is_ascii_alphanumeric() {
1237 c.to_ascii_lowercase()
1238 } else {
1239 '-'
1240 }
1241 })
1242 .collect();
1243 format!("{}-rs", clean.trim_matches('-'))
1244 });
1245 let crate_dir = opts
1246 .out
1247 .clone()
1248 .unwrap_or_else(|| root.join("rust").join(&crate_name));
1249 if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1250 bail!(
1251 "{} already exists and is not empty; rust-anything never overwrites a port in progress",
1252 crate_dir.display()
1253 );
1254 }
1255
1256 let utf16 =
1258 lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1259 let manifest = Manifest {
1260 schema: SCHEMA.into(),
1261 root: root.clone(),
1262 root_written: None,
1263 unit: unit.id.clone(),
1264 language: lang,
1265 kind,
1266 crate_name: crate_name.clone(),
1267 exports: exports.clone(),
1268 classes: classes.clone(),
1269 js_only: js_only.clone(),
1270 batches: parse_batches(&opts.batch)?,
1271 allocator: opts.allocator,
1272 float_tolerance: None,
1273 };
1274 if kind == Kind::CAbi {
1275 return bridge_c(&manifest, &crate_dir, &js_only);
1276 }
1277 if kind == Kind::Ffi {
1278 return bridge_ffi(&manifest, &crate_dir, &js_only);
1279 }
1280 let port = codegen::port_rs(&manifest);
1281 let fns = codegen::parse_port(&port);
1282 let modules = codegen::Modules {
1283 utf16,
1284 js: needs_js(&fns),
1285 };
1286 let mut files: Vec<(String, String)> = vec![
1287 (
1288 "Cargo.toml".into(),
1289 with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1290 ),
1291 ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1292 ("src/port.rs".into(), port),
1293 loader_file(&manifest, &fns),
1294 (
1295 ".gitignore".into(),
1296 "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1297 ),
1298 ("README.md".into(), readme(&manifest)),
1299 (
1300 MANIFEST.into(),
1301 serde_json::to_string_pretty(&manifest)? + "\n",
1302 ),
1303 ];
1304 match kind {
1305 Kind::Napi => files.push((
1306 "build.rs".into(),
1307 "fn main() {\n napi_build::setup();\n}\n".into(),
1308 )),
1309 Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1310 _ => {}
1311 }
1312 if utf16 {
1313 files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1314 }
1315 if modules.js {
1316 files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1317 }
1318 if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1319 files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1320 }
1321 if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1322 files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1323 files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1324 }
1325 for (path, text) in &files {
1326 let target = crate_dir.join(path);
1327 if let Some(parent) = target.parent() {
1328 std::fs::create_dir_all(parent)?;
1329 }
1330 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1331 }
1332
1333 format_rust(&crate_dir);
1334 let mut notes = vec![format!(
1335 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1336 crate_dir.display()
1337 )];
1338 if utf16 {
1339 notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1340 }
1341 for j in &js_only {
1342 notes.push(format!(
1343 "`{}` stays in {}: {}. The shadow module re-exports the original.",
1344 j.name,
1345 lang.name(),
1346 j.reason
1347 ));
1348 }
1349 if exports.iter().any(codegen::is_async) {
1350 notes.push(
1351 "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1352 );
1353 }
1354 Ok(Outcome {
1355 crate_dir,
1356 kind,
1357 files: files.into_iter().map(|(p, _)| p).collect(),
1358 exports: exports
1359 .iter()
1360 .map(|f| f.name.clone())
1361 .chain(classes.iter().map(|c| format!("class {}", c.name)))
1362 .collect(),
1363 notes,
1364 })
1365}
1366
1367fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1368 for (path, text) in files {
1369 let target = crate_dir.join(path);
1370 if let Some(parent) = target.parent() {
1371 std::fs::create_dir_all(parent)?;
1372 }
1373 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1374 }
1375 Ok(())
1376}
1377
1378fn c_bindings(m: &Manifest, port: &str) -> Vec<(String, String)> {
1381 vec![
1382 ("src/lib.rs".into(), crate::codegen_c::lib_rs(m, port)),
1383 (
1384 format!("include/{}.h", m.lib_name()),
1385 crate::codegen_c::header(m),
1386 ),
1387 ]
1388}
1389
1390fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1392 let mut files = if m.language == crate::lang::Lang::Ruby {
1393 vec![
1394 (
1395 "src/lib.rs".to_string(),
1396 with_allocator(
1397 m,
1398 crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1399 ),
1400 ),
1401 (
1402 "src/rbconv.rs".to_string(),
1403 crate::codegen_ruby::RBCONV_RS.to_string(),
1404 ),
1405 ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1406 ]
1407 } else {
1408 let mut lib = crate::codegen_ffi::lib_rs(m, api);
1409 if matches!(
1410 m.language,
1411 crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1412 ) {
1413 lib.push_str(&crate::codegen_java::typed_rs(m, api));
1414 }
1415 if m.language == crate::lang::Lang::Go {
1416 lib.push_str(&crate::codegen_go::typed_rs(m, api));
1417 lib.push_str(&crate::codegen_go::wire_rs(m, api));
1418 lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1419 }
1420 if matches!(
1421 m.language,
1422 crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1423 ) {
1424 lib.push_str(&crate::codegen_java::wire_rs(m, api));
1425 lib.push_str(
1426 &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1427 );
1428 }
1429 if matches!(
1430 m.language,
1431 crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1432 ) {
1433 lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1434 }
1435 let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1436 if matches!(
1437 m.language,
1438 crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1439 ) {
1440 files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1441 }
1442 files
1443 };
1444 match m.language {
1445 crate::lang::Lang::Go => {
1446 if crate::codegen_go::unit_sources(m).is_empty() {
1449 bail!(
1450 "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1451 m.unit,
1452 m.root.display()
1453 );
1454 }
1455 files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1456 files.push((
1457 format!("go/{}.go", crate::codegen_go::package_name(m)),
1458 crate::codegen_go::wrapper(m, api),
1459 ));
1460 }
1461 crate::lang::Lang::Ruby => {
1462 files.push((
1463 crate::harness_ruby::wrapper_path(m),
1464 crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1465 ));
1466 }
1467 crate::lang::Lang::Php => {
1468 files.push((
1469 crate::codegen_php::wrapper_path(m),
1470 crate::codegen_php::wrapper(m),
1471 ));
1472 }
1473 crate::lang::Lang::Csharp => {
1474 files.push((
1475 crate::codegen_csharp::wrapper_path(m),
1476 crate::codegen_csharp::wrapper(m),
1477 ));
1478 }
1479 crate::lang::Lang::Java | crate::lang::Lang::Kotlin => {
1480 files.extend(crate::codegen_java::wrappers(m, api));
1481 files.extend(
1482 crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1483 );
1484 files.push((
1485 format!(
1486 "java/rustanything/{}.java",
1487 crate::codegen_ffi::java_native_class(m)
1488 ),
1489 crate::codegen_java::native_class(m, api),
1490 ));
1491 files.push((
1492 "java/rustanything/RustAnythingJson.java".into(),
1493 crate::codegen_java::JSON_JAVA.into(),
1494 ));
1495 files.push((
1496 "java/rustanything/RustAnythingWire.java".into(),
1497 crate::codegen_java::WIRE_JAVA.into(),
1498 ));
1499 files.push((
1500 "java/rustanything/RustAnythingError.java".into(),
1501 crate::codegen_java::ERROR_JAVA.into(),
1502 ));
1503 }
1504 other => bail!("no wrapper generator for {}", other.name()),
1505 }
1506 Ok(files)
1507}
1508
1509fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1510 let port = codegen::port_rs(manifest);
1511 let api = codegen::parse_port(&port);
1512 let mut files = vec![
1513 (
1514 "Cargo.toml".to_string(),
1515 with_rayon(
1516 manifest,
1517 if manifest.language == crate::lang::Lang::Ruby {
1518 crate::codegen_ruby::cargo_toml(manifest)
1519 } else {
1520 crate::codegen_ffi::cargo_toml(manifest)
1521 },
1522 )?,
1523 ),
1524 ("src/port.rs".into(), port),
1525 (
1526 ".gitignore".into(),
1527 "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\ncs/*.so\ncs/*.dylib\ncs/*.dll\n".into(),
1528 ),
1529 ("README.md".into(), readme(manifest)),
1530 (
1531 MANIFEST.into(),
1532 serde_json::to_string_pretty(manifest)? + "\n",
1533 ),
1534 ];
1535 files.extend(ffi_bindings(manifest, &api)?);
1536 write_files(crate_dir, &files)?;
1537 format_rust(crate_dir);
1538 format_wrapper(crate_dir);
1539 let mut notes = vec![format!(
1540 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1541 crate_dir.display()
1542 )];
1543 for j in kept {
1544 notes.push(format!(
1545 "`{}` stays in {}: {}.",
1546 j.name,
1547 manifest.language.name(),
1548 j.reason
1549 ));
1550 }
1551 Ok(Outcome {
1552 crate_dir: crate_dir.to_path_buf(),
1553 kind: Kind::Ffi,
1554 files: files.into_iter().map(|(p, _)| p).collect(),
1555 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1556 notes,
1557 })
1558}
1559
1560fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1561 let mut files = vec![
1562 (
1563 "Cargo.toml".to_string(),
1564 crate::codegen_c::cargo_toml(manifest),
1565 ),
1566 ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1567 (
1568 ".gitignore".into(),
1569 "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\n".into(),
1570 ),
1571 ("README.md".into(), readme(manifest)),
1572 (
1573 MANIFEST.into(),
1574 serde_json::to_string_pretty(manifest)? + "\n",
1575 ),
1576 ];
1577 let port = crate::codegen_c::port_rs(manifest);
1578 files.extend(c_bindings(manifest, &port));
1579 write_files(crate_dir, &files)?;
1580 format_rust(crate_dir);
1581 let mut notes = vec![
1582 format!(
1583 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1584 crate_dir.display()
1585 ),
1586 format!(
1587 "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1588 manifest.lib_name(),
1589 manifest.lib_name()
1590 ),
1591 ];
1592 for j in kept {
1593 notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1594 }
1595 Ok(Outcome {
1596 crate_dir: crate_dir.to_path_buf(),
1597 kind: Kind::CAbi,
1598 files: files.into_iter().map(|(p, _)| p).collect(),
1599 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1600 notes,
1601 })
1602}
1603
1604fn readme(m: &Manifest) -> String {
1605 let functions: String = m
1606 .exports
1607 .iter()
1608 .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1609 .collect();
1610 format!(
1611 "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1612 ## Loop\n\n```sh\nrust-anything record . # record what the TS code does\nrust-anything build . # build the {kind} module\n\
1613 rust-anything diff . # run the recorded cases against Rust\nrust-anything shadow . # run both in the app, log mismatches\n\
1614 rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n```\n",
1615 name = m.crate_name,
1616 unit = m.unit,
1617 kind = match m.kind {
1618 Kind::Napi => "napi-rs",
1619 Kind::Wasm => "wasm-bindgen",
1620 Kind::Pyo3 => "PyO3",
1621 Kind::CAbi => "the C ABI",
1622 Kind::Ffi => "a JSON dispatcher",
1623 },
1624 )
1625}
1626
1627const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1628//!
1629//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1630//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1631
1632#![forbid(unsafe_code)]
1633
1634/// The UTF-16 code units of `s`, as JS sees the string.
1635pub fn units(s: &str) -> Vec<u16> {
1636 s.encode_utf16().collect()
1637}
1638
1639/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1640pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1641 let end = end.min(units.len());
1642 let start = start.min(end);
1643 String::from_utf16_lossy(&units[start..end])
1644}
1645
1646/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1647pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1648 let from = from.min(haystack.len());
1649 if needle.is_empty() {
1650 return Some(from);
1651 }
1652 haystack[from..]
1653 .windows(needle.len())
1654 .position(|w| w == needle)
1655 .map(|i| i + from)
1656}
1657
1658/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1659pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1660 if needle.is_empty() {
1661 return Some(haystack.len());
1662 }
1663 haystack.windows(needle.len()).rposition(|w| w == needle)
1664}
1665
1666/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1667pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1668 let mut seen = 0;
1669 for (byte, c) in s.char_indices() {
1670 if seen >= utf16_offset {
1671 return byte;
1672 }
1673 seen += c.len_utf16();
1674 }
1675 s.len()
1676}
1677
1678/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1679pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1680 s[..byte_offset.min(s.len())].encode_utf16().count()
1681}
1682
1683#[cfg(test)]
1684mod tests {
1685 use super::*;
1686
1687 #[test]
1688 fn matches_js_indexing() {
1689 let s = units("a👍b");
1690 assert_eq!(s.len(), 4);
1691 assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1692 assert_eq!(last_index_of(&s, &units("a")), Some(0));
1693 assert_eq!(slice(&s, 3, 4), "b");
1694 assert_eq!(byte_offset("a👍b", 3), 5);
1695 assert_eq!(utf16_offset("a👍b", 5), 3);
1696 }
1697}
1698"#;
1699
1700#[cfg(test)]
1701mod tests {
1702 use super::*;
1703
1704 #[test]
1705 fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1706 let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1707 let _ = std::fs::remove_dir_all(&base);
1708 let crate_dir = base.join("repo/rust/x-rs");
1709 std::fs::create_dir_all(&crate_dir).unwrap();
1710 std::fs::write(
1711 crate_dir.join(MANIFEST),
1712 r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1713 )
1714 .unwrap();
1715 let m = Manifest::load(&crate_dir).unwrap();
1716 assert_eq!(m.root, base.join("repo").canonical().unwrap());
1717 assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1718 let mut back = m.clone();
1720 if let Some(w) = back.root_written.clone() {
1721 back.root = w;
1722 }
1723 assert!(
1724 serde_json::to_string(&back)
1725 .unwrap()
1726 .contains(r#""root":"../..""#)
1727 );
1728 std::fs::remove_dir_all(&base).unwrap();
1729 }
1730
1731 #[test]
1732 fn maps_ts_types() {
1733 assert_eq!(RType::from_ts("string").rust(), "String");
1734 assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1735 assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1736 assert_eq!(
1737 RType::from_ts("string | undefined").rust(),
1738 "Option<String>"
1739 );
1740 assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1741 assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1742 assert_eq!(
1743 RType::from_ts("Map<string, number>").rust(),
1744 "serde_json::Value"
1745 );
1746 assert_eq!(
1747 RType::from_ts("string | number").rust(),
1748 "serde_json::Value"
1749 );
1750 assert_eq!(
1751 RType::from_ts("Record<string, string | number>").rust(),
1752 "serde_json::Value"
1753 );
1754 assert_eq!(
1755 RType::from_ts("(string | undefined)").rust(),
1756 "Option<String>"
1757 );
1758 assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
1759 }
1760
1761 #[test]
1762 fn keeps_unbridgeable_exports_in_js() {
1763 let source = "export interface LineIndex {\n readonly lineCount: number\n position(offset: number): number\n}\n\
1764 export interface Range { start: number, end: number }\n\
1765 export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
1766 export function globToRegExp(glob: string): RegExp { return /x/ }\n\
1767 export function createLineIndex(text: string): LineIndex { return null! }\n\
1768 export function* walk(tree: object) {}\n\
1769 export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
1770 export function contains(range: Range, offset: number): boolean { return true }\n";
1771 let types = local_types("a.ts", source);
1772 let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
1773 .iter()
1774 .map(|f| (f.name.clone(), js_only_reason(f, &types)))
1775 .collect();
1776 let js_only: Vec<&str> = reasons
1777 .iter()
1778 .filter(|(_, r)| r.is_some())
1779 .map(|(n, _)| n.as_str())
1780 .collect();
1781 assert_eq!(
1782 js_only,
1783 [
1784 "keyMatcher",
1785 "globToRegExp",
1786 "createLineIndex",
1787 "walk",
1788 "sortTree"
1789 ]
1790 );
1791 }
1792
1793 #[test]
1794 fn resolves_simple_aliases() {
1795 let types = local_types(
1796 "m.ts",
1797 "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
1798 );
1799 assert_eq!(
1800 resolve_aliases("readonly KeyString[]", &types),
1801 "readonly string[]"
1802 );
1803 assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
1804 assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
1805 }
1806
1807 #[test]
1808 fn substitutes_simple_constraints() {
1809 let found = exported_functions(
1810 "a.ts",
1811 "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
1812 export function pick<T>(x: T): T { return x }\n\
1813 export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
1814 );
1815 let mut fns = found;
1816 for f in &mut fns {
1817 substitute_constraints(f, &[]);
1818 }
1819 assert_eq!(fns[0].params[0].ts_type, "(string)");
1820 assert!(fns[0].type_params.is_empty());
1821 assert_eq!(fns[1].type_params, ["T"]);
1822 assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
1823 assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
1824 }
1825
1826 #[test]
1827 fn as_json_bridges_a_data_generic() {
1828 let mut fns = exported_functions(
1829 "a.ts",
1830 "export function paginate<T>(items: T[], page: number): { data: T[] } { return { data: items } }\n",
1831 );
1832 assert!(js_only_reason(&fns[0], &[]).is_some());
1833 substitute_json(&mut fns[0], &["T".to_string()]);
1834 assert!(fns[0].type_params.is_empty());
1835 assert_eq!(fns[0].params[0].ts_type, "unknown[]");
1836 assert_eq!(fns[0].returns, "{ data: unknown[] }");
1837 assert!(js_only_reason(&fns[0], &[]).is_none());
1838 }
1839
1840 #[test]
1841 fn makes_rust_names() {
1842 assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
1843 assert_eq!(snake_case("type"), "r#type");
1844 assert_eq!(snake_case("toURL"), "to_url");
1845 assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
1846 }
1847}