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
37impl Kind {
38 pub fn label(self) -> &'static str {
39 match self {
40 Kind::Napi => "napi-rs",
41 Kind::Wasm => "wasm-bindgen",
42 Kind::Pyo3 => "PyO3",
43 Kind::CAbi => "the C ABI",
44 Kind::Ffi => "a JSON dispatcher",
45 }
46 }
47}
48
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
51pub enum Allocator {
52 #[default]
54 #[serde(rename = "mimalloc")]
55 #[value(name = "mimalloc")]
56 Mimalloc,
57 #[serde(rename = "rusty_alloc")]
59 #[value(name = "rusty_alloc", alias = "rusty-alloc")]
60 RustyAlloc,
61}
62
63impl Allocator {
64 fn is_default(&self) -> bool {
65 *self == Self::default()
66 }
67}
68
69#[derive(Clone, Debug, Serialize, Deserialize)]
71pub struct Manifest {
72 pub schema: String,
73 pub root: PathBuf,
76 #[serde(skip)]
79 pub root_written: Option<PathBuf>,
80 pub unit: String,
81 #[serde(default)]
82 pub language: crate::lang::Lang,
83 pub kind: Kind,
84 pub crate_name: String,
85 pub exports: Vec<ExportedFn>,
87 #[serde(default)]
89 pub classes: Vec<ExportedClass>,
90 #[serde(default)]
93 pub js_only: Vec<JsOnly>,
94 #[serde(default, skip_serializing_if = "Vec::is_empty")]
96 pub batches: Vec<crate::codegen_batch::Batch>,
97 #[serde(default, skip_serializing_if = "Allocator::is_default")]
99 pub allocator: Allocator,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub float_tolerance: Option<f64>,
103 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
105 pub ignore_key_order: bool,
106}
107
108#[derive(Clone, Debug, Serialize, Deserialize)]
109pub struct JsOnly {
110 pub name: String,
111 pub file: String,
112 pub line: u32,
113 pub reason: String,
114}
115
116fn has_functions(name: &str, local_types: &[LocalType], seen: &mut Vec<String>) -> bool {
119 if seen.iter().any(|s| s == name) {
120 return false;
121 }
122 seen.push(name.to_string());
123 let Some(t) = local_types.iter().find(|t| t.name == name) else {
124 return false;
125 };
126 let text = &t.text;
127 let method = text.lines().skip(1).any(|l| {
128 let l = l.trim().trim_start_matches("readonly ");
129 l.contains('(')
130 && l.split('(').next().is_some_and(|head| {
131 !head.is_empty()
132 && head
133 .chars()
134 .all(|c| c.is_alphanumeric() || c == '_' || c == '?')
135 })
136 });
137 if text.contains("=>") || method {
138 return true;
139 }
140 text.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
141 .filter(|w| !w.is_empty() && *w != name)
142 .any(|w| has_functions(w, local_types, seen))
143}
144
145pub fn ts_functions(root: &Path, file: &str, text: &str, types: &[LocalType]) -> Vec<ExportedFn> {
149 let mut functions = exported_functions(file, text);
150 crate::ts::jsdoc::apply_declarations(root, file, &mut functions);
151 for f in &mut functions {
152 for p in &mut f.params {
153 p.ts_type = resolve_aliases(&p.ts_type, types);
154 }
155 f.returns = resolve_aliases(&f.returns, types);
156 substitute_constraints(f, types);
157 }
158 functions
159}
160
161pub fn class_reason(class: &ExportedClass, types: &[LocalType], ts: bool) -> Option<String> {
164 let constructor = ts.then(|| ExportedFn {
165 name: format!("{} constructor", class.name),
166 file: class.file.clone(),
167 line: class.line,
168 params: class.constructor.clone(),
169 returns: "void".into(),
170 ..Default::default()
171 });
172 class.blocker.clone().or_else(|| {
173 constructor
174 .iter()
175 .chain(&class.methods)
176 .find_map(|m| js_only_reason(m, types).map(|r| format!("`{}`: {r}", m.name)))
177 })
178}
179
180pub fn js_only_reason(f: &ExportedFn, local_types: &[LocalType]) -> Option<String> {
185 if let Some(blocker) = &f.blocker {
186 return Some(blocker.clone());
187 }
188 if f.is_generator {
189 return Some("generator: returns a lazy iterator".into());
190 }
191 if f.uses_instanceof {
192 return Some("checks `instanceof`: class identity does not survive the bridge".into());
193 }
194 let types: Vec<&str> = f
195 .params
196 .iter()
197 .map(|p| p.ts_type.as_str())
198 .chain(std::iter::once(f.returns.as_str()))
199 .collect();
200 if types.iter().any(|t| t.contains("=>")) {
201 return Some("takes or returns a function".into());
202 }
203 let words = |t: &str| -> Vec<String> {
204 t.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
205 .filter(|w| !w.is_empty())
206 .map(str::to_string)
207 .collect()
208 };
209 for t in &types {
210 for word in words(t) {
211 match word.as_str() {
212 "RegExp" => return Some("takes or returns a RegExp".into()),
213 "Generator" | "Iterator" | "IterableIterator" | "AsyncGenerator"
214 | "AsyncIterable" => {
215 return Some(format!("uses `{word}`, a lazy iterator"));
216 }
217 "Function" => return Some("takes or returns a function".into()),
218 _ => {}
219 }
220 if f.type_params.contains(&word) {
221 return Some(format!(
222 "generic over `{word}`: values of any shape, functions included"
223 ));
224 }
225 if has_functions(&word, local_types, &mut Vec::new()) {
226 return Some(format!("uses `{word}`, which has function members"));
227 }
228 }
229 }
230 None
231}
232
233impl Manifest {
234 pub fn load(crate_dir: &Path) -> Result<Self> {
235 let path = crate_dir.join(MANIFEST);
236 let text = std::fs::read_to_string(&path).with_context(|| {
237 format!(
238 "reading {} (run `rust-anything bridge` first)",
239 path.display()
240 )
241 })?;
242 let mut manifest: Self =
243 serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
244 if manifest.root.is_relative() {
245 let resolved = crate_dir.join(&manifest.root);
246 let resolved = resolved.canonical().unwrap_or(resolved);
247 manifest.root_written = Some(std::mem::replace(&mut manifest.root, resolved));
248 }
249 Ok(manifest)
250 }
251
252 pub fn save(&self, crate_dir: &Path) -> Result<()> {
254 let mut m = self.clone();
255 if let Some(written) = m.root_written.take() {
256 m.root = written;
257 }
258 let path = crate_dir.join(MANIFEST);
259 std::fs::write(&path, serde_json::to_string_pretty(&m)? + "\n")
260 .with_context(|| format!("writing {}", path.display()))
261 }
262
263 pub fn lib_name(&self) -> String {
265 self.crate_name.replace('-', "_")
266 }
267}
268
269pub struct Options<'a> {
270 pub root: &'a Path,
271 pub unit: &'a str,
272 pub kind: Option<Kind>,
273 pub out: Option<PathBuf>,
274 pub name: Option<String>,
275 pub force: bool,
277 pub keep: Vec<String>,
279 pub lang: Option<crate::lang::Lang>,
281 pub batch: Vec<String>,
283 pub as_json: Vec<String>,
286 pub allocator: Allocator,
288}
289
290#[derive(Debug, Serialize)]
291pub struct Outcome {
292 pub crate_dir: PathBuf,
293 pub kind: Kind,
294 pub files: Vec<String>,
295 pub exports: Vec<String>,
296 pub notes: Vec<String>,
297}
298
299#[derive(Clone, Debug, PartialEq, Eq)]
301pub enum RType {
302 Str,
303 F64,
304 Int,
306 Bool,
307 Bytes,
309 Unit,
310 Vec(Box<RType>),
311 Opt(Box<RType>),
312 Json,
314}
315
316impl RType {
317 pub fn from_ts(ts: &str) -> Self {
318 let ts = ts.trim().trim_start_matches("readonly ").trim();
319 if let Some(inner) = ts.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
321 && balanced(inner)
322 {
323 return Self::from_ts(inner);
324 }
325 if let Some(inner) = ts
326 .strip_prefix("Promise<")
327 .and_then(|t| t.strip_suffix('>'))
328 {
329 return Self::from_ts(inner);
330 }
331 let parts = split_top(ts, '|');
332 if parts.len() > 1 {
333 let (nullish, rest): (Vec<&str>, Vec<&str>) = parts
334 .iter()
335 .partition(|p| matches!(p.trim(), "undefined" | "null" | "void"));
336 if rest.iter().all(|p| is_string_literal(p)) {
337 return Self::wrap_opt(Self::Str, !nullish.is_empty());
338 }
339 if rest.len() == 1 {
340 return Self::wrap_opt(Self::from_ts(rest[0]), !nullish.is_empty());
341 }
342 return Self::Json;
343 }
344 if let Some(inner) = ts.strip_suffix("[]") {
345 return Self::Vec(Box::new(Self::from_ts(
346 inner.trim_start_matches('(').trim_end_matches(')'),
347 )));
348 }
349 for wrapper in ["Array<", "ReadonlyArray<"] {
350 if let Some(inner) = ts.strip_prefix(wrapper).and_then(|t| t.strip_suffix('>')) {
351 return Self::Vec(Box::new(Self::from_ts(inner)));
352 }
353 }
354 if ts.starts_with("asserts ") {
356 return Self::Unit;
357 }
358 if let Some((subject, _)) = ts.split_once(" is ")
359 && subject
360 .trim()
361 .chars()
362 .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
363 {
364 return Self::Bool;
365 }
366 match ts {
367 "string" => Self::Str,
368 "number" => Self::F64,
369 "int" => Self::Int,
370 "boolean" => Self::Bool,
371 "pybytes" => Self::Bytes,
372 "void" | "undefined" => Self::Unit,
373 _ if is_string_literal(ts) => Self::Str,
374 _ => Self::Json,
375 }
376 }
377
378 fn wrap_opt(t: Self, optional: bool) -> Self {
379 if optional { Self::Opt(Box::new(t)) } else { t }
380 }
381
382 pub fn rust(&self) -> String {
383 match self {
384 Self::Str => "String".into(),
385 Self::F64 => "f64".into(),
386 Self::Int => "i64".into(),
387 Self::Bool => "bool".into(),
388 Self::Bytes => "Vec<u8>".into(),
389 Self::Unit => "()".into(),
390 Self::Vec(t) => format!("Vec<{}>", t.rust()),
391 Self::Opt(t) => format!("Option<{}>", t.rust()),
392 Self::Json => "serde_json::Value".into(),
393 }
394 }
395
396 pub fn contains_json(&self) -> bool {
397 match self {
398 Self::Json => true,
399 Self::Vec(t) | Self::Opt(t) => t.contains_json(),
400 _ => false,
401 }
402 }
403}
404
405fn is_string_literal(ts: &str) -> bool {
406 let ts = ts.trim();
407 ts.len() >= 2
408 && ((ts.starts_with('\'') && ts.ends_with('\''))
409 || (ts.starts_with('"') && ts.ends_with('"')))
410}
411
412fn balanced(ts: &str) -> bool {
413 let mut depth = 0i32;
414 for c in ts.chars() {
415 match c {
416 '(' => depth += 1,
417 ')' => {
418 depth -= 1;
419 if depth < 0 {
420 return false;
421 }
422 }
423 _ => {}
424 }
425 }
426 depth == 0
427}
428
429fn split_top(ts: &str, sep: char) -> Vec<&str> {
431 let mut out = Vec::new();
432 let mut depth = 0i32;
433 let mut start = 0;
434 for (i, c) in ts.char_indices() {
435 match c {
436 '<' | '(' | '[' | '{' => depth += 1,
437 '>' | ')' | ']' | '}' => depth -= 1,
438 c if c == sep && depth == 0 => {
439 out.push(ts[start..i].trim());
440 start = i + c.len_utf8();
441 }
442 _ => {}
443 }
444 }
445 out.push(ts[start..].trim());
446 out.retain(|p| !p.is_empty());
447 out
448}
449
450pub fn param_type(p: &crate::ts::exports::Param) -> RType {
452 let base = RType::from_ts(&p.ts_type);
453 let base = if p.rest {
454 match base {
455 RType::Vec(_) => base,
456 other => RType::Vec(Box::new(other)),
457 }
458 } else {
459 base
460 };
461 if p.optional && !matches!(base, RType::Opt(_)) {
462 RType::Opt(Box::new(base))
463 } else {
464 base
465 }
466}
467
468pub fn snake_case(name: &str) -> String {
469 let chars: Vec<char> = name.chars().collect();
470 let mut out = String::new();
471 for (i, &c) in chars.iter().enumerate() {
472 if c.is_uppercase() {
473 let prev = i.checked_sub(1).map(|j| chars[j]);
474 let next = chars.get(i + 1);
475 let boundary = prev.is_some_and(|p| p.is_lowercase() || p.is_ascii_digit())
476 || (prev.is_some_and(char::is_uppercase) && next.is_some_and(|n| n.is_lowercase()));
477 if boundary {
478 out.push('_');
479 }
480 out.extend(c.to_lowercase());
481 } else if c.is_alphanumeric() {
482 out.push(c);
483 } else {
484 out.push('_');
485 }
486 }
487 rust_ident(&out)
488}
489
490const KEYWORDS: &[&str] = &[
491 "as", "break", "const", "continue", "else", "enum", "extern", "false", "fn", "for", "if",
492 "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "static",
493 "struct", "trait", "true", "type", "unsafe", "use", "where", "while", "async", "await", "dyn",
494 "abstract", "become", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized",
495 "virtual", "yield", "try", "gen",
496];
497
498pub(crate) fn rust_ident(word: &str) -> String {
499 if matches!(word, "self" | "Self" | "super" | "crate" | "_") {
500 format!("{word}_")
501 } else if KEYWORDS.contains(&word) {
502 format!("r#{word}")
503 } else {
504 word.to_string()
505 }
506}
507
508pub fn types_in_scope(root: &Path, file: &str, text: &str) -> Vec<LocalType> {
510 let mut types = Vec::new();
511 let mut seen = std::collections::HashSet::new();
512 collect_types(root, file, text, 0, &mut seen, &mut types);
513 types
514}
515
516fn collect_types(
519 root: &Path,
520 file: &str,
521 text: &str,
522 depth: usize,
523 seen: &mut std::collections::HashSet<String>,
524 types: &mut Vec<LocalType>,
525) {
526 if depth > 4 || !seen.insert(file.to_string()) {
527 return;
528 }
529 types.extend(local_types(file, text));
530 let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
531 for import in crate::ts::scan::scan(file, text).imports {
532 let spec = import.specifier;
533 let base = if spec.starts_with('.') {
535 let joined = if dir.is_empty() {
536 spec.clone()
537 } else {
538 format!("{dir}/{spec}")
539 };
540 match normalize_rel(&joined) {
541 Some(base) => base,
542 None => continue,
543 }
544 } else {
545 let name = crate::ts::deps::package_name(&spec);
546 let Some(pkg_dir) = workspace_packages(root).get(name).cloned() else {
547 continue;
548 };
549 let sub = spec[name.len()..].trim_start_matches('/');
550 let src = if root.join(&pkg_dir).join("src").is_dir() {
551 format!("{pkg_dir}/src")
552 } else {
553 pkg_dir
554 };
555 let src = src.trim_start_matches('/').to_string();
556 if sub.is_empty() {
557 format!("{src}/index")
558 } else {
559 format!("{src}/{sub}")
560 }
561 };
562 let stem = base.trim_end_matches(".js");
563 let candidates = [
564 format!("{stem}.ts"),
565 format!("{stem}.mts"),
566 format!("{stem}.d.ts"),
567 format!("{stem}/index.ts"),
568 base.clone(),
569 ];
570 if let Some(found) = candidates.iter().find(|c| root.join(c).is_file())
571 && let Ok(imported) = std::fs::read_to_string(root.join(found))
572 {
573 collect_types(root, found, &imported, depth + 1, seen, types);
574 }
575 }
576}
577
578fn workspace_packages(root: &Path) -> std::collections::HashMap<String, String> {
580 use std::sync::{Mutex, OnceLock};
581 static CACHE: OnceLock<
582 Mutex<std::collections::HashMap<PathBuf, std::collections::HashMap<String, String>>>,
583 > = OnceLock::new();
584 let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
585 let mut cache = cache
586 .lock()
587 .unwrap_or_else(std::sync::PoisonError::into_inner);
588 cache
589 .entry(root.to_path_buf())
590 .or_insert_with(|| {
591 crate::ts::discover::discover(root)
592 .map(|ws| ws.packages.into_iter().map(|p| (p.name, p.dir)).collect())
593 .unwrap_or_default()
594 })
595 .clone()
596}
597
598fn normalize_rel(path: &str) -> Option<String> {
600 let mut parts: Vec<&str> = Vec::new();
601 for part in path.split('/') {
602 match part {
603 "" | "." => {}
604 ".." => {
605 parts.pop()?;
606 }
607 _ => parts.push(part),
608 }
609 }
610 Some(parts.join("/"))
611}
612
613pub fn substitute_constraints(f: &mut ExportedFn, types: &[LocalType]) {
616 let mut remaining = Vec::new();
617 for tp in std::mem::take(&mut f.type_params) {
618 let Some((name, constraint)) = tp.split_once(" extends ") else {
619 remaining.push(tp);
620 continue;
621 };
622 let constraint = resolve_aliases(constraint, types);
623 let open_ended = constraint.contains("=>")
626 || constraint
627 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
628 .any(|w| {
629 matches!(w, "Function" | "object" | "unknown" | "any")
630 || has_functions(w, types, &mut Vec::new())
631 });
632 if open_ended {
633 remaining.push(name.to_string());
634 continue;
635 }
636 let replacement = format!("({constraint})");
637 for p in &mut f.params {
638 p.ts_type = replace_word(&p.ts_type, name, &replacement);
639 }
640 f.returns = replace_word(&f.returns, name, &replacement);
641 }
642 f.type_params = remaining;
643}
644
645fn type_param_name(tp: &str) -> &str {
647 tp.split_once(" extends ").map_or(tp, |(n, _)| n).trim()
648}
649
650fn declared_type_params(root: &Path, file: &str, text: &str) -> Vec<String> {
653 let mut functions = exported_functions(file, text);
654 crate::ts::jsdoc::apply_declarations(root, file, &mut functions);
655 functions
656 .iter()
657 .flat_map(|f| {
658 f.type_params
659 .iter()
660 .map(|tp| type_param_name(tp).to_string())
661 })
662 .collect()
663}
664
665pub fn substitute_json(f: &mut ExportedFn, names: &[String]) {
667 let mut remaining = Vec::new();
668 for tp in std::mem::take(&mut f.type_params) {
669 let name = type_param_name(&tp);
670 if !names.iter().any(|n| n == name) {
671 remaining.push(tp);
672 continue;
673 }
674 for p in &mut f.params {
675 p.ts_type = replace_word(&p.ts_type, name, "unknown");
676 }
677 f.returns = replace_word(&f.returns, name, "unknown");
678 }
679 f.type_params = remaining;
680}
681
682fn replace_word(text: &str, word: &str, with: &str) -> String {
683 let mut out = String::new();
684 let mut current = String::new();
685 for c in text.chars().chain(std::iter::once(' ')) {
686 if c.is_alphanumeric() || c == '_' || c == '$' {
687 current.push(c);
688 } else {
689 out.push_str(if current == word { with } else { ¤t });
690 current.clear();
691 out.push(c);
692 }
693 }
694 out.pop();
695 out
696}
697
698pub fn resolve_aliases(ts: &str, types: &[LocalType]) -> String {
700 let mut out = ts.to_string();
701 for _ in 0..4 {
702 let mut changed = false;
703 let mut next = String::with_capacity(out.len());
704 let mut word = String::new();
705 let flush = |word: &mut String, next: &mut String, changed: &mut bool| {
706 if let Some(t) = types.iter().find(|t| t.alias && t.name == *word) {
707 let text = t.text.trim();
708 if text.contains('|') {
709 next.push('(');
710 next.push_str(text);
711 next.push(')');
712 } else {
713 next.push_str(text);
714 }
715 *changed = true;
716 } else {
717 next.push_str(word);
718 }
719 word.clear();
720 };
721 for c in out.chars() {
722 if c.is_alphanumeric() || c == '_' || c == '$' {
723 word.push(c);
724 } else {
725 flush(&mut word, &mut next, &mut changed);
726 next.push(c);
727 }
728 }
729 flush(&mut word, &mut next, &mut changed);
730 out = next;
731 if !changed {
732 break;
733 }
734 }
735 out
736}
737
738fn needs_js(api: &codegen::PortApi) -> bool {
739 api.needs_json()
740}
741
742fn keep_entry(k: &str) -> (&str, &str) {
744 let (name, reason) = k.split_once(':').unwrap_or((k, ""));
745 (name.trim(), reason.trim())
746}
747
748fn check_keep(keep: &[String], names: &[&str], unit: &str) -> Result<()> {
751 if let Some((name, _)) = keep
752 .iter()
753 .map(|k| keep_entry(k))
754 .find(|(name, _)| !names.contains(name))
755 {
756 let mut known = names.to_vec();
757 known.sort_unstable();
758 known.dedup();
759 bail!(
760 "--keep `{name}` is not an export of `{unit}` (exports: {})",
761 known.join(", ")
762 );
763 }
764 Ok(())
765}
766
767fn check_as_json(as_json: &[String], type_params: &[String], unit: &str) -> Result<()> {
770 if let Some(name) = as_json.iter().find(|n| !type_params.contains(n)) {
771 let mut known = type_params.to_vec();
772 known.sort_unstable();
773 known.dedup();
774 if known.is_empty() {
775 bail!("--as-json `{name}` is not a type parameter of `{unit}` (it has none)");
776 }
777 bail!(
778 "--as-json `{name}` is not a type parameter of `{unit}` (type parameters: {})",
779 known.join(", ")
780 );
781 }
782 Ok(())
783}
784
785fn keep_reason(keep: &[String], name: &str) -> Option<String> {
787 keep.iter().find_map(|k| {
788 let (kept, reason) = keep_entry(k);
789 (kept == name).then(|| {
790 if reason.is_empty() {
791 "kept on request".to_string()
792 } else {
793 reason.to_string()
794 }
795 })
796 })
797}
798
799fn format_rust(crate_dir: &Path) {
801 let files: Vec<PathBuf> = std::fs::read_dir(crate_dir.join("src"))
802 .into_iter()
803 .flatten()
804 .flatten()
805 .map(|e| e.path())
806 .filter(|p| p.extension().is_some_and(|e| e == "rs"))
807 .collect();
808 let _ = std::process::Command::new("rustfmt")
809 .args(["--edition", "2024"])
810 .args(&files)
811 .output();
812}
813
814fn format_wrapper(crate_dir: &Path) {
816 if crate_dir.join("go").is_dir() {
817 let _ = std::process::Command::new("gofmt")
818 .arg("-w")
819 .arg(crate_dir.join("go"))
820 .output();
821 }
822}
823
824fn js_lib_rs(m: &Manifest, api: &codegen::PortApi, modules: &codegen::Modules) -> Result<String> {
826 let mut lib = with_allocator(m, codegen::lib_rs(m, api, modules));
827 if m.kind != Kind::Pyo3 && !m.batches.is_empty() {
828 lib.push_str(&crate::codegen_batch::js_rs(m, api).map_err(anyhow::Error::msg)?);
829 }
830 if !crate::codegen_tswire::uses_wire(m, api) {
831 return Ok(lib);
832 }
833 Ok(lib.replacen(
834 "pub mod port;",
835 "pub mod port;\npub mod wire;\n\n#[allow(unused_imports)]\nuse serde_json::Value;",
836 1,
837 ) + &crate::codegen_tswire::napi_rs(m, api))
838}
839
840fn parse_batches(specs: &[String]) -> Result<Vec<crate::codegen_batch::Batch>> {
841 specs
842 .iter()
843 .map(|s| {
844 crate::codegen_batch::Batch::parse(s)
845 .with_context(|| format!("`--batch {s}`: write it as function:param"))
846 })
847 .collect()
848}
849
850fn ensure_batch_support(lang: crate::lang::Lang, kind: Kind) -> Result<()> {
853 use crate::lang::Lang;
854 let unsupported = match lang {
855 Lang::C | Lang::Php | Lang::Csharp | Lang::Powershell => Some(lang.name()),
856 _ if kind == Kind::CAbi => Some(Lang::C.name()),
857 _ => None,
858 };
859 if let Some(name) = unsupported {
860 bail!("`--batch` is not available for {name} units yet");
861 }
862 Ok(())
863}
864
865pub fn add_batches(crate_dir: &Path, specs: &[String]) -> Result<Refreshed> {
867 let path = crate_dir.join(MANIFEST);
868 let before = std::fs::read_to_string(&path).with_context(|| format!("{}", path.display()))?;
869 let mut manifest = Manifest::load(crate_dir)?;
870 if !specs.is_empty() {
871 ensure_batch_support(manifest.language, manifest.kind)?;
872 }
873 for b in parse_batches(specs)? {
874 if !manifest.batches.contains(&b) {
875 manifest.batches.push(b);
876 }
877 }
878 if let Some(written) = manifest.root_written.clone() {
879 manifest.root = written;
880 }
881 std::fs::write(&path, serde_json::to_string_pretty(&manifest)? + "\n")?;
882 refresh(crate_dir).inspect_err(|_| {
884 let _ = std::fs::write(&path, &before);
885 })
886}
887
888fn with_template_deps(cargo: &str, template: &str) -> Result<String> {
891 let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
892 let template: toml_edit::DocumentMut = template.parse().context("Cargo.toml template")?;
893 if let Some(want) = template.get("dependencies").and_then(|d| d.as_table()) {
894 let deps = doc["dependencies"].or_insert(toml_edit::table());
895 for (name, item) in want {
896 if deps.get(name).is_none() {
897 deps[name] = item.clone();
898 }
899 }
900 }
901 if let Some(want) = template.get("features").and_then(|d| d.as_table()) {
902 let features = doc["features"].or_insert(toml_edit::table());
903 for (name, item) in want {
904 if features.get(name).is_none() {
905 features[name] = item.clone();
906 }
907 }
908 }
909 if let Some(kinds) = template.get("lib").and_then(|l| l.get("crate-type")) {
910 doc["lib"]["crate-type"] = kinds.clone();
911 }
912 Ok(doc.to_string())
913}
914
915fn global_allocator(m: &Manifest) -> Option<Allocator> {
920 if m.batches.is_empty() {
921 return None;
922 }
923 match m.allocator {
924 Allocator::Mimalloc if m.kind == Kind::Wasm => None,
925 a => Some(a),
926 }
927}
928
929fn with_allocator(m: &Manifest, lib: String) -> String {
931 let line = match global_allocator(m) {
932 None => return lib,
933 Some(Allocator::Mimalloc) => {
934 "/// Batches allocate on all cores at once; mimalloc keeps that from serializing.\n\
935 #[global_allocator]\nstatic GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;\n"
936 }
937 Some(Allocator::RustyAlloc) => {
938 "/// Batches allocate on all cores at once; rusty_alloc keeps that from serializing.\n\
939 #[global_allocator]\n\
940 static GLOBAL: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;\n"
941 }
942 };
943 lib.replacen("pub mod port;", &format!("pub mod port;\n\n{line}"), 1)
944}
945
946fn with_rayon(m: &Manifest, cargo: String) -> Result<String> {
948 let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
949 let deps = doc["dependencies"].or_insert(toml_edit::table());
950 if m.kind == Kind::Napi
952 && !m.batches.is_empty()
953 && let Some(napi) = deps.get_mut("napi")
954 {
955 let mut table = toml_edit::InlineTable::new();
956 match napi {
957 toml_edit::Item::Value(toml_edit::Value::String(v)) => {
958 table.insert("version", v.value().clone().into());
959 }
960 toml_edit::Item::Value(toml_edit::Value::InlineTable(t)) => table = t.clone(),
961 _ => {}
962 }
963 let mut features = table
964 .get("features")
965 .and_then(|f| f.as_array())
966 .cloned()
967 .unwrap_or_default();
968 if !features.iter().any(|f| f.as_str() == Some("serde-json")) {
969 features.push("serde-json");
970 }
971 table.insert("features", toml_edit::Value::Array(features));
972 *napi = toml_edit::value(table);
973 }
974 if !crate::codegen_batch::needs_rayon(m) {
975 return Ok(doc.to_string());
976 }
977 if deps.get("rayon").is_none() {
978 deps["rayon"] = toml_edit::value("1");
979 }
980 let allocator = match global_allocator(m) {
981 Some(Allocator::Mimalloc) => Some(("mimalloc", "0.1")),
982 Some(Allocator::RustyAlloc) => Some(("rusty_alloc-api", "2.6")),
983 None => None,
984 };
985 if let Some((name, version)) = allocator
986 && deps.get(name).is_none()
987 {
988 deps[name] = toml_edit::value(version);
989 }
990 Ok(doc.to_string())
991}
992
993fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
995 match m.kind {
996 Kind::Pyo3 => (
997 format!("python/{}/__init__.py", m.lib_name()),
998 crate::codegen_py::package_init(m, api),
999 ),
1000 _ => (
1001 "index.cjs".into(),
1002 codegen::index_cjs(m, api)
1003 + &crate::codegen_tswire::index_cjs(m, api)
1004 + &crate::codegen_batch::index_cjs(m, api)
1005 + &codegen::guard_cjs(api, &crate::codegen_tswire::wired(m, api)),
1006 ),
1007 }
1008}
1009
1010pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
1013 for f in &mut api.functions {
1014 if m.exports.iter().any(|e| e.name == f.js_name) {
1015 continue;
1016 }
1017 let rust = f.rust_name.trim_start_matches("r#");
1018 if let Some(e) = m
1019 .exports
1020 .iter()
1021 .find(|e| snake_case(&e.name).trim_start_matches("r#") == rust)
1022 {
1023 f.js_name = e.name.clone();
1024 }
1025 }
1026}
1027
1028#[derive(Debug, Serialize)]
1030pub struct Refreshed {
1031 pub functions: Vec<String>,
1032 pub files: Vec<String>,
1033}
1034
1035pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
1038 let manifest = Manifest::load(crate_dir)?;
1039 if manifest.kind == Kind::CAbi {
1040 let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
1041 .context("reading src/port.rs")?;
1042 let mut files = c_bindings(&manifest, &port);
1043 let cargo =
1044 std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
1045 files.push((
1046 "Cargo.toml".into(),
1047 with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
1048 ));
1049 write_files(crate_dir, &files)?;
1050 format_rust(crate_dir);
1051 return Ok(Refreshed {
1052 functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1053 files: files.into_iter().map(|(p, _)| p).collect(),
1054 });
1055 }
1056 if manifest.kind == Kind::Ffi {
1057 let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
1058 .context("reading src/port.rs")?;
1059 let mut api = codegen::parse_port(&port);
1060 match_export_names(&manifest, &mut api);
1061 let mut files = ffi_bindings(&manifest, &api)?;
1062 let cargo =
1063 std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
1064 let template = if manifest.language == crate::lang::Lang::Ruby {
1065 crate::codegen_ruby::cargo_toml(&manifest)
1066 } else {
1067 crate::codegen_ffi::cargo_toml(&manifest)
1068 };
1069 let cargo = with_template_deps(&cargo, &template)?;
1070 files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
1071 write_files(crate_dir, &files)?;
1072 format_rust(crate_dir);
1073 format_wrapper(crate_dir);
1074 return Ok(Refreshed {
1075 functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
1076 files: files.into_iter().map(|(p, _)| p).collect(),
1077 });
1078 }
1079 let port =
1080 std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
1081 let mut fns = codegen::parse_port(&port);
1082 match_export_names(&manifest, &mut fns);
1083 if fns.functions.is_empty() && fns.classes.is_empty() {
1084 bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
1085 }
1086 let modules = codegen::Modules {
1087 utf16: crate_dir.join("src/utf16.rs").exists(),
1088 js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
1089 };
1090 let mut files: Vec<(String, String)> = vec![
1091 ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1092 loader_file(&manifest, &fns),
1093 ];
1094 if modules.js {
1095 files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
1096 }
1097 if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1098 files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1099 }
1100 let extension = manifest.kind == Kind::Pyo3
1101 || (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
1102 if extension && !crate_dir.join("build.rs").exists() {
1103 files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
1104 }
1105 if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1106 files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1107 files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1108 }
1109 let cargo_path = crate_dir.join("Cargo.toml");
1110 let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
1111 let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns).map_err(anyhow::Error::msg)?;
1112 let cargo = with_rayon(&manifest, cargo)?;
1113 files.push(("Cargo.toml".into(), cargo));
1114 for (path, text) in &files {
1115 let target = crate_dir.join(path);
1116 if let Some(parent) = target.parent() {
1117 std::fs::create_dir_all(parent)?;
1118 }
1119 std::fs::write(&target, text).with_context(|| format!("writing {path}"))?;
1120 }
1121 format_rust(crate_dir);
1122 Ok(Refreshed {
1123 functions: fns
1124 .functions
1125 .iter()
1126 .map(|f| f.js_name.clone())
1127 .chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
1128 .collect(),
1129 files: files.into_iter().map(|(p, _)| p).collect(),
1130 })
1131}
1132
1133pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
1136 if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
1137 println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
1138 }
1139}
1140"#;
1141
1142fn validate_crate_name(name: &str) -> Result<&str> {
1145 const RUST_KEYWORDS: &[&str] = &[
1146 "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
1147 "extern", "false", "fn", "for", "gen", "if", "impl", "in", "let", "loop", "match", "mod",
1148 "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super",
1149 "trait", "true", "type", "unsafe", "use", "where", "while", "abstract", "become", "box",
1150 "do", "final", "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
1151 ];
1152 const WINDOWS_RESERVED: &[&str] = &[
1153 "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",
1154 "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
1155 ];
1156 let first = name.bytes().next();
1157 let valid_chars = first.is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
1158 && name
1159 .bytes()
1160 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
1161 if !valid_chars {
1162 bail!(
1163 "invalid crate name `{name}`: must be non-empty, start with an ASCII letter or `_`, \
1164 and use only ASCII letters, digits, `-` and `_`"
1165 );
1166 }
1167 let lib = name.replace('-', "_");
1168 if lib == "_" || RUST_KEYWORDS.contains(&lib.as_str()) {
1169 bail!("invalid crate name `{name}`: `{lib}` is a reserved Rust keyword");
1170 }
1171 let lower = name.to_ascii_lowercase();
1172 if WINDOWS_RESERVED.contains(&lower.as_str()) {
1173 bail!("invalid crate name `{name}`: `{name}` is a reserved filename on Windows");
1174 }
1175 Ok(name)
1176}
1177
1178fn default_crate_name(stem: &str) -> String {
1180 let clean: String = stem
1181 .chars()
1182 .map(|c| {
1183 if c.is_ascii_alphanumeric() {
1184 c.to_ascii_lowercase()
1185 } else {
1186 '-'
1187 }
1188 })
1189 .collect();
1190 let trimmed = clean.trim_matches('-');
1191 if trimmed.is_empty() {
1192 "unit-rs".to_string()
1193 } else if trimmed.as_bytes()[0].is_ascii_digit() {
1194 format!("unit-{trimmed}-rs")
1195 } else {
1196 format!("{trimmed}-rs")
1197 }
1198}
1199
1200pub fn bridge(opts: &Options) -> Result<Outcome> {
1201 let explicit_name = opts.name.as_deref().map(validate_crate_name).transpose()?;
1202 let root = opts
1203 .root
1204 .canonical()
1205 .with_context(|| format!("resolving {}", opts.root.display()))?;
1206 let lang = opts
1207 .lang
1208 .unwrap_or_else(|| crate::lang::Lang::detect(&root));
1209 let report = analyze::analyze_lang(&root, lang)?;
1210 let wanted = opts.unit.trim_start_matches("./");
1211 let whole = report
1212 .units
1213 .iter()
1214 .find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'));
1215 let single = || {
1216 report
1217 .units
1218 .iter()
1219 .find(|u| u.files.iter().any(|f| f == wanted))
1220 .map(|u| {
1221 let mut one = u.clone();
1222 one.id = wanted.to_string();
1223 one.files = vec![wanted.to_string()];
1224 one
1225 })
1226 };
1227 let unit = match whole.cloned().or_else(single) {
1228 Some(unit) => unit,
1229 None => bail!(
1230 "no unit or source file `{wanted}`; `rust-anything analyze` lists unit ids, and any \
1231 source file inside a unit can be bridged on its own"
1232 ),
1233 };
1234 let unit = &unit;
1235 if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
1236 bail!(
1237 "unit `{}` is {}: {}. Pass --force to bridge it anyway.",
1238 unit.id,
1239 unit.status.label(),
1240 unit.notes.first().map_or("", String::as_str)
1241 );
1242 }
1243 if let Some(k @ (Kind::Napi | Kind::Wasm)) = opts.kind
1244 && lang != crate::lang::Lang::Ts
1245 {
1246 bail!(
1247 "--kind {} is for TS/JS units; {wanted} is {} and is bridged with {}",
1248 if k == Kind::Napi { "napi" } else { "wasm" },
1249 lang.name(),
1250 Bridge::for_lang(lang).label()
1251 );
1252 }
1253 let kind = opts.kind.unwrap_or(match unit.bridge {
1254 Bridge::WasmBindgen => Kind::Wasm,
1255 Bridge::Pyo3 => Kind::Pyo3,
1256 Bridge::CAbi => Kind::CAbi,
1257 Bridge::Cgo
1258 | Bridge::Fiddle
1259 | Bridge::Jni
1260 | Bridge::PhpFfi
1261 | Bridge::DotnetFfi
1262 | Bridge::PwshFfi => Kind::Ffi,
1263 _ => Kind::Napi,
1264 });
1265 if !opts.batch.is_empty() {
1266 ensure_batch_support(lang, kind)?;
1267 }
1268
1269 let mut exports = Vec::new();
1270 let mut classes = Vec::new();
1271 let mut js_only = Vec::new();
1272 let mut type_params = Vec::new();
1274 let mut kept_overloads = std::collections::HashSet::new();
1276 if lang == crate::lang::Lang::C {
1277 crate::lang::c::use_typedefs(&root);
1278 }
1279 if lang == crate::lang::Lang::Csharp {
1280 crate::lang::csharp::use_shapes(&root);
1281 }
1282 for file in &unit.files {
1283 if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
1284 continue;
1285 }
1286 let text =
1287 std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
1288 if lang != crate::lang::Lang::Ts {
1289 let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
1290 for f in functions {
1291 let overload = f.blocker.as_deref() == Some(crate::lang::OVERLOADED);
1295 match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
1296 Some(_)
1297 if overload && !kept_overloads.insert((f.name.clone(), f.file.clone())) => {
1298 }
1299 Some(reason) => js_only.push(JsOnly {
1300 name: f.name,
1301 file: f.file,
1302 line: f.line,
1303 reason,
1304 }),
1305 None => exports.push(f),
1306 }
1307 }
1308 for class in foreign_classes {
1309 match keep_reason(&opts.keep, &class.name)
1310 .or_else(|| class_reason(&class, &[], false))
1311 {
1312 Some(reason) => js_only.push(JsOnly {
1313 name: class.name,
1314 file: class.file,
1315 line: class.line,
1316 reason: format!("class: {reason}"),
1317 }),
1318 None => classes.push(class),
1319 }
1320 }
1321 continue;
1322 }
1323 let types = types_in_scope(&root, file, &text);
1324 for mut class in exported_classes(file, &text) {
1325 let kept = keep_reason(&opts.keep, &class.name);
1326 match kept.or_else(|| class_reason(&class, &types, true)) {
1327 Some(reason) => js_only.push(JsOnly {
1328 name: class.name,
1329 file: class.file,
1330 line: class.line,
1331 reason: format!("class: {reason}"),
1332 }),
1333 None => {
1334 for p in &mut class.constructor {
1335 p.ts_type = resolve_aliases(&p.ts_type, &types);
1336 }
1337 for m in &mut class.methods {
1338 for p in &mut m.params {
1339 p.ts_type = resolve_aliases(&p.ts_type, &types);
1340 }
1341 m.returns = resolve_aliases(&m.returns, &types);
1342 }
1343 classes.push(class);
1344 }
1345 }
1346 }
1347 type_params.extend(declared_type_params(&root, file, &text));
1348 for mut f in ts_functions(&root, file, &text, &types) {
1349 substitute_json(&mut f, &opts.as_json);
1350 let kept = keep_reason(&opts.keep, &f.name);
1351 match kept.or_else(|| js_only_reason(&f, &types)) {
1352 Some(reason) => js_only.push(JsOnly {
1353 name: f.name,
1354 file: f.file,
1355 line: f.line,
1356 reason,
1357 }),
1358 None => exports.push(f),
1359 }
1360 }
1361 }
1362 let mut defined: Vec<(&str, String)> = exports
1363 .iter()
1364 .map(|f| (f.name.as_str(), format!("{}:{}", f.file, f.line)))
1365 .chain(
1366 classes
1367 .iter()
1368 .map(|c| (c.name.as_str(), format!("{}:{}", c.file, c.line))),
1369 )
1370 .chain(
1371 js_only
1372 .iter()
1373 .map(|j| (j.name.as_str(), format!("{}:{}", j.file, j.line))),
1374 )
1375 .collect();
1376 defined.sort();
1377 check_keep(
1378 &opts.keep,
1379 &defined.iter().map(|(name, _)| *name).collect::<Vec<_>>(),
1380 &unit.id,
1381 )?;
1382 check_as_json(&opts.as_json, &type_params, &unit.id)?;
1383 if let Some(pair) = defined.windows(2).find(|w| w[0].0 == w[1].0) {
1384 bail!(
1385 "`{}` is defined twice in `{}` ({} and {}), and the bridge names every export by \
1386 itself, so one would silently replace the other. Bridge the module you want on its \
1387 own (`rust-anything bridge <root> <that file>`), or rename one of them",
1388 pair[0].0,
1389 unit.id,
1390 pair[0].1,
1391 pair[1].1
1392 );
1393 }
1394 if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1395 bail!(
1396 "every export of `{}` must stay in {}: {}",
1397 unit.id,
1398 lang.name(),
1399 js_only
1400 .iter()
1401 .map(|j| format!("{} ({})", j.name, j.reason))
1402 .collect::<Vec<_>>()
1403 .join(", ")
1404 );
1405 }
1406 if exports.is_empty() && classes.is_empty() {
1407 bail!(
1408 "unit `{}` exports no functions; bridge a unit with an exported function API",
1409 unit.id
1410 );
1411 }
1412
1413 let stem = unit
1414 .id
1415 .trim_end_matches('/')
1416 .rsplit('/')
1417 .next()
1418 .unwrap_or("unit")
1419 .split('.')
1420 .next()
1421 .unwrap_or("unit");
1422 let crate_name = explicit_name
1423 .map(str::to_string)
1424 .unwrap_or_else(|| default_crate_name(stem));
1425 let crate_dir = opts
1426 .out
1427 .clone()
1428 .unwrap_or_else(|| root.join("rust").join(&crate_name));
1429 if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1430 bail!(
1431 "{dir} already exists and is not empty; rust-anything never overwrites a port in \
1432 progress. Run `rust-anything refresh {dir}` to regenerate the bindings, pass --out or \
1433 --name for a new crate, or remove the folder to start over",
1434 dir = crate_dir.display()
1435 );
1436 }
1437
1438 let utf16 =
1440 lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1441 let manifest = Manifest {
1442 schema: SCHEMA.into(),
1443 root: root.clone(),
1444 root_written: None,
1445 unit: unit.id.clone(),
1446 language: lang,
1447 kind,
1448 crate_name: crate_name.clone(),
1449 exports: exports.clone(),
1450 classes: classes.clone(),
1451 js_only: js_only.clone(),
1452 batches: parse_batches(&opts.batch)?,
1453 allocator: opts.allocator,
1454 float_tolerance: None,
1455 ignore_key_order: false,
1456 };
1457 if kind == Kind::CAbi {
1458 return bridge_c(&manifest, &crate_dir, &js_only);
1459 }
1460 if kind == Kind::Ffi {
1461 return bridge_ffi(&manifest, &crate_dir, &js_only);
1462 }
1463 let port = codegen::port_rs(&manifest);
1464 let fns = codegen::parse_port(&port);
1465 let modules = codegen::Modules {
1466 utf16,
1467 js: needs_js(&fns),
1468 };
1469 let mut files: Vec<(String, String)> = vec![
1470 (
1471 "Cargo.toml".into(),
1472 with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1473 ),
1474 ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1475 ("src/port.rs".into(), port),
1476 loader_file(&manifest, &fns),
1477 (
1478 ".gitignore".into(),
1479 "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1480 ),
1481 ("README.md".into(), readme(&manifest)),
1482 (
1483 MANIFEST.into(),
1484 serde_json::to_string_pretty(&manifest)? + "\n",
1485 ),
1486 ];
1487 match kind {
1488 Kind::Napi => files.push((
1489 "build.rs".into(),
1490 "fn main() {\n napi_build::setup();\n}\n".into(),
1491 )),
1492 Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1493 _ => {}
1494 }
1495 if utf16 {
1496 files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1497 }
1498 if modules.js {
1499 files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1500 }
1501 if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1502 files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1503 }
1504 if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1505 files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1506 files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1507 }
1508 for (path, text) in &files {
1509 let target = crate_dir.join(path);
1510 if let Some(parent) = target.parent() {
1511 std::fs::create_dir_all(parent)?;
1512 }
1513 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1514 }
1515
1516 format_rust(&crate_dir);
1517 let mut notes = vec![format!(
1518 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1519 crate_dir.display()
1520 )];
1521 if utf16 {
1522 notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1523 }
1524 for j in &js_only {
1525 notes.push(format!(
1526 "`{}` stays in {}: {}. The shadow module re-exports the original.",
1527 j.name,
1528 lang.name(),
1529 j.reason
1530 ));
1531 }
1532 if exports.iter().any(codegen::is_async) {
1533 notes.push(
1534 "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1535 );
1536 }
1537 Ok(Outcome {
1538 crate_dir,
1539 kind,
1540 files: files.into_iter().map(|(p, _)| p).collect(),
1541 exports: exports
1542 .iter()
1543 .map(|f| f.name.clone())
1544 .chain(classes.iter().map(|c| format!("class {}", c.name)))
1545 .collect(),
1546 notes,
1547 })
1548}
1549
1550fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1551 for (path, text) in files {
1552 let target = crate_dir.join(path);
1553 if let Some(parent) = target.parent() {
1554 std::fs::create_dir_all(parent)?;
1555 }
1556 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1557 }
1558 Ok(())
1559}
1560
1561fn c_bindings(m: &Manifest, port: &str) -> Vec<(String, String)> {
1564 vec![
1565 ("src/lib.rs".into(), crate::codegen_c::lib_rs(m, port)),
1566 (
1567 format!("include/{}.h", m.lib_name()),
1568 crate::codegen_c::header(m),
1569 ),
1570 ]
1571}
1572
1573fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1575 let mut files = if m.language == crate::lang::Lang::Ruby {
1576 vec![
1577 (
1578 "src/lib.rs".to_string(),
1579 with_allocator(
1580 m,
1581 crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1582 ),
1583 ),
1584 (
1585 "src/rbconv.rs".to_string(),
1586 crate::codegen_ruby::RBCONV_RS.to_string(),
1587 ),
1588 ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1589 ]
1590 } else {
1591 let mut lib = crate::codegen_ffi::lib_rs(m, api);
1592 if matches!(
1593 m.language,
1594 crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1595 ) {
1596 lib.push_str(&crate::codegen_java::typed_rs(m, api));
1597 }
1598 if m.language == crate::lang::Lang::Go {
1599 lib.push_str(&crate::codegen_go::typed_rs(m, api));
1600 lib.push_str(&crate::codegen_go::wire_rs(m, api));
1601 lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1602 }
1603 if matches!(
1604 m.language,
1605 crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1606 ) {
1607 lib.push_str(&crate::codegen_java::wire_rs(m, api));
1608 lib.push_str(
1609 &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1610 );
1611 }
1612 if matches!(
1613 m.language,
1614 crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1615 ) {
1616 lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1617 }
1618 let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1619 if matches!(
1620 m.language,
1621 crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
1622 ) {
1623 files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1624 }
1625 files
1626 };
1627 match m.language {
1628 crate::lang::Lang::Go => {
1629 if crate::codegen_go::unit_sources(m).is_empty() {
1632 bail!(
1633 "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1634 m.unit,
1635 m.root.display()
1636 );
1637 }
1638 files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1639 files.push((
1640 format!("go/{}.go", crate::codegen_go::package_name(m)),
1641 crate::codegen_go::wrapper(m, api),
1642 ));
1643 }
1644 crate::lang::Lang::Ruby => {
1645 files.push((
1646 crate::harness_ruby::wrapper_path(m),
1647 crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1648 ));
1649 }
1650 crate::lang::Lang::Php => {
1651 files.push((
1652 crate::codegen_php::wrapper_path(m),
1653 crate::codegen_php::wrapper(m),
1654 ));
1655 }
1656 crate::lang::Lang::Csharp => {
1657 files.push((
1658 crate::codegen_csharp::wrapper_path(m),
1659 crate::codegen_csharp::wrapper(m),
1660 ));
1661 }
1662 crate::lang::Lang::Powershell => {
1663 files.push((
1664 crate::codegen_powershell::wrapper_path(m),
1665 crate::codegen_powershell::wrapper(m),
1666 ));
1667 }
1668 crate::lang::Lang::Java | crate::lang::Lang::Kotlin => {
1669 files.extend(crate::codegen_java::wrappers(m, api));
1670 files.extend(
1671 crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1672 );
1673 files.push((
1674 format!(
1675 "java/rustanything/{}.java",
1676 crate::codegen_ffi::java_native_class(m)
1677 ),
1678 crate::codegen_java::native_class(m, api),
1679 ));
1680 files.push((
1681 "java/rustanything/RustAnythingJson.java".into(),
1682 crate::codegen_java::JSON_JAVA.into(),
1683 ));
1684 files.push((
1685 "java/rustanything/RustAnythingWire.java".into(),
1686 crate::codegen_java::WIRE_JAVA.into(),
1687 ));
1688 files.push((
1689 "java/rustanything/RustAnythingError.java".into(),
1690 crate::codegen_java::ERROR_JAVA.into(),
1691 ));
1692 }
1693 other => bail!("no wrapper generator for {}", other.name()),
1694 }
1695 Ok(files)
1696}
1697
1698fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1699 let port = codegen::port_rs(manifest);
1700 let api = codegen::parse_port(&port);
1701 let mut files = vec![
1702 (
1703 "Cargo.toml".to_string(),
1704 with_rayon(
1705 manifest,
1706 if manifest.language == crate::lang::Lang::Ruby {
1707 crate::codegen_ruby::cargo_toml(manifest)
1708 } else {
1709 crate::codegen_ffi::cargo_toml(manifest)
1710 },
1711 )?,
1712 ),
1713 ("src/port.rs".into(), port),
1714 (
1715 ".gitignore".into(),
1716 "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(),
1717 ),
1718 ("README.md".into(), readme(manifest)),
1719 (
1720 MANIFEST.into(),
1721 serde_json::to_string_pretty(manifest)? + "\n",
1722 ),
1723 ];
1724 files.extend(ffi_bindings(manifest, &api)?);
1725 write_files(crate_dir, &files)?;
1726 format_rust(crate_dir);
1727 format_wrapper(crate_dir);
1728 let mut notes = vec![format!(
1729 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1730 crate_dir.display()
1731 )];
1732 for j in kept {
1733 notes.push(format!(
1734 "`{}` stays in {}: {}.",
1735 j.name,
1736 manifest.language.name(),
1737 j.reason
1738 ));
1739 }
1740 Ok(Outcome {
1741 crate_dir: crate_dir.to_path_buf(),
1742 kind: Kind::Ffi,
1743 files: files.into_iter().map(|(p, _)| p).collect(),
1744 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1745 notes,
1746 })
1747}
1748
1749fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1750 let mut files = vec![
1751 (
1752 "Cargo.toml".to_string(),
1753 crate::codegen_c::cargo_toml(manifest),
1754 ),
1755 ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1756 (
1757 ".gitignore".into(),
1758 "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\nphp/*.so\nphp/*.dylib\nphp/*.dll\n".into(),
1759 ),
1760 ("README.md".into(), readme(manifest)),
1761 (
1762 MANIFEST.into(),
1763 serde_json::to_string_pretty(manifest)? + "\n",
1764 ),
1765 ];
1766 let port = crate::codegen_c::port_rs(manifest);
1767 files.extend(c_bindings(manifest, &port));
1768 write_files(crate_dir, &files)?;
1769 format_rust(crate_dir);
1770 let mut notes = vec![
1771 format!(
1772 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1773 crate_dir.display()
1774 ),
1775 format!(
1776 "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1777 manifest.lib_name(),
1778 manifest.lib_name()
1779 ),
1780 ];
1781 for j in kept {
1782 notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1783 }
1784 Ok(Outcome {
1785 crate_dir: crate_dir.to_path_buf(),
1786 kind: Kind::CAbi,
1787 files: files.into_iter().map(|(p, _)| p).collect(),
1788 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1789 notes,
1790 })
1791}
1792
1793fn readme(m: &Manifest) -> String {
1794 use crate::lang::Lang;
1795 let functions: String = m
1796 .exports
1797 .iter()
1798 .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1799 .collect();
1800 let original = match m.language {
1801 Lang::Ts => "TS",
1802 other => other.name(),
1803 };
1804 let module = match m.kind {
1805 Kind::Napi => "napi-rs module",
1806 Kind::Wasm => "wasm-bindgen module",
1807 Kind::Pyo3 => "PyO3 module",
1808 Kind::CAbi => "C library",
1809 Kind::Ffi => "shared library",
1810 };
1811 let shadow = match m.language {
1812 Lang::Php | Lang::Csharp | Lang::Powershell => String::new(),
1813 _ => "rust-anything shadow . # run both in the app, log mismatches\n".into(),
1814 };
1815 let switch = match m.language {
1816 Lang::Php => format!(
1817 "\nPHP has no shadow module: once `diff` passes, require `{}` in place of the original files.\n",
1818 crate::codegen_php::wrapper_path(m)
1819 ),
1820 Lang::Powershell => format!(
1821 "\nPowerShell has no shadow module: once `diff` passes, `rust-anything enable .` \
1822 dot-sources `{}` at the end of the original file, so every caller (the module's own \
1823 functions too) gets Rust. Most slow PowerShell is the start-up of a new `pwsh` per \
1824 command, which no port fixes: keep one shell open and call into it.\n",
1825 crate::codegen_powershell::wrapper_path(m)
1826 ),
1827 Lang::Csharp => format!(
1828 "\nC# has no shadow module: once `diff` passes, compile `{}` into the project and call \
1829 the `<namespace>.Rust` classes, with the built library next to the app.\n",
1830 crate::codegen_csharp::wrapper_path(m)
1831 ),
1832 _ => String::new(),
1833 };
1834 format!(
1835 "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1836 ## Loop\n\n```sh\nrust-anything record . # record what the {original} code does\nrust-anything build . # build the {module}\n\
1837 rust-anything diff . # run the recorded cases against Rust\n{shadow}\
1838 rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n```\n{switch}",
1839 name = m.crate_name,
1840 unit = m.unit,
1841 kind = m.kind.label(),
1842 )
1843}
1844
1845const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1846//!
1847//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1848//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1849
1850#![forbid(unsafe_code)]
1851
1852/// The UTF-16 code units of `s`, as JS sees the string.
1853pub fn units(s: &str) -> Vec<u16> {
1854 s.encode_utf16().collect()
1855}
1856
1857/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1858pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1859 let end = end.min(units.len());
1860 let start = start.min(end);
1861 String::from_utf16_lossy(&units[start..end])
1862}
1863
1864/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1865pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1866 let from = from.min(haystack.len());
1867 if needle.is_empty() {
1868 return Some(from);
1869 }
1870 haystack[from..]
1871 .windows(needle.len())
1872 .position(|w| w == needle)
1873 .map(|i| i + from)
1874}
1875
1876/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1877pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1878 if needle.is_empty() {
1879 return Some(haystack.len());
1880 }
1881 haystack.windows(needle.len()).rposition(|w| w == needle)
1882}
1883
1884/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1885pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1886 let mut seen = 0;
1887 for (byte, c) in s.char_indices() {
1888 if seen >= utf16_offset {
1889 return byte;
1890 }
1891 seen += c.len_utf16();
1892 }
1893 s.len()
1894}
1895
1896/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1897pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1898 s[..byte_offset.min(s.len())].encode_utf16().count()
1899}
1900
1901#[cfg(test)]
1902mod tests {
1903 use super::*;
1904
1905 #[test]
1906 fn matches_js_indexing() {
1907 let s = units("a👍b");
1908 assert_eq!(s.len(), 4);
1909 assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1910 assert_eq!(last_index_of(&s, &units("a")), Some(0));
1911 assert_eq!(slice(&s, 3, 4), "b");
1912 assert_eq!(byte_offset("a👍b", 3), 5);
1913 assert_eq!(utf16_offset("a👍b", 5), 3);
1914 }
1915}
1916"#;
1917
1918#[cfg(test)]
1919mod tests {
1920 use super::*;
1921
1922 #[test]
1923 fn kind_labels_match_documentation() {
1924 assert_eq!(Kind::Napi.label(), "napi-rs");
1925 assert_eq!(Kind::Wasm.label(), "wasm-bindgen");
1926 assert_eq!(Kind::Pyo3.label(), "PyO3");
1927 assert_eq!(Kind::CAbi.label(), "the C ABI");
1928 assert_eq!(Kind::Ffi.label(), "a JSON dispatcher");
1929 }
1930
1931 #[test]
1932 fn keep_entries_are_trimmed() {
1933 let keep = |k: &[&str]| k.iter().map(|s| s.to_string()).collect::<Vec<_>>();
1934 assert_eq!(
1935 keep_reason(&keep(&["add"]), "add").as_deref(),
1936 Some("kept on request")
1937 );
1938 assert_eq!(
1939 keep_reason(&keep(&[" add "]), "add").as_deref(),
1940 Some("kept on request")
1941 );
1942 assert_eq!(
1943 keep_reason(&keep(&[" add : slow in Rust "]), "add").as_deref(),
1944 Some("slow in Rust")
1945 );
1946 assert_eq!(
1947 keep_reason(&keep(&["add:"]), "add").as_deref(),
1948 Some("kept on request")
1949 );
1950 assert_eq!(keep_reason(&keep(&["add"]), "sub"), None);
1951 }
1952
1953 #[test]
1954 fn unknown_keep_names_are_refused() {
1955 let keep = |k: &str| vec![k.to_string()];
1956 assert!(check_keep(&keep(" add : reason"), &["add", "Point"], "src/add.ts").is_ok());
1957 assert!(check_keep(&keep("Point"), &["add", "Point"], "src/add.ts").is_ok());
1958 let err = check_keep(&keep("nope"), &["sub", "add"], "src/add.ts")
1959 .unwrap_err()
1960 .to_string();
1961 assert_eq!(
1962 err,
1963 "--keep `nope` is not an export of `src/add.ts` (exports: add, sub)"
1964 );
1965 }
1966
1967 #[test]
1968 fn bridge_refuses_unknown_keep_name() {
1969 let dir = crate::app::temp_dir("bridge-keep").unwrap();
1970 std::fs::write(
1971 dir.join("package.json"),
1972 r#"{"name":"demo","version":"1.0.0"}"#,
1973 )
1974 .unwrap();
1975 std::fs::create_dir_all(dir.join("src")).unwrap();
1976 std::fs::write(
1977 dir.join("src/add.ts"),
1978 "export function add(a: number, b: number): number { return a + b; }\n",
1979 )
1980 .unwrap();
1981 let out = dir.join("rust/add-rs");
1982 let err = bridge(&Options {
1983 root: &dir,
1984 unit: "src/add.ts",
1985 kind: Some(Kind::Napi),
1986 out: Some(out.clone()),
1987 name: None,
1988 force: false,
1989 lang: None,
1990 keep: vec!["nope".into()],
1991 batch: vec![],
1992 allocator: Allocator::default(),
1993 as_json: vec![],
1994 })
1995 .unwrap_err();
1996 assert!(
1997 format!("{err:#}")
1998 .contains("--keep `nope` is not an export of `src/add.ts` (exports: add)"),
1999 "{err:#}"
2000 );
2001 assert!(!out.exists());
2002 std::fs::remove_dir_all(dir).unwrap();
2003 }
2004
2005 #[test]
2006 fn bridge_refuses_an_as_json_name_that_is_not_a_type_parameter() {
2007 let dir = crate::app::temp_dir("bridge-as-json").unwrap();
2008 std::fs::write(
2009 dir.join("package.json"),
2010 r#"{"name":"demo","version":"1.0.0"}"#,
2011 )
2012 .unwrap();
2013 std::fs::create_dir_all(dir.join("src")).unwrap();
2014 std::fs::write(
2015 dir.join("src/math.ts"),
2016 "export function add(a: number, b: number): number { return a + b; }\n\
2017 export function first<T>(items: T[]): T { return items[0]; }\n",
2018 )
2019 .unwrap();
2020 let out = dir.join("rust/math-rs");
2021 let err = bridge(&Options {
2022 root: &dir,
2023 unit: "src/math.ts",
2024 kind: Some(Kind::Napi),
2025 out: Some(out.clone()),
2026 name: None,
2027 force: false,
2028 lang: None,
2029 keep: vec![],
2030 batch: vec![],
2031 allocator: Allocator::default(),
2032 as_json: vec!["Q".into()],
2033 })
2034 .unwrap_err();
2035 assert!(
2036 format!("{err:#}").contains(
2037 "--as-json `Q` is not a type parameter of `src/math.ts` (type parameters: T)"
2038 ),
2039 "{err:#}"
2040 );
2041 assert!(!out.exists());
2042 std::fs::remove_dir_all(dir).unwrap();
2043 }
2044
2045 #[test]
2046 fn bridge_accepts_as_json_for_a_type_parameter_its_constraint_resolved() {
2047 let dir = crate::app::temp_dir("bridge-as-json-constrained").unwrap();
2050 std::fs::write(
2051 dir.join("package.json"),
2052 r#"{"name":"demo","version":"1.0.0"}"#,
2053 )
2054 .unwrap();
2055 std::fs::create_dir_all(dir.join("src")).unwrap();
2056 std::fs::write(
2057 dir.join("src/id.ts"),
2058 "export function identity<T extends string>(x: T): T { return x; }\n",
2059 )
2060 .unwrap();
2061 let outcome = bridge(&Options {
2062 root: &dir,
2063 unit: "src/id.ts",
2064 kind: Some(Kind::Napi),
2065 out: Some(dir.join("rust/id-rs")),
2066 name: None,
2067 force: false,
2068 lang: None,
2069 keep: vec![],
2070 batch: vec![],
2071 allocator: Allocator::default(),
2072 as_json: vec!["T".into()],
2073 })
2074 .unwrap();
2075 assert!(
2076 outcome.exports.iter().any(|e| e == "identity"),
2077 "{:?}",
2078 outcome.exports
2079 );
2080 std::fs::remove_dir_all(dir).unwrap();
2081 }
2082
2083 #[test]
2084 fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
2085 let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
2086 let _ = std::fs::remove_dir_all(&base);
2087 let crate_dir = base.join("repo/rust/x-rs");
2088 std::fs::create_dir_all(&crate_dir).unwrap();
2089 std::fs::write(
2090 crate_dir.join(MANIFEST),
2091 r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
2092 )
2093 .unwrap();
2094 let m = Manifest::load(&crate_dir).unwrap();
2095 assert_eq!(m.root, base.join("repo").canonical().unwrap());
2096 assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
2097 let mut back = m.clone();
2099 if let Some(w) = back.root_written.clone() {
2100 back.root = w;
2101 }
2102 assert!(
2103 serde_json::to_string(&back)
2104 .unwrap()
2105 .contains(r#""root":"../..""#)
2106 );
2107 std::fs::remove_dir_all(&base).unwrap();
2108 }
2109
2110 #[test]
2111 fn maps_ts_types() {
2112 assert_eq!(RType::from_ts("string").rust(), "String");
2113 assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
2114 assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
2115 assert_eq!(
2116 RType::from_ts("string | undefined").rust(),
2117 "Option<String>"
2118 );
2119 assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
2120 assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
2121 assert_eq!(
2122 RType::from_ts("Map<string, number>").rust(),
2123 "serde_json::Value"
2124 );
2125 assert_eq!(
2126 RType::from_ts("string | number").rust(),
2127 "serde_json::Value"
2128 );
2129 assert_eq!(
2130 RType::from_ts("Record<string, string | number>").rust(),
2131 "serde_json::Value"
2132 );
2133 assert_eq!(
2134 RType::from_ts("(string | undefined)").rust(),
2135 "Option<String>"
2136 );
2137 assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
2138 }
2139
2140 #[test]
2141 fn keeps_unbridgeable_exports_in_js() {
2142 let source = "export interface LineIndex {\n readonly lineCount: number\n position(offset: number): number\n}\n\
2143 export interface Range { start: number, end: number }\n\
2144 export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
2145 export function globToRegExp(glob: string): RegExp { return /x/ }\n\
2146 export function createLineIndex(text: string): LineIndex { return null! }\n\
2147 export function* walk(tree: object) {}\n\
2148 export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
2149 export function contains(range: Range, offset: number): boolean { return true }\n";
2150 let types = local_types("a.ts", source);
2151 let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
2152 .iter()
2153 .map(|f| (f.name.clone(), js_only_reason(f, &types)))
2154 .collect();
2155 let js_only: Vec<&str> = reasons
2156 .iter()
2157 .filter(|(_, r)| r.is_some())
2158 .map(|(n, _)| n.as_str())
2159 .collect();
2160 assert_eq!(
2161 js_only,
2162 [
2163 "keyMatcher",
2164 "globToRegExp",
2165 "createLineIndex",
2166 "walk",
2167 "sortTree"
2168 ]
2169 );
2170 }
2171
2172 #[test]
2173 fn resolves_simple_aliases() {
2174 let types = local_types(
2175 "m.ts",
2176 "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
2177 );
2178 assert_eq!(
2179 resolve_aliases("readonly KeyString[]", &types),
2180 "readonly string[]"
2181 );
2182 assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
2183 assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
2184 }
2185
2186 #[test]
2187 fn substitutes_simple_constraints() {
2188 let found = exported_functions(
2189 "a.ts",
2190 "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
2191 export function pick<T>(x: T): T { return x }\n\
2192 export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
2193 );
2194 let mut fns = found;
2195 for f in &mut fns {
2196 substitute_constraints(f, &[]);
2197 }
2198 assert_eq!(fns[0].params[0].ts_type, "(string)");
2199 assert!(fns[0].type_params.is_empty());
2200 assert_eq!(fns[1].type_params, ["T"]);
2201 assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
2202 assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
2203 }
2204
2205 #[test]
2206 fn unknown_as_json_names_are_refused() {
2207 let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>();
2208 assert!(check_as_json(&names(&["T"]), &names(&["U", "T"]), "src/a.ts").is_ok());
2209 let err = check_as_json(&names(&["Q"]), &names(&["U", "T", "T"]), "src/a.ts")
2210 .unwrap_err()
2211 .to_string();
2212 assert_eq!(
2213 err,
2214 "--as-json `Q` is not a type parameter of `src/a.ts` (type parameters: T, U)"
2215 );
2216 let err = check_as_json(&names(&["T"]), &[], "src/a.ts")
2217 .unwrap_err()
2218 .to_string();
2219 assert_eq!(
2220 err,
2221 "--as-json `T` is not a type parameter of `src/a.ts` (it has none)"
2222 );
2223 }
2224
2225 #[test]
2226 fn as_json_bridges_a_data_generic() {
2227 let mut fns = exported_functions(
2228 "a.ts",
2229 "export function paginate<T>(items: T[], page: number): { data: T[] } { return { data: items } }\n",
2230 );
2231 assert!(js_only_reason(&fns[0], &[]).is_some());
2232 substitute_json(&mut fns[0], &["T".to_string()]);
2233 assert!(fns[0].type_params.is_empty());
2234 assert_eq!(fns[0].params[0].ts_type, "unknown[]");
2235 assert_eq!(fns[0].returns, "{ data: unknown[] }");
2236 assert!(js_only_reason(&fns[0], &[]).is_none());
2237 }
2238
2239 #[test]
2240 fn readme_fits_the_language() {
2241 let manifest = |language: &str, kind: &str| -> Manifest {
2242 serde_json::from_str(&format!(
2243 r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "src/X.cs", "language": "{language}", "kind": "{kind}", "crate_name": "x-rs", "exports": []}}"#
2244 ))
2245 .unwrap()
2246 };
2247 let ts = readme(&manifest("ts", "napi"));
2248 assert!(ts.contains("what the TS code does") && ts.contains("build the napi-rs module"));
2249 assert!(ts.contains("rust-anything shadow ."));
2250 let c = readme(&manifest("c", "c-abi"));
2251 assert!(c.contains("what the C code does") && c.contains("build the C library"));
2252 let cs = readme(&manifest("csharp", "ffi"));
2253 assert!(cs.contains("what the C# code does") && cs.contains("build the shared library"));
2254 assert!(!cs.contains("rust-anything shadow") && cs.contains("C# has no shadow module"));
2255 let php = readme(&manifest("php", "ffi"));
2256 assert!(!php.contains("rust-anything shadow") && php.contains("PHP has no shadow module"));
2257 }
2258
2259 #[test]
2260 fn makes_rust_names() {
2261 assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
2262 assert_eq!(snake_case("type"), "r#type");
2263 assert_eq!(snake_case("toURL"), "to_url");
2264 assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
2265 assert_eq!(snake_case("box"), "r#box");
2266 assert_eq!(snake_case("yield"), "r#yield");
2267 assert_eq!(snake_case("try"), "r#try");
2268 assert_eq!(snake_case("self"), "self_");
2269 assert_eq!(snake_case("Super"), "super_");
2270 }
2271
2272 #[test]
2273 fn validates_crate_names() {
2274 for good in ["add-rs", "my_crate", "_helper", "Foo2", "a-1_b"] {
2275 assert_eq!(validate_crate_name(good).unwrap(), good, "{good}");
2276 }
2277 for bad in [
2278 "",
2279 " ",
2280 " add-rs ",
2281 "foo bar",
2282 "123-rs",
2283 "-foo",
2284 "../escape",
2285 "a/b",
2286 "a\\b",
2287 "a\"b",
2288 "café",
2289 "_",
2290 "fn",
2291 "type",
2292 "self",
2293 "Self",
2294 "gen",
2295 "con",
2296 "NUL",
2297 ] {
2298 assert!(
2299 validate_crate_name(bad).is_err(),
2300 "expected error for {bad:?}"
2301 );
2302 }
2303 }
2304
2305 #[test]
2306 fn default_crate_name_is_always_valid_for_cargo() {
2307 assert_eq!(default_crate_name("add"), "add-rs");
2308 assert_eq!(default_crate_name("my_util"), "my-util-rs");
2309 assert_eq!(default_crate_name("123"), "unit-123-rs");
2310 assert_eq!(default_crate_name("---"), "unit-rs");
2311 assert_eq!(default_crate_name(""), "unit-rs");
2312 for stem in ["add", "my_util", "123", "---", "", "00-index", "café"] {
2313 let name = default_crate_name(stem);
2314 assert!(
2315 validate_crate_name(&name).is_ok(),
2316 "{stem:?} -> {name:?} should be a valid crate name"
2317 );
2318 }
2319 }
2320
2321 #[test]
2322 fn bridge_refuses_invalid_name_before_writing_anything() {
2323 let out = std::env::temp_dir().join(format!("ra-bridge-bad-name-{}", std::process::id()));
2324 let _ = std::fs::remove_dir_all(&out);
2325 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
2326 for bad in ["../escape", "123bad", "", "fn"] {
2327 let err = bridge(&Options {
2328 root: &root,
2329 unit: "packages/a/src/util.ts",
2330 kind: Some(Kind::Napi),
2331 out: Some(out.clone()),
2332 name: Some(bad.to_string()),
2333 force: false,
2334 keep: Vec::new(),
2335 lang: None,
2336 batch: Vec::new(),
2337 as_json: Vec::new(),
2338 allocator: Allocator::default(),
2339 })
2340 .unwrap_err();
2341 assert!(
2342 format!("{err:#}").contains("invalid crate name"),
2343 "{bad:?}: {err:#}"
2344 );
2345 assert!(
2346 !out.exists(),
2347 "refused --name {bad:?} must not create folder"
2348 );
2349 }
2350 }
2351}