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 crosses = |h: &&Hot| {
88 h.unit.is_some() && h.portable && h.js_only.is_none() && h.exported && !h.params.is_empty()
89 };
90 let eligible = |h: &&Hot| crosses(h) && !h.mostly_waits();
91 if function.is_none()
92 && report.child_pct >= 50.0
93 && let Some(summary) = report.child_summary()
94 {
95 let anyway = if report.hot.iter().any(|h| eligible(&h)) {
96 " To port a function anyway, name it with `--function`."
97 } else {
98 ""
99 };
100 bail!("{summary} {}{anyway}", crate::profile::CHILD_ADVICE);
101 }
102 let hot = match function {
103 Some(name) => report
104 .hot
105 .iter()
106 .filter(|h| h.name == name)
107 .find(eligible)
108 .or_else(|| report.hot.iter().find(|h| h.name == name))
109 .with_context(|| {
110 format!("`{name}` is not among the hot functions of this run (see `rust-anything profile`)")
111 })?,
112 None => report.hot.iter().find(eligible).with_context(|| {
113 if report.hot.iter().any(|h| crosses(&h) && h.mostly_waits()) {
114 let summary = report
115 .child_summary()
116 .map_or_else(String::new, |s| format!(" {s}"));
117 return format!(
118 "no hot function to port: the ones that could cross the bridge mostly wait on \
119 child processes.{summary} {}",
120 crate::profile::CHILD_ADVICE
121 );
122 }
123 format!(
124 "no hot function to port: none of the {} hot functions is exported by a portable \
125 unit, can cross the bridge and takes arguments. `rust-anything profile` shows why.",
126 report.hot.len()
127 )
128 })?,
129 };
130 if !eligible(&hot) {
131 if let Some(reason) = &hot.js_only {
132 bail!(
133 "`{}` cannot be bridged: `bridge` keeps it in {}: {reason}",
134 hot.name,
135 report.language.name()
136 );
137 }
138 if hot.mostly_waits() {
139 bail!(
140 "`{}` spends {:.0}% of its time waiting on child processes. {}",
141 hot.name,
142 hot.child_pct.unwrap_or_default(),
143 crate::profile::CHILD_ADVICE
144 );
145 }
146 bail!("`{}` cannot be bridged: {}", hot.name, hot.advice);
147 }
148 let why = match &hot.batch {
149 Some(spec) => format!(
150 "{:.0}% of the run; called in a loop by `{}`, so it is bridged with `--batch {spec}`",
151 hot.total_pct,
152 hot.callers
153 .first()
154 .map_or("its caller", |c| c.name.as_str())
155 ),
156 None => format!(
157 "{:.0}% of the run, the outermost portable function",
158 hot.total_pct
159 ),
160 };
161 Ok(Pick {
162 function: hot.name.clone(),
163 file: hot.file.clone(),
164 line: hot.line,
165 total_pct: hot.total_pct,
166 batch: hot.batch.clone(),
167 caller: hot
168 .callers
169 .first()
170 .map(|c| (c.name.clone(), format!("{}:{}", c.file, c.line))),
171 why,
172 })
173}
174
175pub fn crate_name(function: &str) -> String {
176 format!(
177 "{}-rs",
178 crate::bridge::snake_case(function).replace('_', "-")
179 )
180}
181
182fn others(root: &Path, lang: Lang, file: &str, function: &str) -> Result<Vec<String>> {
186 let text =
187 std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
188 crate::profile::use_project_types(root, lang);
189 let classes = if lang == Lang::Ts {
190 crate::ts::exports::exported_classes(file, &text)
191 } else {
192 crate::lang::exports(lang, file, &text).1
193 };
194 Ok(crate::profile::exports_judged(root, lang, file, &text)
195 .into_iter()
196 .filter(|(_, reason)| reason.is_none())
197 .map(|(f, _)| f.name)
198 .chain(classes.into_iter().map(|c| c.name))
199 .filter(|n| n != function)
200 .map(|n| format!("{n}: not hot in the profiled run; `go` ports one function"))
201 .collect())
202}
203
204pub fn task(crate_dir: &Path, pick: &Pick, command: &[String]) -> String {
205 let batch = pick.batch.as_ref().map_or_else(String::new, |spec| {
206 let function = spec.split(':').next().unwrap_or(&pick.function);
207 format!(
208 "\nThe crate also has a batch class for `{spec}`, which runs `{function}` over many \
209 items kept in Rust. A `{}Index` struct in `src/port.rs` can prepare the items once \
210 (see the Hot paths section of rust-anything's docs/how-it-works.md); `rust-anything go` runs `rust-anything \
211 refresh` before building, so the batch class uses it.\n",
212 crate::codegen_batch::pascal(function)
213 )
214 });
215 format!(
216 "# Port `{function}` to Rust\n\n\
217 `{function}` (`{file}:{line}`) took {pct:.0}% of `{command}`. Port it, and only it, in \
218 `src/port.rs` of this crate ({dir}). The bindings, the recorded cases and \
219 `rust-anything.json` are generated: leave them as they are.\n{batch}\n\
220 ## Rules\n\n\
221 - Match the original exactly on every recorded case in `cases.jsonl`: values, errors and \
222 their messages, edge cases (empty input, Unicode, large numbers). Read the original \
223 first; port its behavior, not a cleaner idea of it.\n\
224 - No `unwrap`, `expect` or `panic!` outside tests; no `unsafe` without a `// SAFETY:` comment.\n\
225 - Keep helpers private; only the unit's functions are `pub`.\n\n\
226 ## Loop\n\n\
227 ```sh\n\
228 rust-anything build .\n\
229 rust-anything diff . # every recorded case must match\n\
230 rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n\
231 ```\n\n\
232 Done when `diff` matches every case and `gate` passes. Do not switch the port on; \
233 `rust-anything go` does that once both pass.\n",
234 function = pick.function,
235 file = pick.file,
236 line = pick.line,
237 pct = pick.total_pct,
238 command = command.join(" "),
239 dir = crate_dir.display(),
240 )
241}
242
243pub fn agent_command(agent: &str) -> Result<Command> {
246 let words: Vec<&str> = agent.split_whitespace().collect();
247 let (program, args) = words.split_first().context("--agent is empty")?;
248 let mut cmd = Command::new(program);
249 match *program {
250 "claude" if args.is_empty() => {
251 cmd.args([
252 "-p",
253 "--permission-mode",
254 "acceptEdits",
255 "--allowedTools",
256 "Bash(cargo:*)",
257 "Bash(rust-anything:*)",
258 ]);
259 }
260 "codex" if args.is_empty() => {
261 cmd.args(["exec", "--full-auto", "-"]);
262 }
263 _ => {
264 cmd.args(args);
265 }
266 }
267 Ok(cmd)
268}
269
270fn say(steps: &mut Vec<String>, line: String) {
271 eprintln!("go: {line}");
272 steps.push(line);
273}
274
275pub fn go(opts: &Options) -> Result<Outcome> {
276 let root = opts
277 .root
278 .canonical()
279 .with_context(|| format!("resolving {}", opts.root.display()))?;
280 let lang = opts.lang.unwrap_or_else(|| Lang::detect(&root));
281 let mut steps = Vec::new();
282
283 let report = crate::profile::profile(&root, opts.command, Some(lang))?;
284 let pick = pick(&report, opts.function)?;
285 say(
286 &mut steps,
287 format!(
288 "profiled `{}` ({:.0} ms): porting `{}` ({}:{}), {}",
289 opts.command.join(" "),
290 report.total_ms,
291 pick.function,
292 pick.file,
293 pick.line,
294 pick.why
295 ),
296 );
297
298 let name = crate_name(&pick.function);
299 let crate_dir = root.join("rust").join(&name);
300 if crate_dir.join("rust-anything.json").is_file() {
301 let m = Manifest::load(&crate_dir)?;
302 if !m.exports.iter().any(|f| f.name == pick.function) {
303 bail!(
304 "{} exists for other functions ({}); move it aside or pass --function",
305 crate_dir.display(),
306 m.exports
307 .iter()
308 .map(|f| f.name.as_str())
309 .collect::<Vec<_>>()
310 .join(", ")
311 );
312 }
313 say(
314 &mut steps,
315 format!("kept the crate at {}", crate_dir.display()),
316 );
317 } else {
318 let outcome = crate::bridge::bridge(&crate::bridge::Options {
319 root: &root,
320 unit: &pick.file,
321 kind: None,
322 out: Some(crate_dir.clone()),
323 name: Some(name.clone()),
324 force: false,
325 keep: others(&root, lang, &pick.file, &pick.function)?,
326 lang: Some(lang),
327 batch: pick.batch.iter().cloned().collect(),
328 as_json: Vec::new(),
329 allocator: crate::bridge::Allocator::default(),
330 })?;
331 say(
332 &mut steps,
333 format!(
334 "bridged {} ({:?}) at {}",
335 outcome.exports.join(", "),
336 outcome.kind,
337 outcome.crate_dir.display()
338 ),
339 );
340 }
341 let manifest = Manifest::load(&crate_dir)?;
342
343 let cases = crate_dir.join(crate::harness::CASES);
344 let stale = crate::recording::stale(&crate_dir, &manifest);
345 if !cases.is_file() || stale.is_some() {
346 let captured = match manifest.language {
347 Lang::Ts | Lang::Python => {
348 let c = crate::from_tests::capture(&crate_dir, opts.command)?;
349 let n: usize = c.per_function.values().sum();
350 say(
351 &mut steps,
352 format!("captured {n} real call(s) from the workload"),
353 );
354 (n > 0).then_some(c.inputs)
355 }
356 _ => None,
357 };
358 let recorded = crate::harness::record(&crate::harness::RecordOptions {
359 crate_dir: &crate_dir,
360 count: opts.count,
361 inputs: captured.as_deref(),
362 module: None,
363 resolve_from: None,
364 node_args: &[],
365 })?;
366 say(
367 &mut steps,
368 format!(
369 "recorded {} case(s) ({} throw in the original)",
370 recorded.cases, recorded.errors
371 ),
372 );
373 } else {
374 say(&mut steps, "kept the recorded cases".into());
375 }
376
377 let task_path = crate_dir.join(TASK);
378 let task = task(&crate_dir, &pick, opts.command);
379 std::fs::write(&task_path, &task)
380 .with_context(|| format!("writing {}", task_path.display()))?;
381 let outcome = |stage, steps, cases, matched, failed_checks, next: String| Outcome {
382 stage,
383 pick: pick.clone(),
384 crate_dir: crate_dir.clone(),
385 task: task_path.clone(),
386 cases,
387 matched,
388 speedup: None,
389 failed_checks,
390 steps,
391 next,
392 };
393
394 let mut prompt = task.clone();
395 let rounds = if opts.agent.is_some() {
396 opts.rounds.max(1)
397 } else {
398 0
399 };
400 let mut round = 0;
401 let mut need_port = !crate::gate::ported_check(&crate_dir).passed;
402 let (cases, matched) = loop {
403 if need_port {
404 let Some(agent) = opts.agent.filter(|_| round < rounds) else {
405 say(&mut steps, format!("wrote {}", task_path.display()));
406 return Ok(outcome(
407 Stage::WaitingForPort,
408 steps,
409 None,
410 None,
411 Vec::new(),
412 format!(
413 "Port `{}` in {} as {} says (or pass --agent claude), then run the same \
414 `rust-anything go` again.",
415 pick.function,
416 crate_dir.join("src/port.rs").display(),
417 task_path.display()
418 ),
419 ));
420 };
421 round += 1;
422 say(
423 &mut steps,
424 format!("handing the port to `{agent}` (turn {round} of {rounds})"),
425 );
426 let mut cmd = agent_command(agent)?;
427 cmd.current_dir(&crate_dir).stdout(std::io::stderr());
428 let status = crate::process::status_with_input(
429 &mut cmd,
430 prompt.as_bytes(),
431 crate::process::TESTS,
432 )?;
433 if !status.success() {
434 bail!("`{agent}` failed ({status})");
435 }
436 if !crate::gate::ported_check(&crate_dir).passed {
437 say(&mut steps, "the agent left stubs in src/port.rs".into());
438 prompt = format!(
439 "{task}\n\nsrc/port.rs still has `todo!`, `unimplemented!` or functions that only panic. Finish them.\n"
440 );
441 continue;
442 }
443 }
444
445 let (cases, matched, problems) = check(&crate_dir, &mut steps)?;
446 if problems.is_empty() {
447 break (cases, matched);
448 }
449 if round >= rounds {
450 let stage = if matched < cases {
451 Stage::Mismatch
452 } else {
453 Stage::GateFailed
454 };
455 return Ok(outcome(
456 stage,
457 steps,
458 Some(cases),
459 Some(matched),
460 problems,
461 format!(
462 "Fix the port ({}), then run the same `rust-anything go` again. The unit stays off.",
463 task_path.display()
464 ),
465 ));
466 }
467 prompt = format!(
468 "{task}\n\nYour last port does not pass yet. Fix it:\n\n{}\n",
469 problems.join("\n\n")
470 );
471 need_port = true;
472 };
473
474 let rows = crate::harness::bench(&crate::harness::BenchOptions {
475 crate_dir: &crate_dir,
476 min_ms: 200,
477 resolve_from: None,
478 node_args: &[],
479 })?;
480 let speedup = crate::harness::verdict(&rows, manifest.language).speedup;
481 say(
482 &mut steps,
483 format!(
484 "bench: {} as its callers call it, call included",
485 times(speedup)
486 ),
487 );
488 if speedup < 1.0 {
489 let next = slower_advice(&pick, speedup);
490 let mut out = outcome(
491 Stage::Slower,
492 steps,
493 Some(cases),
494 Some(matched),
495 Vec::new(),
496 next,
497 );
498 out.speedup = Some(speedup);
499 return Ok(out);
500 }
501
502 let mut out = if crate::enable::is_supported(&manifest) {
503 let on = crate::enable::enable(&crate_dir)?;
504 say(
505 &mut steps,
506 format!(
507 "switched on: {} {} in Rust now ({}); `rust-anything disable {}` turns it off",
508 on.functions.join(", "),
509 if on.functions.len() == 1 {
510 "runs"
511 } else {
512 "run"
513 },
514 on.files
515 .iter()
516 .map(|f| f.display().to_string())
517 .collect::<Vec<_>>()
518 .join(", "),
519 crate_dir.display()
520 ),
521 );
522 outcome(
523 Stage::On,
524 steps,
525 Some(cases),
526 Some(matched),
527 Vec::new(),
528 format!(
529 "Measure it: `rust-anything report {}` writes REPORT.md and card.svg.",
530 crate_dir.display()
531 ),
532 )
533 } else {
534 outcome(
535 Stage::Passed,
536 steps,
537 Some(cases),
538 Some(matched),
539 Vec::new(),
540 format!(
541 "Every case matches and gate passes. Switch it in with the shadow module \
542 (`rust-anything shadow {}`), then `rust-anything report` it.",
543 crate_dir.display()
544 ),
545 )
546 };
547 out.speedup = Some(speedup);
548 Ok(out)
549}
550
551fn times(x: f64) -> String {
552 if x >= 1.0 {
553 if x < 1.05 {
555 format!("{x:.2}x faster")
556 } else {
557 format!("{x:.1}x faster")
558 }
559 } else {
560 let slower = 1.0 / x.max(1e-9);
561 if slower < 1.05 {
564 format!("{slower:.2}x slower")
565 } else {
566 format!("{slower:.1}x slower")
567 }
568 }
569}
570
571pub fn slower_advice(pick: &Pick, speedup: f64) -> String {
573 let caller = pick.caller.as_ref().map_or_else(
574 || "its caller".to_string(),
575 |(n, at)| format!("`{n}` ({at})"),
576 );
577 let lost = times(speedup);
578 match &pick.batch {
579 Some(spec) => {
580 let function = spec.split(':').next().unwrap_or(&pick.function);
581 format!(
582 "Every case matches, but called once per item the port is {lost} than the \
583 original, so it stays off. The speed is in the batch: in {caller}, build \
584 `{}Batch` once over the items and call it per query (the crate's type \
585 declarations list its methods), or port {caller} with it. Then `rust-anything enable` and \
586 `rust-anything report`.",
587 crate::codegen_batch::pascal(function)
588 )
589 }
590 None => format!(
591 "Every case matches, but the port is {lost} than the original as {caller} calls it: \
592 each call into Rust costs more than its work. It stays off. Port {caller} with it \
593 (`rust-anything go --function <name>`), or keep it in the original."
594 ),
595 }
596}
597
598fn check(crate_dir: &Path, steps: &mut Vec<String>) -> Result<(usize, usize, Vec<String>)> {
600 if !Manifest::load(crate_dir)?.batches.is_empty()
601 && let Err(e) = crate::bridge::refresh(crate_dir)
602 {
603 say(steps, "refresh failed".into());
604 return Ok((0, 0, vec![format!("`rust-anything refresh` fails:\n{e:#}")]));
605 }
606 if let Err(e) = crate::harness::build(crate_dir) {
607 say(steps, "the build failed".into());
608 return Ok((0, 0, vec![format!("The build fails:\n{e:#}")]));
609 }
610 let diff = crate::harness::diff(&crate::harness::DiffOptions {
611 crate_dir,
612 module: None,
613 ignore_key_order: false,
614 node_args: &[],
615 float_tolerance: None,
616 })?;
617 say(
618 steps,
619 format!("diff: {}/{} cases match", diff.passed, diff.total),
620 );
621 if diff.failed > 0 || !diff.missing.is_empty() || diff.total == 0 {
622 let shown: Vec<String> = diff
623 .mismatches
624 .iter()
625 .take(5)
626 .map(|m| serde_json::to_string(m).unwrap_or_default())
627 .collect();
628 return Ok((
629 diff.total,
630 diff.passed,
631 vec![format!(
632 "{} of {} recorded cases differ{}. First mismatches:\n{}",
633 diff.total - diff.passed,
634 diff.total,
635 if diff.missing.is_empty() {
636 String::new()
637 } else {
638 format!("; missing from Rust: {}", diff.missing.join(", "))
639 },
640 shown.join("\n")
641 )],
642 ));
643 }
644 let gate = crate::gate::gate(crate_dir, &[])?;
645 let failed: Vec<String> = gate
646 .checks
647 .iter()
648 .filter(|c| !c.passed)
649 .map(|c| format!("gate check `{}` fails: {}", c.name, c.detail))
650 .collect();
651 say(
652 steps,
653 if failed.is_empty() {
654 "gate passed".into()
655 } else {
656 format!("gate: {} check(s) fail", failed.len())
657 },
658 );
659 Ok((diff.total, diff.passed, failed))
660}
661
662#[cfg(test)]
663mod tests {
664 use super::*;
665 use crate::profile::Caller;
666
667 fn hot(name: &str, pct: f64, unit: bool, params: &[&str], batch: Option<&str>) -> Hot {
668 Hot {
669 name: name.into(),
670 file: "app.py".into(),
671 line: 1,
672 unit: unit.then(|| "app.py".into()),
673 exported: true,
674 self_ms: 1.0,
675 total_ms: pct,
676 total_pct: pct,
677 calls: None,
678 ns_per_call: None,
679 callers: vec![Caller {
680 name: "main".into(),
681 file: "app.py".into(),
682 line: 9,
683 ms: pct,
684 calls: None,
685 }],
686 advice: "Hot, outside the analyzed units.".into(),
687 portable: unit,
688 js_only: None,
689 params: params.iter().map(|p| p.to_string()).collect(),
690 batch: batch.map(str::to_string),
691 child_pct: None,
692 }
693 }
694
695 fn report(hot: Vec<Hot>) -> Report {
696 Report {
697 schema: crate::profile::SCHEMA,
698 language: Lang::Python,
699 command: vec!["python3".into(), "app.py".into()],
700 total_ms: 100.0,
701 repo_pct: 100.0,
702 hot,
703 compiled: Vec::new(),
704 child_pct: 0.0,
705 child_processes: Vec::new(),
706 }
707 }
708
709 #[test]
710 fn the_outermost_portable_function_with_arguments_wins() {
711 let r = report(vec![
712 hot("main", 99.0, true, &[], None),
713 hot("load", 95.0, false, &["path"], None),
714 hot("dedupe", 90.0, true, &["names", "limit"], None),
715 hot(
716 "levenshtein",
717 85.0,
718 true,
719 &["a", "b"],
720 Some("levenshtein:b"),
721 ),
722 ]);
723 let p = pick(&r, None).unwrap();
724 assert_eq!((p.function.as_str(), p.batch), ("dedupe", None));
725 assert!(p.why.contains("outermost"), "{}", p.why);
726 }
727
728 #[test]
729 fn a_loop_the_profile_batches_is_bridged_with_its_batch() {
730 let r = report(vec![
731 hot("main", 99.0, true, &[], None),
732 hot(
733 "levenshtein",
734 85.0,
735 true,
736 &["a", "b"],
737 Some("levenshtein:b"),
738 ),
739 ]);
740 let p = pick(&r, None).unwrap();
741 assert_eq!(p.batch.as_deref(), Some("levenshtein:b"));
742 assert!(p.why.contains("--batch levenshtein:b"), "{}", p.why);
743 }
744
745 #[test]
746 fn a_named_function_must_be_portable() {
747 let r = report(vec![hot("load", 95.0, false, &["path"], None)]);
748 assert!(pick(&r, Some("load")).is_err());
749 assert!(pick(&r, Some("missing")).is_err());
750 assert!(pick(&r, None).is_err());
751 }
752
753 #[test]
754 fn a_function_that_mostly_waits_on_child_processes_is_passed_over() {
755 let waits = || {
756 let mut h = hot("run_all", 40.0, true, &["n"], None);
757 h.child_pct = Some(95.0);
758 h
759 };
760 let mut r = report(vec![waits(), hot("main", 99.0, true, &[], None)]);
761 r.child_pct = 38.0;
762 r.child_processes = vec![crate::profile::ChildProcess {
763 command: Some("git".into()),
764 file: "app.py".into(),
765 line: 4,
766 function: "run_all".into(),
767 ms: 38.0,
768 share: 38.0,
769 }];
770 let none = pick(&r, None).unwrap_err().to_string();
771 assert!(
772 none.starts_with("no hot function to port: the ones that could cross the bridge mostly wait on child processes. 38% of the run waits on child processes (`git` from `app.py:4`)."),
773 "{none}"
774 );
775 r.hot.push(hot("parse", 30.0, true, &["text"], None));
776 assert_eq!(pick(&r, None).unwrap().function, "parse");
777 }
778
779 #[test]
780 fn a_named_function_bridge_keeps_says_so_even_when_it_waits() {
781 let mut h = hot("each", 80.0, true, &["items"], None);
782 h.js_only = Some("takes or returns a function".into());
783 h.child_pct = Some(70.0);
784 let named = pick(&report(vec![h]), Some("each"))
785 .unwrap_err()
786 .to_string();
787 assert!(
788 named.contains("cannot be bridged") && named.contains("takes or returns a function"),
789 "{named}"
790 );
791 }
792
793 #[test]
794 fn a_named_function_bridge_keeps_says_why_and_yields_to_one_that_can_cross() {
795 let kept = || {
796 let mut h = hot("calc", 60.0, true, &["xs", "cb"], None);
797 h.js_only = Some("takes or returns a function".into());
798 h
799 };
800 let only = pick(&report(vec![kept()]), Some("calc"))
801 .unwrap_err()
802 .to_string();
803 assert!(
804 only.contains("`bridge` keeps it in Python: takes or returns a function"),
805 "{only}"
806 );
807 let r = report(vec![kept(), hot("calc", 20.0, true, &["n"], None)]);
808 assert_eq!(pick(&r, Some("calc")).unwrap().total_pct, 20.0);
809 }
810
811 #[test]
812 fn functions_bridge_keeps_are_left_to_bridge_for_their_reason() {
813 let root =
814 std::env::temp_dir().join(format!("rust-anything-go-others-{}", std::process::id()));
815 let _ = std::fs::remove_dir_all(&root);
816 std::fs::create_dir_all(&root).unwrap();
817 std::fs::write(
818 root.join("plug.js"),
819 "export function each(items, visit) { for (const it of items) visit(it); }\n\
820 export function half(n) { return n / 2; }\n\
821 export function third(n) { return n / 3; }\n",
822 )
823 .unwrap();
824 std::fs::write(
825 root.join("plug.d.ts"),
826 "export declare function each<T>(items: T[], visit: (item: T) => void): void;\n",
827 )
828 .unwrap();
829 let keep = others(&root, Lang::Ts, "plug.js", "half").unwrap();
830 std::fs::remove_dir_all(&root).unwrap();
831 assert_eq!(
832 keep,
833 ["third: not hot in the profiled run; `go` ports one function"]
834 );
835 }
836
837 #[test]
838 fn agents_run_headless_and_others_as_given() {
839 let args = |c: &Command| -> Vec<String> {
840 c.get_args()
841 .map(|a| a.to_string_lossy().into_owned())
842 .collect()
843 };
844 let claude = agent_command("claude").unwrap();
845 assert_eq!(claude.get_program(), "claude");
846 assert_eq!(
847 args(&claude)[..3],
848 ["-p", "--permission-mode", "acceptEdits"]
849 );
850 assert_eq!(
851 args(&agent_command("codex").unwrap()),
852 ["exec", "--full-auto", "-"]
853 );
854 let own = agent_command("my-agent --fast").unwrap();
855 assert_eq!(
856 (own.get_program(), args(&own)),
857 ("my-agent".as_ref(), vec!["--fast".to_string()])
858 );
859 assert!(agent_command(" ").is_err());
860 }
861
862 #[test]
863 fn a_slower_port_stays_off_and_says_where_the_speed_is() {
864 let r = report(vec![hot(
865 "score",
866 85.0,
867 true,
868 &["q", "text"],
869 Some("score:text"),
870 )]);
871 let batched = slower_advice(&pick(&r, None).unwrap(), 0.13);
872 assert!(batched.contains("7.7x slower"), "{batched}");
873 assert!(batched.contains("`ScoreBatch`"), "{batched}");
874 assert!(batched.contains("`main` (app.py:9)"), "{batched}");
875 let r = report(vec![hot("dedupe", 85.0, true, &["names"], None)]);
876 let plain = slower_advice(&pick(&r, None).unwrap(), 0.5);
877 assert!(
878 plain.contains("2.0x slower") && plain.contains("--function"),
879 "{plain}"
880 );
881 assert_eq!(times(31.42), "31.4x faster");
882 assert_eq!(times(1.04), "1.04x faster");
884 assert_eq!(times(1.2), "1.2x faster");
885 assert_eq!(times(0.97), "1.03x slower");
887 assert_eq!(times(0.96), "1.04x slower");
888 assert_eq!(times(0.9), "1.1x slower");
889 assert_eq!(times(0.5), "2.0x slower");
890 }
891
892 #[test]
893 fn the_other_functions_and_classes_of_the_file_stay_in_the_original() {
894 let root = std::env::temp_dir().join(format!("ra-go-others-{}", std::process::id()));
895 let _ = std::fs::remove_dir_all(&root);
896 std::fs::create_dir_all(&root).unwrap();
897 std::fs::write(
898 root.join("lib.py"),
899 "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",
900 )
901 .unwrap();
902 let kept = others(&root, Lang::Python, "lib.py", "hot").unwrap();
903 std::fs::remove_dir_all(&root).unwrap();
904 let names: Vec<&str> = kept.iter().map(|k| k.split(':').next().unwrap()).collect();
905 assert_eq!(names, ["cold", "Table"], "{kept:?}");
906 }
907
908 #[test]
909 fn crate_names_follow_the_function() {
910 assert_eq!(crate_name("fuzzyScore"), "fuzzy-score-rs");
911 assert_eq!(crate_name("dedupe_names"), "dedupe-names-rs");
912 }
913}