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