1use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::{Context, Result, bail};
10use serde::Serialize;
11
12use crate::bridge::Manifest;
13use crate::lang::Lang;
14use crate::profile::{Hot, Report};
15use crate::walk::Canonical;
16
17pub const TASK: &str = "TASK.md";
18
19pub struct Options<'a> {
20 pub root: &'a Path,
21 pub command: &'a [String],
22 pub lang: Option<Lang>,
23 pub agent: Option<&'a str>,
25 pub function: Option<&'a str>,
27 pub count: usize,
29 pub rounds: usize,
31}
32
33#[derive(Debug, Clone, Serialize)]
34pub struct Pick {
35 pub function: String,
36 pub file: String,
37 pub line: u32,
38 pub total_pct: f64,
39 #[serde(skip_serializing_if = "Option::is_none")]
41 pub batch: Option<String>,
42 #[serde(skip_serializing_if = "Option::is_none")]
44 pub caller: Option<(String, String)>,
45 pub why: String,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "snake_case")]
50pub enum Stage {
51 WaitingForPort,
53 Mismatch,
55 GateFailed,
57 On,
59 Passed,
61 Slower,
64}
65
66#[derive(Debug, Serialize)]
67pub struct Outcome {
68 pub stage: Stage,
69 pub pick: Pick,
70 pub crate_dir: PathBuf,
71 pub task: PathBuf,
72 #[serde(skip_serializing_if = "Option::is_none")]
73 pub cases: Option<usize>,
74 #[serde(skip_serializing_if = "Option::is_none")]
75 pub matched: Option<usize>,
76 #[serde(skip_serializing_if = "Option::is_none")]
78 pub speedup: Option<f64>,
79 pub failed_checks: Vec<String>,
80 pub steps: Vec<String>,
81 pub next: String,
82}
83
84pub fn pick(report: &Report, function: Option<&str>) -> Result<Pick> {
87 let eligible = |h: &&Hot| h.unit.is_some() && h.portable && h.exported && !h.params.is_empty();
88 let hot = match function {
89 Some(name) => report
90 .hot
91 .iter()
92 .find(|h| h.name == name)
93 .with_context(|| {
94 format!("`{name}` is not among the hot functions of this run (see `rust-anything profile`)")
95 })?,
96 None => report.hot.iter().find(eligible).with_context(|| {
97 format!(
98 "no hot function to port: none of the {} hot functions is exported by a portable \
99 unit and takes arguments. `rust-anything profile` shows why.",
100 report.hot.len()
101 )
102 })?,
103 };
104 if !eligible(&hot) {
105 bail!("`{}` cannot be bridged: {}", hot.name, hot.advice);
106 }
107 let why = match &hot.batch {
108 Some(spec) => format!(
109 "{:.0}% of the run; called in a loop by `{}`, so it is bridged with `--batch {spec}`",
110 hot.total_pct,
111 hot.callers
112 .first()
113 .map_or("its caller", |c| c.name.as_str())
114 ),
115 None => format!(
116 "{:.0}% of the run, the outermost portable function",
117 hot.total_pct
118 ),
119 };
120 Ok(Pick {
121 function: hot.name.clone(),
122 file: hot.file.clone(),
123 line: hot.line,
124 total_pct: hot.total_pct,
125 batch: hot.batch.clone(),
126 caller: hot
127 .callers
128 .first()
129 .map(|c| (c.name.clone(), format!("{}:{}", c.file, c.line))),
130 why,
131 })
132}
133
134pub fn crate_name(function: &str) -> String {
135 format!(
136 "{}-rs",
137 crate::bridge::snake_case(function).replace('_', "-")
138 )
139}
140
141fn others(root: &Path, lang: Lang, file: &str, function: &str) -> Result<Vec<String>> {
143 let text =
144 std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
145 let (fns, classes) = if lang == Lang::Ts {
146 (
147 crate::ts::exports::exported_functions(file, &text),
148 crate::ts::exports::exported_classes(file, &text),
149 )
150 } else {
151 crate::lang::exports(lang, file, &text)
152 };
153 Ok(fns
154 .into_iter()
155 .map(|f| f.name)
156 .chain(classes.into_iter().map(|c| c.name))
157 .filter(|n| n != function)
158 .map(|n| format!("{n}: not hot in the profiled run; `go` ports one function"))
159 .collect())
160}
161
162pub fn task(crate_dir: &Path, pick: &Pick, command: &[String]) -> String {
163 let batch = pick.batch.as_ref().map_or_else(String::new, |spec| {
164 let function = spec.split(':').next().unwrap_or(&pick.function);
165 format!(
166 "\nThe crate also has a batch class for `{spec}`, which runs `{function}` over many \
167 items kept in Rust. A `{}Index` struct in `src/port.rs` can prepare the items once \
168 (see the Hot paths section of rust-anything's docs/how-it-works.md); `rust-anything go` runs `rust-anything \
169 refresh` before building, so the batch class uses it.\n",
170 crate::codegen_batch::pascal(function)
171 )
172 });
173 format!(
174 "# Port `{function}` to Rust\n\n\
175 `{function}` (`{file}:{line}`) took {pct:.0}% of `{command}`. Port it, and only it, in \
176 `src/port.rs` of this crate ({dir}). The bindings, the recorded cases and \
177 `rust-anything.json` are generated: leave them as they are.\n{batch}\n\
178 ## Rules\n\n\
179 - Match the original exactly on every recorded case in `cases.jsonl`: values, errors and \
180 their messages, edge cases (empty input, Unicode, large numbers). Read the original \
181 first; port its behavior, not a cleaner idea of it.\n\
182 - No `unwrap`, `expect` or `panic!` outside tests; no `unsafe` without a `// SAFETY:` comment.\n\
183 - Keep helpers private; only the unit's functions are `pub`.\n\n\
184 ## Loop\n\n\
185 ```sh\n\
186 rust-anything build .\n\
187 rust-anything diff . # every recorded case must match\n\
188 rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n\
189 ```\n\n\
190 Done when `diff` matches every case and `gate` passes. Do not switch the port on; \
191 `rust-anything go` does that once both pass.\n",
192 function = pick.function,
193 file = pick.file,
194 line = pick.line,
195 pct = pick.total_pct,
196 command = command.join(" "),
197 dir = crate_dir.display(),
198 )
199}
200
201pub fn agent_command(agent: &str) -> Result<Command> {
204 let words: Vec<&str> = agent.split_whitespace().collect();
205 let (program, args) = words.split_first().context("--agent is empty")?;
206 let mut cmd = Command::new(program);
207 match *program {
208 "claude" if args.is_empty() => {
209 cmd.args([
210 "-p",
211 "--permission-mode",
212 "acceptEdits",
213 "--allowedTools",
214 "Bash(cargo:*)",
215 "Bash(rust-anything:*)",
216 ]);
217 }
218 "codex" if args.is_empty() => {
219 cmd.args(["exec", "--full-auto", "-"]);
220 }
221 _ => {
222 cmd.args(args);
223 }
224 }
225 Ok(cmd)
226}
227
228fn say(steps: &mut Vec<String>, line: String) {
229 eprintln!("go: {line}");
230 steps.push(line);
231}
232
233pub fn go(opts: &Options) -> Result<Outcome> {
234 let root = opts
235 .root
236 .canonical()
237 .with_context(|| format!("resolving {}", opts.root.display()))?;
238 let lang = opts.lang.unwrap_or_else(|| Lang::detect(&root));
239 let mut steps = Vec::new();
240
241 let report = crate::profile::profile(&root, opts.command, Some(lang))?;
242 let pick = pick(&report, opts.function)?;
243 say(
244 &mut steps,
245 format!(
246 "profiled `{}` ({:.0} ms): porting `{}` ({}:{}), {}",
247 opts.command.join(" "),
248 report.total_ms,
249 pick.function,
250 pick.file,
251 pick.line,
252 pick.why
253 ),
254 );
255
256 let name = crate_name(&pick.function);
257 let crate_dir = root.join("rust").join(&name);
258 if crate_dir.join("rust-anything.json").is_file() {
259 let m = Manifest::load(&crate_dir)?;
260 if !m.exports.iter().any(|f| f.name == pick.function) {
261 bail!(
262 "{} exists for other functions ({}); move it aside or pass --function",
263 crate_dir.display(),
264 m.exports
265 .iter()
266 .map(|f| f.name.as_str())
267 .collect::<Vec<_>>()
268 .join(", ")
269 );
270 }
271 say(
272 &mut steps,
273 format!("kept the crate at {}", crate_dir.display()),
274 );
275 } else {
276 let outcome = crate::bridge::bridge(&crate::bridge::Options {
277 root: &root,
278 unit: &pick.file,
279 kind: None,
280 out: Some(crate_dir.clone()),
281 name: Some(name.clone()),
282 force: false,
283 keep: others(&root, lang, &pick.file, &pick.function)?,
284 lang: Some(lang),
285 batch: pick.batch.iter().cloned().collect(),
286 as_json: Vec::new(),
287 allocator: crate::bridge::Allocator::default(),
288 })?;
289 say(
290 &mut steps,
291 format!(
292 "bridged {} ({:?}) at {}",
293 outcome.exports.join(", "),
294 outcome.kind,
295 outcome.crate_dir.display()
296 ),
297 );
298 }
299 let manifest = Manifest::load(&crate_dir)?;
300
301 let cases = crate_dir.join(crate::harness::CASES);
302 let stale = crate::recording::stale(&crate_dir, &manifest);
303 if !cases.is_file() || stale.is_some() {
304 let captured = match manifest.language {
305 Lang::Ts | Lang::Python => {
306 let c = crate::from_tests::capture(&crate_dir, opts.command)?;
307 let n: usize = c.per_function.values().sum();
308 say(
309 &mut steps,
310 format!("captured {n} real call(s) from the workload"),
311 );
312 (n > 0).then_some(c.inputs)
313 }
314 _ => None,
315 };
316 let recorded = crate::harness::record(&crate::harness::RecordOptions {
317 crate_dir: &crate_dir,
318 count: opts.count,
319 inputs: captured.as_deref(),
320 module: None,
321 resolve_from: None,
322 node_args: &[],
323 })?;
324 say(
325 &mut steps,
326 format!(
327 "recorded {} case(s) ({} throw in the original)",
328 recorded.cases, recorded.errors
329 ),
330 );
331 } else {
332 say(&mut steps, "kept the recorded cases".into());
333 }
334
335 let task_path = crate_dir.join(TASK);
336 let task = task(&crate_dir, &pick, opts.command);
337 std::fs::write(&task_path, &task)
338 .with_context(|| format!("writing {}", task_path.display()))?;
339 let outcome = |stage, steps, cases, matched, failed_checks, next: String| Outcome {
340 stage,
341 pick: pick.clone(),
342 crate_dir: crate_dir.clone(),
343 task: task_path.clone(),
344 cases,
345 matched,
346 speedup: None,
347 failed_checks,
348 steps,
349 next,
350 };
351
352 let mut prompt = task.clone();
353 let rounds = if opts.agent.is_some() {
354 opts.rounds.max(1)
355 } else {
356 0
357 };
358 let mut round = 0;
359 let mut need_port = !crate::gate::ported_check(&crate_dir).passed;
360 let (cases, matched) = loop {
361 if need_port {
362 let Some(agent) = opts.agent.filter(|_| round < rounds) else {
363 say(&mut steps, format!("wrote {}", task_path.display()));
364 return Ok(outcome(
365 Stage::WaitingForPort,
366 steps,
367 None,
368 None,
369 Vec::new(),
370 format!(
371 "Port `{}` in {} as {} says (or pass --agent claude), then run the same \
372 `rust-anything go` again.",
373 pick.function,
374 crate_dir.join("src/port.rs").display(),
375 task_path.display()
376 ),
377 ));
378 };
379 round += 1;
380 say(
381 &mut steps,
382 format!("handing the port to `{agent}` (turn {round} of {rounds})"),
383 );
384 let mut cmd = agent_command(agent)?;
385 cmd.current_dir(&crate_dir).stdout(std::io::stderr());
386 let status = crate::process::status_with_input(
387 &mut cmd,
388 prompt.as_bytes(),
389 crate::process::TESTS,
390 )?;
391 if !status.success() {
392 bail!("`{agent}` failed ({status})");
393 }
394 if !crate::gate::ported_check(&crate_dir).passed {
395 say(&mut steps, "the agent left stubs in src/port.rs".into());
396 prompt = format!(
397 "{task}\n\nsrc/port.rs still has `todo!`, `unimplemented!` or functions that only panic. Finish them.\n"
398 );
399 continue;
400 }
401 }
402
403 let (cases, matched, problems) = check(&crate_dir, &mut steps)?;
404 if problems.is_empty() {
405 break (cases, matched);
406 }
407 if round >= rounds {
408 let stage = if matched < cases {
409 Stage::Mismatch
410 } else {
411 Stage::GateFailed
412 };
413 return Ok(outcome(
414 stage,
415 steps,
416 Some(cases),
417 Some(matched),
418 problems,
419 format!(
420 "Fix the port ({}), then run the same `rust-anything go` again. The unit stays off.",
421 task_path.display()
422 ),
423 ));
424 }
425 prompt = format!(
426 "{task}\n\nYour last port does not pass yet. Fix it:\n\n{}\n",
427 problems.join("\n\n")
428 );
429 need_port = true;
430 };
431
432 let rows = crate::harness::bench(&crate::harness::BenchOptions {
433 crate_dir: &crate_dir,
434 min_ms: 200,
435 resolve_from: None,
436 node_args: &[],
437 })?;
438 let speedup = crate::harness::verdict(&rows, manifest.language).speedup;
439 say(
440 &mut steps,
441 format!(
442 "bench: {} as its callers call it, call included",
443 times(speedup)
444 ),
445 );
446 if speedup < 1.0 {
447 let next = slower_advice(&pick, speedup);
448 let mut out = outcome(
449 Stage::Slower,
450 steps,
451 Some(cases),
452 Some(matched),
453 Vec::new(),
454 next,
455 );
456 out.speedup = Some(speedup);
457 return Ok(out);
458 }
459
460 let mut out = if crate::enable::is_supported(&manifest) {
461 let on = crate::enable::enable(&crate_dir)?;
462 say(
463 &mut steps,
464 format!(
465 "switched on: {} {} in Rust now ({}); `rust-anything disable {}` turns it off",
466 on.functions.join(", "),
467 if on.functions.len() == 1 {
468 "runs"
469 } else {
470 "run"
471 },
472 on.files
473 .iter()
474 .map(|f| f.display().to_string())
475 .collect::<Vec<_>>()
476 .join(", "),
477 crate_dir.display()
478 ),
479 );
480 outcome(
481 Stage::On,
482 steps,
483 Some(cases),
484 Some(matched),
485 Vec::new(),
486 format!(
487 "Measure it: `rust-anything report {}` writes REPORT.md and card.svg.",
488 crate_dir.display()
489 ),
490 )
491 } else {
492 outcome(
493 Stage::Passed,
494 steps,
495 Some(cases),
496 Some(matched),
497 Vec::new(),
498 format!(
499 "Every case matches and gate passes. Switch it in with the shadow module \
500 (`rust-anything shadow {}`), then `rust-anything report` it.",
501 crate_dir.display()
502 ),
503 )
504 };
505 out.speedup = Some(speedup);
506 Ok(out)
507}
508
509fn times(x: f64) -> String {
510 if x >= 1.0 {
511 format!("{x:.1}x faster")
512 } else {
513 format!("{:.1}x slower", 1.0 / x.max(1e-9))
514 }
515}
516
517pub fn slower_advice(pick: &Pick, speedup: f64) -> String {
519 let caller = pick.caller.as_ref().map_or_else(
520 || "its caller".to_string(),
521 |(n, at)| format!("`{n}` ({at})"),
522 );
523 let lost = times(speedup);
524 match &pick.batch {
525 Some(spec) => {
526 let function = spec.split(':').next().unwrap_or(&pick.function);
527 format!(
528 "Every case matches, but called once per item the port is {lost} than the \
529 original, so it stays off. The speed is in the batch: in {caller}, build \
530 `{}Batch` once over the items and call it per query (the crate's type \
531 declarations list its methods), or port {caller} with it. Then `rust-anything enable` and \
532 `rust-anything report`.",
533 crate::codegen_batch::pascal(function)
534 )
535 }
536 None => format!(
537 "Every case matches, but the port is {lost} than the original as {caller} calls it: \
538 each call into Rust costs more than its work. It stays off. Port {caller} with it \
539 (`rust-anything go --function <name>`), or keep it in the original."
540 ),
541 }
542}
543
544fn check(crate_dir: &Path, steps: &mut Vec<String>) -> Result<(usize, usize, Vec<String>)> {
546 if !Manifest::load(crate_dir)?.batches.is_empty()
547 && let Err(e) = crate::bridge::refresh(crate_dir)
548 {
549 say(steps, "refresh failed".into());
550 return Ok((0, 0, vec![format!("`rust-anything refresh` fails:\n{e:#}")]));
551 }
552 if let Err(e) = crate::harness::build(crate_dir) {
553 say(steps, "the build failed".into());
554 return Ok((0, 0, vec![format!("The build fails:\n{e:#}")]));
555 }
556 let diff = crate::harness::diff(&crate::harness::DiffOptions {
557 crate_dir,
558 module: None,
559 ignore_key_order: false,
560 node_args: &[],
561 float_tolerance: None,
562 })?;
563 say(
564 steps,
565 format!("diff: {}/{} cases match", diff.passed, diff.total),
566 );
567 if diff.failed > 0 || !diff.missing.is_empty() || diff.total == 0 {
568 let shown: Vec<String> = diff
569 .mismatches
570 .iter()
571 .take(5)
572 .map(|m| serde_json::to_string(m).unwrap_or_default())
573 .collect();
574 return Ok((
575 diff.total,
576 diff.passed,
577 vec![format!(
578 "{} of {} recorded cases differ{}. First mismatches:\n{}",
579 diff.total - diff.passed,
580 diff.total,
581 if diff.missing.is_empty() {
582 String::new()
583 } else {
584 format!("; missing from Rust: {}", diff.missing.join(", "))
585 },
586 shown.join("\n")
587 )],
588 ));
589 }
590 let gate = crate::gate::gate(crate_dir, &[])?;
591 let failed: Vec<String> = gate
592 .checks
593 .iter()
594 .filter(|c| !c.passed)
595 .map(|c| format!("gate check `{}` fails: {}", c.name, c.detail))
596 .collect();
597 say(
598 steps,
599 if failed.is_empty() {
600 "gate passed".into()
601 } else {
602 format!("gate: {} check(s) fail", failed.len())
603 },
604 );
605 Ok((diff.total, diff.passed, failed))
606}
607
608#[cfg(test)]
609mod tests {
610 use super::*;
611 use crate::profile::Caller;
612
613 fn hot(name: &str, pct: f64, unit: bool, params: &[&str], batch: Option<&str>) -> Hot {
614 Hot {
615 name: name.into(),
616 file: "app.py".into(),
617 line: 1,
618 unit: unit.then(|| "app.py".into()),
619 exported: true,
620 self_ms: 1.0,
621 total_ms: pct,
622 total_pct: pct,
623 calls: None,
624 ns_per_call: None,
625 callers: vec![Caller {
626 name: "main".into(),
627 file: "app.py".into(),
628 line: 9,
629 ms: pct,
630 calls: None,
631 }],
632 advice: "Hot, outside the analyzed units.".into(),
633 portable: unit,
634 params: params.iter().map(|p| p.to_string()).collect(),
635 batch: batch.map(str::to_string),
636 }
637 }
638
639 fn report(hot: Vec<Hot>) -> Report {
640 Report {
641 schema: crate::profile::SCHEMA,
642 language: Lang::Python,
643 command: vec!["python3".into(), "app.py".into()],
644 total_ms: 100.0,
645 repo_pct: 100.0,
646 hot,
647 compiled: Vec::new(),
648 }
649 }
650
651 #[test]
652 fn the_outermost_portable_function_with_arguments_wins() {
653 let r = report(vec![
654 hot("main", 99.0, true, &[], None),
655 hot("load", 95.0, false, &["path"], None),
656 hot("dedupe", 90.0, true, &["names", "limit"], None),
657 hot(
658 "levenshtein",
659 85.0,
660 true,
661 &["a", "b"],
662 Some("levenshtein:b"),
663 ),
664 ]);
665 let p = pick(&r, None).unwrap();
666 assert_eq!((p.function.as_str(), p.batch), ("dedupe", None));
667 assert!(p.why.contains("outermost"), "{}", p.why);
668 }
669
670 #[test]
671 fn a_loop_the_profile_batches_is_bridged_with_its_batch() {
672 let r = report(vec![
673 hot("main", 99.0, true, &[], None),
674 hot(
675 "levenshtein",
676 85.0,
677 true,
678 &["a", "b"],
679 Some("levenshtein:b"),
680 ),
681 ]);
682 let p = pick(&r, None).unwrap();
683 assert_eq!(p.batch.as_deref(), Some("levenshtein:b"));
684 assert!(p.why.contains("--batch levenshtein:b"), "{}", p.why);
685 }
686
687 #[test]
688 fn a_named_function_must_be_portable() {
689 let r = report(vec![hot("load", 95.0, false, &["path"], None)]);
690 assert!(pick(&r, Some("load")).is_err());
691 assert!(pick(&r, Some("missing")).is_err());
692 assert!(pick(&r, None).is_err());
693 }
694
695 #[test]
696 fn agents_run_headless_and_others_as_given() {
697 let args = |c: &Command| -> Vec<String> {
698 c.get_args()
699 .map(|a| a.to_string_lossy().into_owned())
700 .collect()
701 };
702 let claude = agent_command("claude").unwrap();
703 assert_eq!(claude.get_program(), "claude");
704 assert_eq!(
705 args(&claude)[..3],
706 ["-p", "--permission-mode", "acceptEdits"]
707 );
708 assert_eq!(
709 args(&agent_command("codex").unwrap()),
710 ["exec", "--full-auto", "-"]
711 );
712 let own = agent_command("my-agent --fast").unwrap();
713 assert_eq!(
714 (own.get_program(), args(&own)),
715 ("my-agent".as_ref(), vec!["--fast".to_string()])
716 );
717 assert!(agent_command(" ").is_err());
718 }
719
720 #[test]
721 fn a_slower_port_stays_off_and_says_where_the_speed_is() {
722 let r = report(vec![hot(
723 "score",
724 85.0,
725 true,
726 &["q", "text"],
727 Some("score:text"),
728 )]);
729 let batched = slower_advice(&pick(&r, None).unwrap(), 0.13);
730 assert!(batched.contains("7.7x slower"), "{batched}");
731 assert!(batched.contains("`ScoreBatch`"), "{batched}");
732 assert!(batched.contains("`main` (app.py:9)"), "{batched}");
733 let r = report(vec![hot("dedupe", 85.0, true, &["names"], None)]);
734 let plain = slower_advice(&pick(&r, None).unwrap(), 0.5);
735 assert!(
736 plain.contains("2.0x slower") && plain.contains("--function"),
737 "{plain}"
738 );
739 assert_eq!(times(31.42), "31.4x faster");
740 }
741
742 #[test]
743 fn the_other_functions_and_classes_of_the_file_stay_in_the_original() {
744 let root = std::env::temp_dir().join(format!("ra-go-others-{}", std::process::id()));
745 let _ = std::fs::remove_dir_all(&root);
746 std::fs::create_dir_all(&root).unwrap();
747 std::fs::write(
748 root.join("lib.py"),
749 "def hot(xs):\n return xs\n\n\ndef cold(x):\n return x\n\n\nclass Table:\n def __init__(self, n):\n self.n = n\n\n def render(self):\n return str(self.n)\n",
750 )
751 .unwrap();
752 let kept = others(&root, Lang::Python, "lib.py", "hot").unwrap();
753 std::fs::remove_dir_all(&root).unwrap();
754 let names: Vec<&str> = kept.iter().map(|k| k.split(':').next().unwrap()).collect();
755 assert_eq!(names, ["cold", "Table"], "{kept:?}");
756 }
757
758 #[test]
759 fn crate_names_follow_the_function() {
760 assert_eq!(crate_name("fuzzyScore"), "fuzzy-score-rs");
761 assert_eq!(crate_name("dedupe_names"), "dedupe-names-rs");
762 }
763}