1use crate::walk::Canonical;
9use std::path::{Path, PathBuf};
10
11use anyhow::{Context, Result, bail};
12use serde::{Deserialize, Serialize};
13
14use crate::analyze::{self, Bridge, Status};
15use crate::codegen;
16use crate::risks::Risk;
17use crate::ts::exports::{
18 ExportedClass, ExportedFn, LocalType, exported_classes, exported_functions, local_types,
19};
20
21pub const MANIFEST: &str = "rust-anything.json";
22pub const SCHEMA: &str = "rust-anything/bridge@1";
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum Kind {
27 Napi,
28 Wasm,
29 Pyo3,
30 #[serde(rename = "c-abi")]
32 CAbi,
33 Ffi,
35}
36
37#[derive(Clone, Debug, Serialize, Deserialize)]
39pub struct Manifest {
40 pub schema: String,
41 pub root: PathBuf,
44 #[serde(skip)]
47 pub root_written: Option<PathBuf>,
48 pub unit: String,
49 #[serde(default)]
50 pub language: crate::lang::Lang,
51 pub kind: Kind,
52 pub crate_name: String,
53 pub exports: Vec<ExportedFn>,
55 #[serde(default)]
57 pub classes: Vec<ExportedClass>,
58 #[serde(default)]
61 pub js_only: Vec<JsOnly>,
62 #[serde(default, skip_serializing_if = "Vec::is_empty")]
64 pub batches: Vec<crate::codegen_batch::Batch>,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub float_tolerance: Option<f64>,
68}
69
70#[derive(Clone, Debug, Serialize, Deserialize)]
71pub struct JsOnly {
72 pub name: String,
73 pub file: String,
74 pub line: u32,
75 pub reason: String,
76}
77
78fn has_functions(name: &str, local_types: &[LocalType], seen: &mut Vec<String>) -> bool {
81 if seen.iter().any(|s| s == name) {
82 return false;
83 }
84 seen.push(name.to_string());
85 let Some(t) = local_types.iter().find(|t| t.name == name) else {
86 return false;
87 };
88 let text = &t.text;
89 let method = text.lines().skip(1).any(|l| {
90 let l = l.trim().trim_start_matches("readonly ");
91 l.contains('(')
92 && l.split('(').next().is_some_and(|head| {
93 !head.is_empty()
94 && head
95 .chars()
96 .all(|c| c.is_alphanumeric() || c == '_' || c == '?')
97 })
98 });
99 if text.contains("=>") || method {
100 return true;
101 }
102 text.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
103 .filter(|w| !w.is_empty() && *w != name)
104 .any(|w| has_functions(w, local_types, seen))
105}
106
107pub fn js_only_reason(f: &ExportedFn, local_types: &[LocalType]) -> Option<String> {
112 if let Some(blocker) = &f.blocker {
113 return Some(blocker.clone());
114 }
115 if f.is_generator {
116 return Some("generator: returns a lazy iterator".into());
117 }
118 if f.uses_instanceof {
119 return Some("checks `instanceof`: class identity does not survive the bridge".into());
120 }
121 let types: Vec<&str> = f
122 .params
123 .iter()
124 .map(|p| p.ts_type.as_str())
125 .chain(std::iter::once(f.returns.as_str()))
126 .collect();
127 if types.iter().any(|t| t.contains("=>")) {
128 return Some("takes or returns a function".into());
129 }
130 let words = |t: &str| -> Vec<String> {
131 t.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
132 .filter(|w| !w.is_empty())
133 .map(str::to_string)
134 .collect()
135 };
136 for t in &types {
137 for word in words(t) {
138 match word.as_str() {
139 "RegExp" => return Some("takes or returns a RegExp".into()),
140 "Generator" | "Iterator" | "IterableIterator" | "AsyncGenerator"
141 | "AsyncIterable" => {
142 return Some(format!("uses `{word}`, a lazy iterator"));
143 }
144 "Function" => return Some("takes or returns a function".into()),
145 _ => {}
146 }
147 if f.type_params.contains(&word) {
148 return Some(format!(
149 "generic over `{word}`: values of any shape, functions included"
150 ));
151 }
152 if has_functions(&word, local_types, &mut Vec::new()) {
153 return Some(format!("uses `{word}`, which has function members"));
154 }
155 }
156 }
157 None
158}
159
160impl Manifest {
161 pub fn load(crate_dir: &Path) -> Result<Self> {
162 let path = crate_dir.join(MANIFEST);
163 let text = std::fs::read_to_string(&path).with_context(|| {
164 format!(
165 "reading {} (run `rust-anything bridge` first)",
166 path.display()
167 )
168 })?;
169 let mut manifest: Self =
170 serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
171 if manifest.root.is_relative() {
172 let resolved = crate_dir.join(&manifest.root);
173 let resolved = resolved.canonical().unwrap_or(resolved);
174 manifest.root_written = Some(std::mem::replace(&mut manifest.root, resolved));
175 }
176 Ok(manifest)
177 }
178
179 pub fn save(&self, crate_dir: &Path) -> Result<()> {
181 let mut m = self.clone();
182 if let Some(written) = m.root_written.take() {
183 m.root = written;
184 }
185 let path = crate_dir.join(MANIFEST);
186 std::fs::write(&path, serde_json::to_string_pretty(&m)? + "\n")
187 .with_context(|| format!("writing {}", path.display()))
188 }
189
190 pub fn lib_name(&self) -> String {
192 self.crate_name.replace('-', "_")
193 }
194}
195
196pub struct Options<'a> {
197 pub root: &'a Path,
198 pub unit: &'a str,
199 pub kind: Option<Kind>,
200 pub out: Option<PathBuf>,
201 pub name: Option<String>,
202 pub force: bool,
204 pub keep: Vec<String>,
206 pub lang: Option<crate::lang::Lang>,
208 pub batch: Vec<String>,
210}
211
212#[derive(Debug, Serialize)]
213pub struct Outcome {
214 pub crate_dir: PathBuf,
215 pub kind: Kind,
216 pub files: Vec<String>,
217 pub exports: Vec<String>,
218 pub notes: Vec<String>,
219}
220
221#[derive(Clone, Debug, PartialEq, Eq)]
223pub enum RType {
224 Str,
225 F64,
226 Int,
228 Bool,
229 Unit,
230 Vec(Box<RType>),
231 Opt(Box<RType>),
232 Json,
234}
235
236impl RType {
237 pub fn from_ts(ts: &str) -> Self {
238 let ts = ts.trim().trim_start_matches("readonly ").trim();
239 if let Some(inner) = ts.strip_prefix('(').and_then(|t| t.strip_suffix(')'))
241 && balanced(inner)
242 {
243 return Self::from_ts(inner);
244 }
245 if let Some(inner) = ts
246 .strip_prefix("Promise<")
247 .and_then(|t| t.strip_suffix('>'))
248 {
249 return Self::from_ts(inner);
250 }
251 let parts = split_top(ts, '|');
252 if parts.len() > 1 {
253 let (nullish, rest): (Vec<&str>, Vec<&str>) = parts
254 .iter()
255 .partition(|p| matches!(p.trim(), "undefined" | "null" | "void"));
256 if rest.iter().all(|p| is_string_literal(p)) {
257 return Self::wrap_opt(Self::Str, !nullish.is_empty());
258 }
259 if rest.len() == 1 {
260 return Self::wrap_opt(Self::from_ts(rest[0]), !nullish.is_empty());
261 }
262 return Self::Json;
263 }
264 if let Some(inner) = ts.strip_suffix("[]") {
265 return Self::Vec(Box::new(Self::from_ts(
266 inner.trim_start_matches('(').trim_end_matches(')'),
267 )));
268 }
269 for wrapper in ["Array<", "ReadonlyArray<"] {
270 if let Some(inner) = ts.strip_prefix(wrapper).and_then(|t| t.strip_suffix('>')) {
271 return Self::Vec(Box::new(Self::from_ts(inner)));
272 }
273 }
274 if ts.starts_with("asserts ") {
276 return Self::Unit;
277 }
278 if let Some((subject, _)) = ts.split_once(" is ")
279 && subject
280 .trim()
281 .chars()
282 .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
283 {
284 return Self::Bool;
285 }
286 match ts {
287 "string" => Self::Str,
288 "number" => Self::F64,
289 "int" => Self::Int,
290 "boolean" => Self::Bool,
291 "void" | "undefined" => Self::Unit,
292 _ if is_string_literal(ts) => Self::Str,
293 _ => Self::Json,
294 }
295 }
296
297 fn wrap_opt(t: Self, optional: bool) -> Self {
298 if optional { Self::Opt(Box::new(t)) } else { t }
299 }
300
301 pub fn rust(&self) -> String {
302 match self {
303 Self::Str => "String".into(),
304 Self::F64 => "f64".into(),
305 Self::Int => "i64".into(),
306 Self::Bool => "bool".into(),
307 Self::Unit => "()".into(),
308 Self::Vec(t) => format!("Vec<{}>", t.rust()),
309 Self::Opt(t) => format!("Option<{}>", t.rust()),
310 Self::Json => "serde_json::Value".into(),
311 }
312 }
313
314 pub fn contains_json(&self) -> bool {
315 match self {
316 Self::Json => true,
317 Self::Vec(t) | Self::Opt(t) => t.contains_json(),
318 _ => false,
319 }
320 }
321}
322
323fn is_string_literal(ts: &str) -> bool {
324 let ts = ts.trim();
325 ts.len() >= 2
326 && ((ts.starts_with('\'') && ts.ends_with('\''))
327 || (ts.starts_with('"') && ts.ends_with('"')))
328}
329
330fn balanced(ts: &str) -> bool {
331 let mut depth = 0i32;
332 for c in ts.chars() {
333 match c {
334 '(' => depth += 1,
335 ')' => {
336 depth -= 1;
337 if depth < 0 {
338 return false;
339 }
340 }
341 _ => {}
342 }
343 }
344 depth == 0
345}
346
347fn split_top(ts: &str, sep: char) -> Vec<&str> {
349 let mut out = Vec::new();
350 let mut depth = 0i32;
351 let mut start = 0;
352 for (i, c) in ts.char_indices() {
353 match c {
354 '<' | '(' | '[' | '{' => depth += 1,
355 '>' | ')' | ']' | '}' => depth -= 1,
356 c if c == sep && depth == 0 => {
357 out.push(ts[start..i].trim());
358 start = i + c.len_utf8();
359 }
360 _ => {}
361 }
362 }
363 out.push(ts[start..].trim());
364 out.retain(|p| !p.is_empty());
365 out
366}
367
368pub fn param_type(p: &crate::ts::exports::Param) -> RType {
370 let base = RType::from_ts(&p.ts_type);
371 let base = if p.rest {
372 match base {
373 RType::Vec(_) => base,
374 other => RType::Vec(Box::new(other)),
375 }
376 } else {
377 base
378 };
379 if p.optional && !matches!(base, RType::Opt(_)) {
380 RType::Opt(Box::new(base))
381 } else {
382 base
383 }
384}
385
386pub fn snake_case(name: &str) -> String {
387 let chars: Vec<char> = name.chars().collect();
388 let mut out = String::new();
389 for (i, &c) in chars.iter().enumerate() {
390 if c.is_uppercase() {
391 let prev = i.checked_sub(1).map(|j| chars[j]);
392 let next = chars.get(i + 1);
393 let boundary = prev.is_some_and(|p| p.is_lowercase() || p.is_ascii_digit())
394 || (prev.is_some_and(char::is_uppercase) && next.is_some_and(|n| n.is_lowercase()));
395 if boundary {
396 out.push('_');
397 }
398 out.extend(c.to_lowercase());
399 } else if c.is_alphanumeric() {
400 out.push(c);
401 } else {
402 out.push('_');
403 }
404 }
405 const KEYWORDS: &[&str] = &[
406 "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
407 "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
408 "return", "self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use",
409 "where", "while", "async", "await", "dyn", "gen",
410 ];
411 if KEYWORDS.contains(&out.as_str()) {
412 format!("r#{out}")
413 } else {
414 out
415 }
416}
417
418pub fn types_in_scope(root: &Path, file: &str, text: &str) -> Vec<LocalType> {
420 let mut types = Vec::new();
421 let mut seen = std::collections::HashSet::new();
422 collect_types(root, file, text, 0, &mut seen, &mut types);
423 types
424}
425
426fn collect_types(
429 root: &Path,
430 file: &str,
431 text: &str,
432 depth: usize,
433 seen: &mut std::collections::HashSet<String>,
434 types: &mut Vec<LocalType>,
435) {
436 if depth > 4 || !seen.insert(file.to_string()) {
437 return;
438 }
439 types.extend(local_types(file, text));
440 let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
441 for import in crate::ts::scan::scan(file, text).imports {
442 let spec = import.specifier;
443 let base = if spec.starts_with('.') {
445 let joined = if dir.is_empty() {
446 spec.clone()
447 } else {
448 format!("{dir}/{spec}")
449 };
450 match normalize_rel(&joined) {
451 Some(base) => base,
452 None => continue,
453 }
454 } else {
455 let name = crate::ts::deps::package_name(&spec);
456 let Some(pkg_dir) = workspace_packages(root).get(name).cloned() else {
457 continue;
458 };
459 let sub = spec[name.len()..].trim_start_matches('/');
460 let src = if root.join(&pkg_dir).join("src").is_dir() {
461 format!("{pkg_dir}/src")
462 } else {
463 pkg_dir
464 };
465 let src = src.trim_start_matches('/').to_string();
466 if sub.is_empty() {
467 format!("{src}/index")
468 } else {
469 format!("{src}/{sub}")
470 }
471 };
472 let stem = base.trim_end_matches(".js");
473 let candidates = [
474 format!("{stem}.ts"),
475 format!("{stem}.mts"),
476 format!("{stem}.d.ts"),
477 format!("{stem}/index.ts"),
478 base.clone(),
479 ];
480 if let Some(found) = candidates.iter().find(|c| root.join(c).is_file())
481 && let Ok(imported) = std::fs::read_to_string(root.join(found))
482 {
483 collect_types(root, found, &imported, depth + 1, seen, types);
484 }
485 }
486}
487
488fn workspace_packages(root: &Path) -> std::collections::HashMap<String, String> {
490 use std::sync::{Mutex, OnceLock};
491 static CACHE: OnceLock<
492 Mutex<std::collections::HashMap<PathBuf, std::collections::HashMap<String, String>>>,
493 > = OnceLock::new();
494 let cache = CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
495 let mut cache = cache
496 .lock()
497 .unwrap_or_else(std::sync::PoisonError::into_inner);
498 cache
499 .entry(root.to_path_buf())
500 .or_insert_with(|| {
501 crate::ts::discover::discover(root)
502 .map(|ws| ws.packages.into_iter().map(|p| (p.name, p.dir)).collect())
503 .unwrap_or_default()
504 })
505 .clone()
506}
507
508fn normalize_rel(path: &str) -> Option<String> {
510 let mut parts: Vec<&str> = Vec::new();
511 for part in path.split('/') {
512 match part {
513 "" | "." => {}
514 ".." => {
515 parts.pop()?;
516 }
517 _ => parts.push(part),
518 }
519 }
520 Some(parts.join("/"))
521}
522
523pub fn substitute_constraints(f: &mut ExportedFn, types: &[LocalType]) {
526 let mut remaining = Vec::new();
527 for tp in std::mem::take(&mut f.type_params) {
528 let Some((name, constraint)) = tp.split_once(" extends ") else {
529 remaining.push(tp);
530 continue;
531 };
532 let constraint = resolve_aliases(constraint, types);
533 let open_ended = constraint.contains("=>")
536 || constraint
537 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
538 .any(|w| {
539 matches!(w, "Function" | "object" | "unknown" | "any")
540 || has_functions(w, types, &mut Vec::new())
541 });
542 if open_ended {
543 remaining.push(name.to_string());
544 continue;
545 }
546 let replacement = format!("({constraint})");
547 for p in &mut f.params {
548 p.ts_type = replace_word(&p.ts_type, name, &replacement);
549 }
550 f.returns = replace_word(&f.returns, name, &replacement);
551 }
552 f.type_params = remaining;
553}
554
555fn replace_word(text: &str, word: &str, with: &str) -> String {
556 let mut out = String::new();
557 let mut current = String::new();
558 for c in text.chars().chain(std::iter::once(' ')) {
559 if c.is_alphanumeric() || c == '_' || c == '$' {
560 current.push(c);
561 } else {
562 out.push_str(if current == word { with } else { ¤t });
563 current.clear();
564 out.push(c);
565 }
566 }
567 out.pop();
568 out
569}
570
571pub fn resolve_aliases(ts: &str, types: &[LocalType]) -> String {
573 let mut out = ts.to_string();
574 for _ in 0..4 {
575 let mut changed = false;
576 let mut next = String::with_capacity(out.len());
577 let mut word = String::new();
578 let flush = |word: &mut String, next: &mut String, changed: &mut bool| {
579 if let Some(t) = types.iter().find(|t| t.alias && t.name == *word) {
580 let text = t.text.trim();
581 if text.contains('|') {
582 next.push('(');
583 next.push_str(text);
584 next.push(')');
585 } else {
586 next.push_str(text);
587 }
588 *changed = true;
589 } else {
590 next.push_str(word);
591 }
592 word.clear();
593 };
594 for c in out.chars() {
595 if c.is_alphanumeric() || c == '_' || c == '$' {
596 word.push(c);
597 } else {
598 flush(&mut word, &mut next, &mut changed);
599 next.push(c);
600 }
601 }
602 flush(&mut word, &mut next, &mut changed);
603 out = next;
604 if !changed {
605 break;
606 }
607 }
608 out
609}
610
611fn needs_js(api: &codegen::PortApi) -> bool {
612 api.needs_json()
613}
614
615fn keep_reason(keep: &[String], name: &str) -> Option<String> {
617 keep.iter().find_map(|k| {
618 let (kept, reason) = k
619 .split_once(':')
620 .map_or((k.as_str(), ""), |(n, r)| (n.trim(), r.trim()));
621 (kept == name).then(|| {
622 if reason.is_empty() {
623 "kept on request".to_string()
624 } else {
625 reason.to_string()
626 }
627 })
628 })
629}
630
631fn format_rust(crate_dir: &Path) {
633 let files: Vec<PathBuf> = std::fs::read_dir(crate_dir.join("src"))
634 .into_iter()
635 .flatten()
636 .flatten()
637 .map(|e| e.path())
638 .filter(|p| p.extension().is_some_and(|e| e == "rs"))
639 .collect();
640 let _ = std::process::Command::new("rustfmt")
641 .args(["--edition", "2024"])
642 .args(&files)
643 .output();
644}
645
646fn format_wrapper(crate_dir: &Path) {
648 if crate_dir.join("go").is_dir() {
649 let _ = std::process::Command::new("gofmt")
650 .arg("-w")
651 .arg(crate_dir.join("go"))
652 .output();
653 }
654}
655
656fn js_lib_rs(m: &Manifest, api: &codegen::PortApi, modules: &codegen::Modules) -> Result<String> {
658 let mut lib = with_allocator(m, codegen::lib_rs(m, api, modules));
659 if m.kind != Kind::Pyo3 && !m.batches.is_empty() {
660 lib.push_str(&crate::codegen_batch::js_rs(m, api).map_err(anyhow::Error::msg)?);
661 }
662 if !crate::codegen_tswire::uses_wire(m, api) {
663 return Ok(lib);
664 }
665 Ok(lib.replacen(
666 "pub mod port;",
667 "pub mod port;\npub mod wire;\n\n#[allow(unused_imports)]\nuse serde_json::Value;",
668 1,
669 ) + &crate::codegen_tswire::napi_rs(m, api))
670}
671
672fn parse_batches(specs: &[String]) -> Result<Vec<crate::codegen_batch::Batch>> {
673 specs
674 .iter()
675 .map(|s| {
676 crate::codegen_batch::Batch::parse(s)
677 .with_context(|| format!("`--batch {s}`: write it as function:param"))
678 })
679 .collect()
680}
681
682pub fn add_batches(crate_dir: &Path, specs: &[String]) -> Result<Refreshed> {
684 let path = crate_dir.join(MANIFEST);
685 let before = std::fs::read_to_string(&path).with_context(|| format!("{}", path.display()))?;
686 let mut manifest = Manifest::load(crate_dir)?;
687 for b in parse_batches(specs)? {
688 if !manifest.batches.contains(&b) {
689 manifest.batches.push(b);
690 }
691 }
692 if let Some(written) = manifest.root_written.clone() {
693 manifest.root = written;
694 }
695 std::fs::write(&path, serde_json::to_string_pretty(&manifest)? + "\n")?;
696 refresh(crate_dir).inspect_err(|_| {
698 let _ = std::fs::write(&path, &before);
699 })
700}
701
702fn with_template_deps(cargo: &str, template: &str) -> Result<String> {
705 let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
706 let template: toml_edit::DocumentMut = template.parse().context("Cargo.toml template")?;
707 if let Some(want) = template.get("dependencies").and_then(|d| d.as_table()) {
708 let deps = doc["dependencies"].or_insert(toml_edit::table());
709 for (name, item) in want {
710 if deps.get(name).is_none() {
711 deps[name] = item.clone();
712 }
713 }
714 }
715 if let Some(want) = template.get("features").and_then(|d| d.as_table()) {
716 let features = doc["features"].or_insert(toml_edit::table());
717 for (name, item) in want {
718 if features.get(name).is_none() {
719 features[name] = item.clone();
720 }
721 }
722 }
723 if let Some(kinds) = template.get("lib").and_then(|l| l.get("crate-type")) {
724 doc["lib"]["crate-type"] = kinds.clone();
725 }
726 Ok(doc.to_string())
727}
728
729fn needs_mimalloc(m: &Manifest) -> bool {
734 !m.batches.is_empty() && m.kind != Kind::Wasm
735}
736
737fn with_allocator(m: &Manifest, lib: String) -> String {
739 if !needs_mimalloc(m) {
740 return lib;
741 }
742 lib.replacen(
743 "pub mod port;",
744 "pub mod port;\n\n/// Batches allocate on all cores at once; mimalloc keeps that from serializing.\n\
745 #[global_allocator]\nstatic GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;\n",
746 1,
747 )
748}
749
750fn with_rayon(m: &Manifest, cargo: String) -> Result<String> {
752 if !crate::codegen_batch::needs_rayon(m) {
753 return Ok(cargo);
754 }
755 let mut doc: toml_edit::DocumentMut = cargo.parse().context("Cargo.toml")?;
756 let deps = doc["dependencies"].or_insert(toml_edit::table());
757 if deps.get("rayon").is_none() {
758 deps["rayon"] = toml_edit::value("1");
759 }
760 if needs_mimalloc(m) && deps.get("mimalloc").is_none() {
761 deps["mimalloc"] = toml_edit::value("0.1");
762 }
763 Ok(doc.to_string())
764}
765
766fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
768 match m.kind {
769 Kind::Pyo3 => (
770 format!("python/{}/__init__.py", m.lib_name()),
771 crate::codegen_py::package_init(m, api),
772 ),
773 _ => (
774 "index.cjs".into(),
775 codegen::index_cjs(m, api)
776 + &crate::codegen_tswire::index_cjs(m, api)
777 + &codegen::guard_cjs(api),
778 ),
779 }
780}
781
782pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
785 for f in &mut api.functions {
786 if m.exports.iter().any(|e| e.name == f.js_name) {
787 continue;
788 }
789 let rust = f.rust_name.trim_start_matches("r#");
790 if let Some(e) = m.exports.iter().find(|e| snake_case(&e.name) == rust) {
791 f.js_name = e.name.clone();
792 }
793 }
794}
795
796#[derive(Debug, Serialize)]
798pub struct Refreshed {
799 pub functions: Vec<String>,
800 pub files: Vec<String>,
801}
802
803pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
806 let manifest = Manifest::load(crate_dir)?;
807 if manifest.kind == Kind::CAbi {
808 let mut files = c_bindings(&manifest);
809 let cargo =
810 std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
811 files.push((
812 "Cargo.toml".into(),
813 with_template_deps(&cargo, &crate::codegen_c::cargo_toml(&manifest))?,
814 ));
815 write_files(crate_dir, &files)?;
816 format_rust(crate_dir);
817 return Ok(Refreshed {
818 functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
819 files: files.into_iter().map(|(p, _)| p).collect(),
820 });
821 }
822 if manifest.kind == Kind::Ffi {
823 let port = std::fs::read_to_string(crate_dir.join("src/port.rs"))
824 .context("reading src/port.rs")?;
825 let mut api = codegen::parse_port(&port);
826 match_export_names(&manifest, &mut api);
827 let mut files = ffi_bindings(&manifest, &api)?;
828 let cargo =
829 std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
830 let template = if manifest.language == crate::lang::Lang::Ruby {
831 crate::codegen_ruby::cargo_toml(&manifest)
832 } else {
833 crate::codegen_ffi::cargo_toml(&manifest)
834 };
835 let cargo = with_template_deps(&cargo, &template)?;
836 files.push(("Cargo.toml".into(), with_rayon(&manifest, cargo)?));
837 write_files(crate_dir, &files)?;
838 format_rust(crate_dir);
839 format_wrapper(crate_dir);
840 return Ok(Refreshed {
841 functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
842 files: files.into_iter().map(|(p, _)| p).collect(),
843 });
844 }
845 let port =
846 std::fs::read_to_string(crate_dir.join("src/port.rs")).context("reading src/port.rs")?;
847 let mut fns = codegen::parse_port(&port);
848 match_export_names(&manifest, &mut fns);
849 if fns.functions.is_empty() && fns.classes.is_empty() {
850 bail!("src/port.rs has no `pub fn` or ported class: nothing to bind");
851 }
852 let modules = codegen::Modules {
853 utf16: crate_dir.join("src/utf16.rs").exists(),
854 js: needs_js(&fns) || crate_dir.join("src/js.rs").exists(),
855 };
856 let mut files: Vec<(String, String)> = vec![
857 ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
858 loader_file(&manifest, &fns),
859 ];
860 if modules.js {
861 files.push(("src/js.rs".into(), codegen::JS_RS.to_string()));
862 }
863 if crate::codegen_tswire::uses_wire(&manifest, &fns) {
864 files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
865 }
866 let extension = manifest.kind == Kind::Pyo3
867 || (manifest.kind == Kind::Ffi && manifest.language == crate::lang::Lang::Ruby);
868 if extension && !crate_dir.join("build.rs").exists() {
869 files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into()));
870 }
871 if manifest.kind == Kind::Pyo3 && fns.needs_json() {
872 files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
873 files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
874 }
875 let cargo_path = crate_dir.join("Cargo.toml");
876 let cargo = std::fs::read_to_string(&cargo_path).context("reading Cargo.toml")?;
877 let cargo = codegen::ensure_deps(&cargo, manifest.kind, &fns).map_err(anyhow::Error::msg)?;
878 let cargo = with_rayon(&manifest, cargo)?;
879 files.push(("Cargo.toml".into(), cargo));
880 for (path, text) in &files {
881 let target = crate_dir.join(path);
882 if let Some(parent) = target.parent() {
883 std::fs::create_dir_all(parent)?;
884 }
885 std::fs::write(&target, text).with_context(|| format!("writing {path}"))?;
886 }
887 format_rust(crate_dir);
888 Ok(Refreshed {
889 functions: fns
890 .functions
891 .iter()
892 .map(|f| f.js_name.clone())
893 .chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
894 .collect(),
895 files: files.into_iter().map(|(p, _)| p).collect(),
896 })
897}
898
899pub(crate) const DYNAMIC_LOOKUP_BUILD_RS: &str = r#"fn main() {
902 if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
903 println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
904 }
905}
906"#;
907
908pub fn bridge(opts: &Options) -> Result<Outcome> {
909 let root = opts
910 .root
911 .canonical()
912 .with_context(|| format!("resolving {}", opts.root.display()))?;
913 let lang = opts
914 .lang
915 .unwrap_or_else(|| crate::lang::Lang::detect(&root));
916 let report = analyze::analyze_lang(&root, lang)?;
917 let wanted = opts.unit.trim_start_matches("./");
918 let unit = report
919 .units
920 .iter()
921 .find(|u| u.id == wanted || u.id.trim_end_matches('/') == wanted.trim_end_matches('/'))
922 .with_context(|| format!("no unit `{wanted}`; `rust-anything analyze` lists unit ids"))?;
923 if matches!(unit.status, Status::Keep | Status::Blocked) && !opts.force {
924 bail!(
925 "unit `{}` is {:?}: {}. Pass --force to bridge it anyway.",
926 unit.id,
927 unit.status,
928 unit.notes.first().map_or("", String::as_str)
929 );
930 }
931 if unit.bridge == Bridge::PhpFfi {
932 bail!(
933 "bridging PHP units into Rust comes next (PHP FFI over a C ABI); for now a PHP app can \
934 be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
935 door (`app front-door`) that hands everything to the original"
936 );
937 }
938 if unit.bridge == Bridge::DotnetFfi {
939 bail!(
940 "bridging C# units into Rust comes next (P/Invoke over a C ABI); for now a C# app can \
941 be analyzed, recorded and replayed (`app record`, `app replay`) and get a Rust front \
942 door (`app front-door`) that hands everything to the original"
943 );
944 }
945 let kind = opts.kind.unwrap_or(match unit.bridge {
946 Bridge::WasmBindgen => Kind::Wasm,
947 Bridge::Pyo3 => Kind::Pyo3,
948 Bridge::CAbi => Kind::CAbi,
949 Bridge::Cgo | Bridge::Fiddle | Bridge::Jni => Kind::Ffi,
950 _ => Kind::Napi,
951 });
952
953 let mut exports = Vec::new();
954 let mut classes = Vec::new();
955 let mut js_only = Vec::new();
956 for file in &unit.files {
957 if file.ends_with(".vue") || file.ends_with(".svelte") || file.ends_with(".astro") {
958 continue;
959 }
960 let text =
961 std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
962 if lang != crate::lang::Lang::Ts {
963 let (functions, foreign_classes) = crate::lang::exports(lang, file, &text);
964 for f in functions {
965 match keep_reason(&opts.keep, &f.name).or_else(|| js_only_reason(&f, &[])) {
966 Some(reason) => js_only.push(JsOnly {
967 name: f.name,
968 file: f.file,
969 line: f.line,
970 reason,
971 }),
972 None => exports.push(f),
973 }
974 }
975 for class in foreign_classes {
976 let method_reason = class
977 .methods
978 .iter()
979 .find_map(|m| js_only_reason(m, &[]).map(|r| format!("`{}`: {r}", m.name)));
980 match keep_reason(&opts.keep, &class.name)
981 .or_else(|| class.blocker.clone())
982 .or(method_reason)
983 {
984 Some(reason) => js_only.push(JsOnly {
985 name: class.name,
986 file: class.file,
987 line: class.line,
988 reason: format!("class: {reason}"),
989 }),
990 None => classes.push(class),
991 }
992 }
993 continue;
994 }
995 let types = types_in_scope(&root, file, &text);
996 for mut class in exported_classes(file, &text) {
997 let kept = keep_reason(&opts.keep, &class.name);
998 let constructor = ExportedFn {
999 name: format!("{} constructor", class.name),
1000 file: class.file.clone(),
1001 line: class.line,
1002 params: class.constructor.clone(),
1003 returns: "void".into(),
1004 is_async: false,
1005 is_generator: false,
1006 type_params: Vec::new(),
1007 uses_instanceof: false,
1008 ..Default::default()
1009 };
1010 let method_reason = std::iter::once(&constructor)
1011 .chain(&class.methods)
1012 .find_map(|m| js_only_reason(m, &types).map(|r| format!("`{}`: {r}", m.name)));
1013 match kept.or_else(|| class.blocker.clone()).or(method_reason) {
1014 Some(reason) => js_only.push(JsOnly {
1015 name: class.name,
1016 file: class.file,
1017 line: class.line,
1018 reason: format!("class: {reason}"),
1019 }),
1020 None => {
1021 for p in &mut class.constructor {
1022 p.ts_type = resolve_aliases(&p.ts_type, &types);
1023 }
1024 for m in &mut class.methods {
1025 for p in &mut m.params {
1026 p.ts_type = resolve_aliases(&p.ts_type, &types);
1027 }
1028 m.returns = resolve_aliases(&m.returns, &types);
1029 }
1030 classes.push(class);
1031 }
1032 }
1033 }
1034 for mut f in exported_functions(file, &text) {
1035 for p in &mut f.params {
1036 p.ts_type = resolve_aliases(&p.ts_type, &types);
1037 }
1038 f.returns = resolve_aliases(&f.returns, &types);
1039 substitute_constraints(&mut f, &types);
1040 let kept = keep_reason(&opts.keep, &f.name);
1041 match kept.or_else(|| js_only_reason(&f, &types)) {
1042 Some(reason) => js_only.push(JsOnly {
1043 name: f.name,
1044 file: f.file,
1045 line: f.line,
1046 reason,
1047 }),
1048 None => exports.push(f),
1049 }
1050 }
1051 }
1052 if exports.is_empty() && classes.is_empty() && !js_only.is_empty() {
1053 bail!(
1054 "every export of `{}` must stay in {}: {}",
1055 unit.id,
1056 lang.name(),
1057 js_only
1058 .iter()
1059 .map(|j| format!("{} ({})", j.name, j.reason))
1060 .collect::<Vec<_>>()
1061 .join(", ")
1062 );
1063 }
1064 if exports.is_empty() && classes.is_empty() {
1065 bail!(
1066 "unit `{}` exports no functions; bridge a unit with an exported function API",
1067 unit.id
1068 );
1069 }
1070
1071 let stem = unit
1072 .id
1073 .trim_end_matches('/')
1074 .rsplit('/')
1075 .next()
1076 .unwrap_or("unit")
1077 .split('.')
1078 .next()
1079 .unwrap_or("unit");
1080 let crate_name = opts.name.clone().unwrap_or_else(|| {
1081 let clean: String = stem
1082 .chars()
1083 .map(|c| {
1084 if c.is_ascii_alphanumeric() {
1085 c.to_ascii_lowercase()
1086 } else {
1087 '-'
1088 }
1089 })
1090 .collect();
1091 format!("{}-rs", clean.trim_matches('-'))
1092 });
1093 let crate_dir = opts
1094 .out
1095 .clone()
1096 .unwrap_or_else(|| root.join("rust").join(&crate_name));
1097 if crate_dir.exists() && std::fs::read_dir(&crate_dir)?.next().is_some() {
1098 bail!(
1099 "{} already exists and is not empty; rust-anything never overwrites a port in progress",
1100 crate_dir.display()
1101 );
1102 }
1103
1104 let utf16 =
1106 lang == crate::lang::Lang::Ts && unit.risks.iter().any(|r| r.risk == Risk::StringOffsets);
1107 let manifest = Manifest {
1108 schema: SCHEMA.into(),
1109 root: root.clone(),
1110 root_written: None,
1111 unit: unit.id.clone(),
1112 language: lang,
1113 kind,
1114 crate_name: crate_name.clone(),
1115 exports: exports.clone(),
1116 classes: classes.clone(),
1117 js_only: js_only.clone(),
1118 batches: parse_batches(&opts.batch)?,
1119 float_tolerance: None,
1120 };
1121 if kind == Kind::CAbi {
1122 return bridge_c(&manifest, &crate_dir, &js_only);
1123 }
1124 if kind == Kind::Ffi {
1125 return bridge_ffi(&manifest, &crate_dir, &js_only);
1126 }
1127 let port = codegen::port_rs(&manifest);
1128 let fns = codegen::parse_port(&port);
1129 let modules = codegen::Modules {
1130 utf16,
1131 js: needs_js(&fns),
1132 };
1133 let mut files: Vec<(String, String)> = vec![
1134 (
1135 "Cargo.toml".into(),
1136 with_rayon(&manifest, codegen::cargo_toml(&manifest, &fns))?,
1137 ),
1138 ("src/lib.rs".into(), js_lib_rs(&manifest, &fns, &modules)?),
1139 ("src/port.rs".into(), port),
1140 loader_file(&manifest, &fns),
1141 (
1142 ".gitignore".into(),
1143 "target/\n*.node\npkg/\n.rust-anything/\n*.so\n*.pyd\n__pycache__/\n".into(),
1144 ),
1145 ("README.md".into(), readme(&manifest)),
1146 (
1147 MANIFEST.into(),
1148 serde_json::to_string_pretty(&manifest)? + "\n",
1149 ),
1150 ];
1151 match kind {
1152 Kind::Napi => files.push((
1153 "build.rs".into(),
1154 "fn main() {\n napi_build::setup();\n}\n".into(),
1155 )),
1156 Kind::Pyo3 => files.push(("build.rs".into(), DYNAMIC_LOOKUP_BUILD_RS.into())),
1157 _ => {}
1158 }
1159 if utf16 {
1160 files.push(("src/utf16.rs".into(), UTF16_RS.into()));
1161 }
1162 if modules.js {
1163 files.push(("src/js.rs".into(), codegen::JS_RS.into()));
1164 }
1165 if crate::codegen_tswire::uses_wire(&manifest, &fns) {
1166 files.push(("src/wire.rs".into(), crate::wire::WIRE_RS.into()));
1167 }
1168 if manifest.kind == Kind::Pyo3 && fns.needs_json() {
1169 files.push(("src/pyconv.rs".into(), crate::codegen_py::PYCONV_RS.into()));
1170 files.push(("src/pynum.rs".into(), crate::codegen_py::PYNUM_RS.into()));
1171 }
1172 for (path, text) in &files {
1173 let target = crate_dir.join(path);
1174 if let Some(parent) = target.parent() {
1175 std::fs::create_dir_all(parent)?;
1176 }
1177 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1178 }
1179
1180 format_rust(&crate_dir);
1181 let mut notes = vec![format!(
1182 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1183 crate_dir.display()
1184 )];
1185 if utf16 {
1186 notes.push("The unit works with string offsets: src/utf16.rs has UTF-16 helpers that match JS indexing.".into());
1187 }
1188 for j in &js_only {
1189 notes.push(format!(
1190 "`{}` stays in {}: {}. The shadow module re-exports the original.",
1191 j.name,
1192 lang.name(),
1193 j.reason
1194 ));
1195 }
1196 if exports.iter().any(codegen::is_async) {
1197 notes.push(
1198 "Async TS functions are `async fn` in the port; the bindings return promises.".into(),
1199 );
1200 }
1201 Ok(Outcome {
1202 crate_dir,
1203 kind,
1204 files: files.into_iter().map(|(p, _)| p).collect(),
1205 exports: exports
1206 .iter()
1207 .map(|f| f.name.clone())
1208 .chain(classes.iter().map(|c| format!("class {}", c.name)))
1209 .collect(),
1210 notes,
1211 })
1212}
1213
1214fn write_files(crate_dir: &Path, files: &[(String, String)]) -> Result<()> {
1215 for (path, text) in files {
1216 let target = crate_dir.join(path);
1217 if let Some(parent) = target.parent() {
1218 std::fs::create_dir_all(parent)?;
1219 }
1220 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
1221 }
1222 Ok(())
1223}
1224
1225fn c_bindings(m: &Manifest) -> Vec<(String, String)> {
1228 vec![
1229 ("src/lib.rs".into(), crate::codegen_c::lib_rs(m)),
1230 (
1231 format!("include/{}.h", m.lib_name()),
1232 crate::codegen_c::header(m),
1233 ),
1234 ]
1235}
1236
1237fn ffi_bindings(m: &Manifest, api: &codegen::PortApi) -> Result<Vec<(String, String)>> {
1239 let mut files = if m.language == crate::lang::Lang::Ruby {
1240 vec![
1241 (
1242 "src/lib.rs".to_string(),
1243 with_allocator(
1244 m,
1245 crate::codegen_ruby::lib_rs(m, api).map_err(anyhow::Error::msg)?,
1246 ),
1247 ),
1248 (
1249 "src/rbconv.rs".to_string(),
1250 crate::codegen_ruby::RBCONV_RS.to_string(),
1251 ),
1252 ("build.rs".to_string(), DYNAMIC_LOOKUP_BUILD_RS.to_string()),
1253 ]
1254 } else {
1255 let mut lib = crate::codegen_ffi::lib_rs(m, api);
1256 if m.language == crate::lang::Lang::Java {
1257 lib.push_str(&crate::codegen_java::typed_rs(m, api));
1258 }
1259 if m.language == crate::lang::Lang::Go {
1260 lib.push_str(&crate::codegen_go::typed_rs(m, api));
1261 lib.push_str(&crate::codegen_go::wire_rs(m, api));
1262 lib.push_str(&crate::codegen_batch_native::go_rs(m, api).map_err(anyhow::Error::msg)?);
1263 }
1264 if m.language == crate::lang::Lang::Java {
1265 lib.push_str(&crate::codegen_java::wire_rs(m, api));
1266 lib.push_str(
1267 &crate::codegen_batch_native::java_rs(m, api).map_err(anyhow::Error::msg)?,
1268 );
1269 }
1270 if matches!(m.language, crate::lang::Lang::Go | crate::lang::Lang::Java) {
1271 lib = lib.replacen("pub mod port;", "pub mod port;\npub mod wire;", 1);
1272 }
1273 let mut files = vec![("src/lib.rs".to_string(), with_allocator(m, lib))];
1274 if matches!(m.language, crate::lang::Lang::Go | crate::lang::Lang::Java) {
1275 files.push(("src/wire.rs".to_string(), crate::wire::WIRE_RS.to_string()));
1276 }
1277 files
1278 };
1279 match m.language {
1280 crate::lang::Lang::Go => {
1281 if crate::codegen_go::unit_sources(m).is_empty() {
1284 bail!(
1285 "cannot read the Go sources of `{}` under {}: is `root` in {MANIFEST} right?",
1286 m.unit,
1287 m.root.display()
1288 );
1289 }
1290 files.push(("go/go.mod".into(), crate::harness_go::wrapper_go_mod(m)));
1291 files.push((
1292 format!("go/{}.go", crate::codegen_go::package_name(m)),
1293 crate::codegen_go::wrapper(m, api),
1294 ));
1295 }
1296 crate::lang::Lang::Ruby => {
1297 files.push((
1298 crate::harness_ruby::wrapper_path(m),
1299 crate::codegen_ruby::wrapper(m, api).map_err(anyhow::Error::msg)?,
1300 ));
1301 }
1302 crate::lang::Lang::Java => {
1303 files.extend(crate::codegen_java::wrappers(m, api));
1304 files.extend(
1305 crate::codegen_batch_native::java_files(m, api).map_err(anyhow::Error::msg)?,
1306 );
1307 files.push((
1308 format!(
1309 "java/rustanything/{}.java",
1310 crate::codegen_ffi::java_native_class(m)
1311 ),
1312 crate::codegen_java::native_class(m, api),
1313 ));
1314 files.push((
1315 "java/rustanything/RustAnythingJson.java".into(),
1316 crate::codegen_java::JSON_JAVA.into(),
1317 ));
1318 files.push((
1319 "java/rustanything/RustAnythingWire.java".into(),
1320 crate::codegen_java::WIRE_JAVA.into(),
1321 ));
1322 files.push((
1323 "java/rustanything/RustAnythingError.java".into(),
1324 crate::codegen_java::ERROR_JAVA.into(),
1325 ));
1326 }
1327 other => bail!("no wrapper generator for {}", other.name()),
1328 }
1329 Ok(files)
1330}
1331
1332fn bridge_ffi(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1333 let port = codegen::port_rs(manifest);
1334 let api = codegen::parse_port(&port);
1335 let mut files = vec![
1336 (
1337 "Cargo.toml".to_string(),
1338 with_rayon(
1339 manifest,
1340 if manifest.language == crate::lang::Lang::Ruby {
1341 crate::codegen_ruby::cargo_toml(manifest)
1342 } else {
1343 crate::codegen_ffi::cargo_toml(manifest)
1344 },
1345 )?,
1346 ),
1347 ("src/port.rs".into(), port),
1348 (
1349 ".gitignore".into(),
1350 "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1351 ),
1352 ("README.md".into(), readme(manifest)),
1353 (
1354 MANIFEST.into(),
1355 serde_json::to_string_pretty(manifest)? + "\n",
1356 ),
1357 ];
1358 files.extend(ffi_bindings(manifest, &api)?);
1359 write_files(crate_dir, &files)?;
1360 format_rust(crate_dir);
1361 format_wrapper(crate_dir);
1362 let mut notes = vec![format!(
1363 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1364 crate_dir.display()
1365 )];
1366 for j in kept {
1367 notes.push(format!(
1368 "`{}` stays in {}: {}.",
1369 j.name,
1370 manifest.language.name(),
1371 j.reason
1372 ));
1373 }
1374 Ok(Outcome {
1375 crate_dir: crate_dir.to_path_buf(),
1376 kind: Kind::Ffi,
1377 files: files.into_iter().map(|(p, _)| p).collect(),
1378 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1379 notes,
1380 })
1381}
1382
1383fn bridge_c(manifest: &Manifest, crate_dir: &Path, kept: &[JsOnly]) -> Result<Outcome> {
1384 let mut files = vec![
1385 (
1386 "Cargo.toml".to_string(),
1387 crate::codegen_c::cargo_toml(manifest),
1388 ),
1389 ("src/port.rs".into(), crate::codegen_c::port_rs(manifest)),
1390 (
1391 ".gitignore".into(),
1392 "target/\n.rust-anything/\nruby/*.so\nruby/*.bundle\n".into(),
1393 ),
1394 ("README.md".into(), readme(manifest)),
1395 (
1396 MANIFEST.into(),
1397 serde_json::to_string_pretty(manifest)? + "\n",
1398 ),
1399 ];
1400 files.extend(c_bindings(manifest));
1401 write_files(crate_dir, &files)?;
1402 format_rust(crate_dir);
1403 let mut notes = vec![
1404 format!(
1405 "Port each function in src/port.rs, then: rust-anything record {0} && rust-anything build {0} && rust-anything diff {0}",
1406 crate_dir.display()
1407 ),
1408 format!(
1409 "Link target/release/lib{}.a (or the .so) instead of the C objects; include/{}.h has the prototypes.",
1410 manifest.lib_name(),
1411 manifest.lib_name()
1412 ),
1413 ];
1414 for j in kept {
1415 notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));
1416 }
1417 Ok(Outcome {
1418 crate_dir: crate_dir.to_path_buf(),
1419 kind: Kind::CAbi,
1420 files: files.into_iter().map(|(p, _)| p).collect(),
1421 exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
1422 notes,
1423 })
1424}
1425
1426fn readme(m: &Manifest) -> String {
1427 let functions: String = m
1428 .exports
1429 .iter()
1430 .map(|f| format!("- `{}` (`{}:{}`)\n", f.name, f.file, f.line))
1431 .collect();
1432 format!(
1433 "# {name}\n\nRust port of `{unit}`, bridged with {kind}. Generated by rust-anything.\n\n## Functions\n\n{functions}\n\
1434 ## Loop\n\n```sh\nrust-anything record . # record what the TS code does\nrust-anything build . # build the {kind} module\n\
1435 rust-anything diff . # run the recorded cases against Rust\nrust-anything shadow . # run both in the app, log mismatches\n\
1436 rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n```\n",
1437 name = m.crate_name,
1438 unit = m.unit,
1439 kind = match m.kind {
1440 Kind::Napi => "napi-rs",
1441 Kind::Wasm => "wasm-bindgen",
1442 Kind::Pyo3 => "PyO3",
1443 Kind::CAbi => "the C ABI",
1444 Kind::Ffi => "a JSON dispatcher",
1445 },
1446 )
1447}
1448
1449const UTF16_RS: &str = r#"//! JS string indexing in Rust.
1450//!
1451//! JS strings are indexed in UTF-16 code units; Rust `str` in UTF-8 bytes. A port that returns
1452//! or consumes offsets must use these helpers, or non-ASCII text gets wrong results silently.
1453
1454#![forbid(unsafe_code)]
1455
1456/// The UTF-16 code units of `s`, as JS sees the string.
1457pub fn units(s: &str) -> Vec<u16> {
1458 s.encode_utf16().collect()
1459}
1460
1461/// The string `units[start..end]` decodes to, like JS `slice` (lone surrogates become U+FFFD).
1462pub fn slice(units: &[u16], start: usize, end: usize) -> String {
1463 let end = end.min(units.len());
1464 let start = start.min(end);
1465 String::from_utf16_lossy(&units[start..end])
1466}
1467
1468/// JS `haystack.indexOf(needle, from)`, in UTF-16 code units.
1469pub fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option<usize> {
1470 let from = from.min(haystack.len());
1471 if needle.is_empty() {
1472 return Some(from);
1473 }
1474 haystack[from..]
1475 .windows(needle.len())
1476 .position(|w| w == needle)
1477 .map(|i| i + from)
1478}
1479
1480/// JS `haystack.lastIndexOf(needle)`, in UTF-16 code units.
1481pub fn last_index_of(haystack: &[u16], needle: &[u16]) -> Option<usize> {
1482 if needle.is_empty() {
1483 return Some(haystack.len());
1484 }
1485 haystack.windows(needle.len()).rposition(|w| w == needle)
1486}
1487
1488/// UTF-8 byte offset of a UTF-16 offset in `s`, for slicing a Rust `str`.
1489pub fn byte_offset(s: &str, utf16_offset: usize) -> usize {
1490 let mut seen = 0;
1491 for (byte, c) in s.char_indices() {
1492 if seen >= utf16_offset {
1493 return byte;
1494 }
1495 seen += c.len_utf16();
1496 }
1497 s.len()
1498}
1499
1500/// UTF-16 offset of a UTF-8 byte offset in `s`, for returning ranges to JS.
1501pub fn utf16_offset(s: &str, byte_offset: usize) -> usize {
1502 s[..byte_offset.min(s.len())].encode_utf16().count()
1503}
1504
1505#[cfg(test)]
1506mod tests {
1507 use super::*;
1508
1509 #[test]
1510 fn matches_js_indexing() {
1511 let s = units("a👍b");
1512 assert_eq!(s.len(), 4);
1513 assert_eq!(index_of(&s, &units("b"), 0), Some(3));
1514 assert_eq!(last_index_of(&s, &units("a")), Some(0));
1515 assert_eq!(slice(&s, 3, 4), "b");
1516 assert_eq!(byte_offset("a👍b", 3), 5);
1517 assert_eq!(utf16_offset("a👍b", 5), 3);
1518 }
1519}
1520"#;
1521
1522#[cfg(test)]
1523mod tests {
1524 use super::*;
1525
1526 #[test]
1527 fn a_relative_root_is_resolved_from_the_crate_and_kept_relative() {
1528 let base = std::env::temp_dir().join(format!("rust-anything-root-{}", std::process::id()));
1529 let _ = std::fs::remove_dir_all(&base);
1530 let crate_dir = base.join("repo/rust/x-rs");
1531 std::fs::create_dir_all(&crate_dir).unwrap();
1532 std::fs::write(
1533 crate_dir.join(MANIFEST),
1534 r#"{"schema": "rust-anything/bridge@1", "root": "../..", "unit": "src/x.ts", "kind": "napi", "crate_name": "x-rs", "exports": []}"#,
1535 )
1536 .unwrap();
1537 let m = Manifest::load(&crate_dir).unwrap();
1538 assert_eq!(m.root, base.join("repo").canonicalize().unwrap());
1539 assert_eq!(m.root_written.as_deref(), Some(Path::new("../..")));
1540 let mut back = m.clone();
1542 if let Some(w) = back.root_written.clone() {
1543 back.root = w;
1544 }
1545 assert!(
1546 serde_json::to_string(&back)
1547 .unwrap()
1548 .contains(r#""root":"../..""#)
1549 );
1550 std::fs::remove_dir_all(&base).unwrap();
1551 }
1552
1553 #[test]
1554 fn maps_ts_types() {
1555 assert_eq!(RType::from_ts("string").rust(), "String");
1556 assert_eq!(RType::from_ts("readonly string[]").rust(), "Vec<String>");
1557 assert_eq!(RType::from_ts("Array<number>").rust(), "Vec<f64>");
1558 assert_eq!(
1559 RType::from_ts("string | undefined").rust(),
1560 "Option<String>"
1561 );
1562 assert_eq!(RType::from_ts("'a' | 'b'").rust(), "String");
1563 assert_eq!(RType::from_ts("Promise<boolean>").rust(), "bool");
1564 assert_eq!(
1565 RType::from_ts("Map<string, number>").rust(),
1566 "serde_json::Value"
1567 );
1568 assert_eq!(
1569 RType::from_ts("string | number").rust(),
1570 "serde_json::Value"
1571 );
1572 assert_eq!(
1573 RType::from_ts("Record<string, string | number>").rust(),
1574 "serde_json::Value"
1575 );
1576 assert_eq!(
1577 RType::from_ts("(string | undefined)").rust(),
1578 "Option<String>"
1579 );
1580 assert_eq!(RType::from_ts("(a) | (b)").rust(), "serde_json::Value");
1581 }
1582
1583 #[test]
1584 fn keeps_unbridgeable_exports_in_js() {
1585 let source = "export interface LineIndex {\n readonly lineCount: number\n position(offset: number): number\n}\n\
1586 export interface Range { start: number, end: number }\n\
1587 export function keyMatcher(globs: readonly string[]): (key: string) => boolean { return () => true }\n\
1588 export function globToRegExp(glob: string): RegExp { return /x/ }\n\
1589 export function createLineIndex(text: string): LineIndex { return null! }\n\
1590 export function* walk(tree: object) {}\n\
1591 export function sortTree(tree: object, compare: (a: string, b: string) => number) {}\n\
1592 export function contains(range: Range, offset: number): boolean { return true }\n";
1593 let types = local_types("a.ts", source);
1594 let reasons: Vec<(String, Option<String>)> = exported_functions("a.ts", source)
1595 .iter()
1596 .map(|f| (f.name.clone(), js_only_reason(f, &types)))
1597 .collect();
1598 let js_only: Vec<&str> = reasons
1599 .iter()
1600 .filter(|(_, r)| r.is_some())
1601 .map(|(n, _)| n.as_str())
1602 .collect();
1603 assert_eq!(
1604 js_only,
1605 [
1606 "keyMatcher",
1607 "globToRegExp",
1608 "createLineIndex",
1609 "walk",
1610 "sortTree"
1611 ]
1612 );
1613 }
1614
1615 #[test]
1616 fn resolves_simple_aliases() {
1617 let types = local_types(
1618 "m.ts",
1619 "export type KeyString = string\nexport type Leaf = string | null\nexport type Map2<T> = T\n",
1620 );
1621 assert_eq!(
1622 resolve_aliases("readonly KeyString[]", &types),
1623 "readonly string[]"
1624 );
1625 assert_eq!(resolve_aliases("Leaf", &types), "(string | null)");
1626 assert_eq!(resolve_aliases("Map2<KeyString>", &types), "Map2<string>");
1627 }
1628
1629 #[test]
1630 fn substitutes_simple_constraints() {
1631 let found = exported_functions(
1632 "a.ts",
1633 "export function up<T extends string>(s: T): Uppercase<T> { return s as any }\n\
1634 export function pick<T>(x: T): T { return x }\n\
1635 export function first<S extends readonly string[]>(xs: S, n?: number): string { return '' }\n",
1636 );
1637 let mut fns = found;
1638 for f in &mut fns {
1639 substitute_constraints(f, &[]);
1640 }
1641 assert_eq!(fns[0].params[0].ts_type, "(string)");
1642 assert!(fns[0].type_params.is_empty());
1643 assert_eq!(fns[1].type_params, ["T"]);
1644 assert_eq!(fns[2].params[0].ts_type, "(readonly string[])");
1645 assert!(js_only_reason(&fns[0], &[]).is_none() && js_only_reason(&fns[1], &[]).is_some());
1646 }
1647
1648 #[test]
1649 fn makes_rust_names() {
1650 assert_eq!(snake_case("fuzzyScore"), "fuzzy_score");
1651 assert_eq!(snake_case("type"), "r#type");
1652 assert_eq!(snake_case("toURL"), "to_url");
1653 assert_eq!(snake_case("parseHTMLString"), "parse_html_string");
1654 }
1655}