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 format!("{x:.1}x faster")
554 } else {
555 format!("{:.1}x slower", 1.0 / x.max(1e-9))
556 }
557}
558
559pub fn slower_advice(pick: &Pick, speedup: f64) -> String {
561 let caller = pick.caller.as_ref().map_or_else(
562 || "its caller".to_string(),
563 |(n, at)| format!("`{n}` ({at})"),
564 );
565 let lost = times(speedup);
566 match &pick.batch {
567 Some(spec) => {
568 let function = spec.split(':').next().unwrap_or(&pick.function);
569 format!(
570 "Every case matches, but called once per item the port is {lost} than the \
571 original, so it stays off. The speed is in the batch: in {caller}, build \
572 `{}Batch` once over the items and call it per query (the crate's type \
573 declarations list its methods), or port {caller} with it. Then `rust-anything enable` and \
574 `rust-anything report`.",
575 crate::codegen_batch::pascal(function)
576 )
577 }
578 None => format!(
579 "Every case matches, but the port is {lost} than the original as {caller} calls it: \
580 each call into Rust costs more than its work. It stays off. Port {caller} with it \
581 (`rust-anything go --function <name>`), or keep it in the original."
582 ),
583 }
584}
585
586fn check(crate_dir: &Path, steps: &mut Vec<String>) -> Result<(usize, usize, Vec<String>)> {
588 if !Manifest::load(crate_dir)?.batches.is_empty()
589 && let Err(e) = crate::bridge::refresh(crate_dir)
590 {
591 say(steps, "refresh failed".into());
592 return Ok((0, 0, vec![format!("`rust-anything refresh` fails:\n{e:#}")]));
593 }
594 if let Err(e) = crate::harness::build(crate_dir) {
595 say(steps, "the build failed".into());
596 return Ok((0, 0, vec![format!("The build fails:\n{e:#}")]));
597 }
598 let diff = crate::harness::diff(&crate::harness::DiffOptions {
599 crate_dir,
600 module: None,
601 ignore_key_order: false,
602 node_args: &[],
603 float_tolerance: None,
604 })?;
605 say(
606 steps,
607 format!("diff: {}/{} cases match", diff.passed, diff.total),
608 );
609 if diff.failed > 0 || !diff.missing.is_empty() || diff.total == 0 {
610 let shown: Vec<String> = diff
611 .mismatches
612 .iter()
613 .take(5)
614 .map(|m| serde_json::to_string(m).unwrap_or_default())
615 .collect();
616 return Ok((
617 diff.total,
618 diff.passed,
619 vec![format!(
620 "{} of {} recorded cases differ{}. First mismatches:\n{}",
621 diff.total - diff.passed,
622 diff.total,
623 if diff.missing.is_empty() {
624 String::new()
625 } else {
626 format!("; missing from Rust: {}", diff.missing.join(", "))
627 },
628 shown.join("\n")
629 )],
630 ));
631 }
632 let gate = crate::gate::gate(crate_dir, &[])?;
633 let failed: Vec<String> = gate
634 .checks
635 .iter()
636 .filter(|c| !c.passed)
637 .map(|c| format!("gate check `{}` fails: {}", c.name, c.detail))
638 .collect();
639 say(
640 steps,
641 if failed.is_empty() {
642 "gate passed".into()
643 } else {
644 format!("gate: {} check(s) fail", failed.len())
645 },
646 );
647 Ok((diff.total, diff.passed, failed))
648}
649
650#[cfg(test)]
651mod tests {
652 use super::*;
653 use crate::profile::Caller;
654
655 fn hot(name: &str, pct: f64, unit: bool, params: &[&str], batch: Option<&str>) -> Hot {
656 Hot {
657 name: name.into(),
658 file: "app.py".into(),
659 line: 1,
660 unit: unit.then(|| "app.py".into()),
661 exported: true,
662 self_ms: 1.0,
663 total_ms: pct,
664 total_pct: pct,
665 calls: None,
666 ns_per_call: None,
667 callers: vec![Caller {
668 name: "main".into(),
669 file: "app.py".into(),
670 line: 9,
671 ms: pct,
672 calls: None,
673 }],
674 advice: "Hot, outside the analyzed units.".into(),
675 portable: unit,
676 js_only: None,
677 params: params.iter().map(|p| p.to_string()).collect(),
678 batch: batch.map(str::to_string),
679 child_pct: None,
680 }
681 }
682
683 fn report(hot: Vec<Hot>) -> Report {
684 Report {
685 schema: crate::profile::SCHEMA,
686 language: Lang::Python,
687 command: vec!["python3".into(), "app.py".into()],
688 total_ms: 100.0,
689 repo_pct: 100.0,
690 hot,
691 compiled: Vec::new(),
692 child_pct: 0.0,
693 child_processes: Vec::new(),
694 }
695 }
696
697 #[test]
698 fn the_outermost_portable_function_with_arguments_wins() {
699 let r = report(vec![
700 hot("main", 99.0, true, &[], None),
701 hot("load", 95.0, false, &["path"], None),
702 hot("dedupe", 90.0, true, &["names", "limit"], None),
703 hot(
704 "levenshtein",
705 85.0,
706 true,
707 &["a", "b"],
708 Some("levenshtein:b"),
709 ),
710 ]);
711 let p = pick(&r, None).unwrap();
712 assert_eq!((p.function.as_str(), p.batch), ("dedupe", None));
713 assert!(p.why.contains("outermost"), "{}", p.why);
714 }
715
716 #[test]
717 fn a_loop_the_profile_batches_is_bridged_with_its_batch() {
718 let r = report(vec![
719 hot("main", 99.0, true, &[], None),
720 hot(
721 "levenshtein",
722 85.0,
723 true,
724 &["a", "b"],
725 Some("levenshtein:b"),
726 ),
727 ]);
728 let p = pick(&r, None).unwrap();
729 assert_eq!(p.batch.as_deref(), Some("levenshtein:b"));
730 assert!(p.why.contains("--batch levenshtein:b"), "{}", p.why);
731 }
732
733 #[test]
734 fn a_named_function_must_be_portable() {
735 let r = report(vec![hot("load", 95.0, false, &["path"], None)]);
736 assert!(pick(&r, Some("load")).is_err());
737 assert!(pick(&r, Some("missing")).is_err());
738 assert!(pick(&r, None).is_err());
739 }
740
741 #[test]
742 fn a_function_that_mostly_waits_on_child_processes_is_passed_over() {
743 let waits = || {
744 let mut h = hot("run_all", 40.0, true, &["n"], None);
745 h.child_pct = Some(95.0);
746 h
747 };
748 let mut r = report(vec![waits(), hot("main", 99.0, true, &[], None)]);
749 r.child_pct = 38.0;
750 r.child_processes = vec![crate::profile::ChildProcess {
751 command: Some("git".into()),
752 file: "app.py".into(),
753 line: 4,
754 function: "run_all".into(),
755 ms: 38.0,
756 share: 38.0,
757 }];
758 let none = pick(&r, None).unwrap_err().to_string();
759 assert!(
760 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`)."),
761 "{none}"
762 );
763 r.hot.push(hot("parse", 30.0, true, &["text"], None));
764 assert_eq!(pick(&r, None).unwrap().function, "parse");
765 }
766
767 #[test]
768 fn a_named_function_bridge_keeps_says_so_even_when_it_waits() {
769 let mut h = hot("each", 80.0, true, &["items"], None);
770 h.js_only = Some("takes or returns a function".into());
771 h.child_pct = Some(70.0);
772 let named = pick(&report(vec![h]), Some("each"))
773 .unwrap_err()
774 .to_string();
775 assert!(
776 named.contains("cannot be bridged") && named.contains("takes or returns a function"),
777 "{named}"
778 );
779 }
780
781 #[test]
782 fn a_named_function_bridge_keeps_says_why_and_yields_to_one_that_can_cross() {
783 let kept = || {
784 let mut h = hot("calc", 60.0, true, &["xs", "cb"], None);
785 h.js_only = Some("takes or returns a function".into());
786 h
787 };
788 let only = pick(&report(vec![kept()]), Some("calc"))
789 .unwrap_err()
790 .to_string();
791 assert!(
792 only.contains("`bridge` keeps it in Python: takes or returns a function"),
793 "{only}"
794 );
795 let r = report(vec![kept(), hot("calc", 20.0, true, &["n"], None)]);
796 assert_eq!(pick(&r, Some("calc")).unwrap().total_pct, 20.0);
797 }
798
799 #[test]
800 fn functions_bridge_keeps_are_left_to_bridge_for_their_reason() {
801 let root =
802 std::env::temp_dir().join(format!("rust-anything-go-others-{}", std::process::id()));
803 let _ = std::fs::remove_dir_all(&root);
804 std::fs::create_dir_all(&root).unwrap();
805 std::fs::write(
806 root.join("plug.js"),
807 "export function each(items, visit) { for (const it of items) visit(it); }\n\
808 export function half(n) { return n / 2; }\n\
809 export function third(n) { return n / 3; }\n",
810 )
811 .unwrap();
812 std::fs::write(
813 root.join("plug.d.ts"),
814 "export declare function each<T>(items: T[], visit: (item: T) => void): void;\n",
815 )
816 .unwrap();
817 let keep = others(&root, Lang::Ts, "plug.js", "half").unwrap();
818 std::fs::remove_dir_all(&root).unwrap();
819 assert_eq!(
820 keep,
821 ["third: not hot in the profiled run; `go` ports one function"]
822 );
823 }
824
825 #[test]
826 fn agents_run_headless_and_others_as_given() {
827 let args = |c: &Command| -> Vec<String> {
828 c.get_args()
829 .map(|a| a.to_string_lossy().into_owned())
830 .collect()
831 };
832 let claude = agent_command("claude").unwrap();
833 assert_eq!(claude.get_program(), "claude");
834 assert_eq!(
835 args(&claude)[..3],
836 ["-p", "--permission-mode", "acceptEdits"]
837 );
838 assert_eq!(
839 args(&agent_command("codex").unwrap()),
840 ["exec", "--full-auto", "-"]
841 );
842 let own = agent_command("my-agent --fast").unwrap();
843 assert_eq!(
844 (own.get_program(), args(&own)),
845 ("my-agent".as_ref(), vec!["--fast".to_string()])
846 );
847 assert!(agent_command(" ").is_err());
848 }
849
850 #[test]
851 fn a_slower_port_stays_off_and_says_where_the_speed_is() {
852 let r = report(vec![hot(
853 "score",
854 85.0,
855 true,
856 &["q", "text"],
857 Some("score:text"),
858 )]);
859 let batched = slower_advice(&pick(&r, None).unwrap(), 0.13);
860 assert!(batched.contains("7.7x slower"), "{batched}");
861 assert!(batched.contains("`ScoreBatch`"), "{batched}");
862 assert!(batched.contains("`main` (app.py:9)"), "{batched}");
863 let r = report(vec![hot("dedupe", 85.0, true, &["names"], None)]);
864 let plain = slower_advice(&pick(&r, None).unwrap(), 0.5);
865 assert!(
866 plain.contains("2.0x slower") && plain.contains("--function"),
867 "{plain}"
868 );
869 assert_eq!(times(31.42), "31.4x faster");
870 }
871
872 #[test]
873 fn the_other_functions_and_classes_of_the_file_stay_in_the_original() {
874 let root = std::env::temp_dir().join(format!("ra-go-others-{}", std::process::id()));
875 let _ = std::fs::remove_dir_all(&root);
876 std::fs::create_dir_all(&root).unwrap();
877 std::fs::write(
878 root.join("lib.py"),
879 "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",
880 )
881 .unwrap();
882 let kept = others(&root, Lang::Python, "lib.py", "hot").unwrap();
883 std::fs::remove_dir_all(&root).unwrap();
884 let names: Vec<&str> = kept.iter().map(|k| k.split(':').next().unwrap()).collect();
885 assert_eq!(names, ["cold", "Table"], "{kept:?}");
886 }
887
888 #[test]
889 fn crate_names_follow_the_function() {
890 assert_eq!(crate_name("fuzzyScore"), "fuzzy-score-rs");
891 assert_eq!(crate_name("dedupe_names"), "dedupe-names-rs");
892 }
893}