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