Skip to main content

rust_anything/
profile.rs

1//! `profile`: run a real workload under the language's own profiler and say what to port.
2//!
3//! Porting a leaf function rarely pays: each call into Rust costs more than the leaf's work.
4//! What pays is moving a hot loop with its callers, keeping data on the Rust side, and using all
5//! cores. This step finds those: hot functions in the repository, by inclusive time, with the
6//! callers that spend it, call counts where the profiler has them, and a recommendation each.
7
8use crate::walk::Canonical;
9use std::collections::{BTreeMap, HashMap, HashSet};
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13use anyhow::{Context, Result, bail};
14use serde::Serialize;
15use serde_json::Value;
16
17use crate::lang::Lang;
18
19pub const SCHEMA: &str = "rust-anything/profile@1";
20
21#[derive(Debug, Serialize)]
22pub struct Caller {
23    pub name: String,
24    pub file: String,
25    pub line: u32,
26    /// Time of the callee spent under this caller.
27    pub ms: f64,
28    /// Calls from this caller, when the profiler counts calls.
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub calls: Option<u64>,
31}
32
33#[derive(Debug, Serialize)]
34pub struct Hot {
35    pub name: String,
36    pub file: String,
37    pub line: u32,
38    /// The analyzed unit holding the function, and whether the unit exports it.
39    pub unit: Option<String>,
40    pub exported: bool,
41    pub self_ms: f64,
42    pub total_ms: f64,
43    pub total_pct: f64,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub calls: Option<u64>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub ns_per_call: Option<f64>,
48    pub callers: Vec<Caller>,
49    pub advice: String,
50    /// The unit may move to Rust (not marked keep or blocked).
51    pub portable: bool,
52    /// Why `bridge` keeps this exported function in the source language (a callback, a RegExp,
53    /// a generator...), judged by the same rules `bridge` applies. `go` never picks it.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub js_only: Option<String>,
56    /// Parameters of the exported function.
57    pub params: Vec<String>,
58    /// `function:param` for `bridge --batch` when the advice is to batch it.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub batch: Option<String>,
61    /// Share of this function's time spent waiting on child processes it started, itself or
62    /// through the functions it calls. `go` passes over a function that mostly waits.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub child_pct: Option<f64>,
65}
66
67impl Hot {
68    /// Most of its time goes to waiting on child processes: the same work in Rust still waits.
69    pub fn mostly_waits(&self) -> bool {
70        self.child_pct.is_some_and(|p| p >= 50.0)
71    }
72}
73
74/// Time a function in user code (the repository or the workload script) spent waiting on child
75/// processes it started (`execSync`, `subprocess.run`, `os.system`...), itself or through a
76/// library.
77#[derive(Debug, Clone, Serialize)]
78pub struct ChildProcess {
79    /// The program, when the call passes it as a literal (`sleep` for `execSync("sleep 0.2")`).
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub command: Option<String>,
82    pub file: String,
83    /// The call's line when the function makes one such call, else the function's line.
84    pub line: u32,
85    /// The function that makes the call.
86    pub function: String,
87    pub ms: f64,
88    /// Percent of the whole run.
89    pub share: f64,
90}
91
92#[derive(Debug, Serialize)]
93pub struct Report {
94    pub schema: &'static str,
95    pub language: Lang,
96    pub command: Vec<String>,
97    pub total_ms: f64,
98    /// Share of the run spent in the repository's own code (the rest: runtime, libraries).
99    pub repo_pct: f64,
100    /// Every function with at least 1% of the run, hottest first; the first `SHOWN` are
101    /// serialized and printed, and `go` picks from all of them.
102    #[serde(serialize_with = "shown")]
103    pub hot: Vec<Hot>,
104    /// Functions the repository already compiles to machine code (numba, Cython, JAX).
105    #[serde(skip_serializing_if = "Vec::is_empty")]
106    pub compiled: Vec<Compiled>,
107    /// Percent of the run spent waiting on child processes; 0 below 1%.
108    #[serde(skip_serializing_if = "is_zero")]
109    pub child_pct: f64,
110    /// Where the run waits on child processes, longest first (each at least 1% of the run).
111    #[serde(skip_serializing_if = "Vec::is_empty")]
112    pub child_processes: Vec<ChildProcess>,
113}
114
115/// Hot functions in the report and in `--json`.
116pub const SHOWN: usize = 25;
117
118fn shown<S: serde::Serializer>(hot: &[Hot], s: S) -> std::result::Result<S::Ok, S::Error> {
119    s.collect_seq(hot.iter().take(SHOWN))
120}
121
122fn is_zero(x: &f64) -> bool {
123    *x == 0.0
124}
125
126/// What to do instead of porting when the time goes to child processes.
127pub const CHILD_ADVICE: &str = "Porting code will not speed this up: keep one long-lived process \
128                                open, batch the commands, or call the API directly.";
129
130impl Report {
131    /// "38% of the run waits on child processes (`sleep` from `lib.js:6`)." With several,
132    /// "(mostly `sleep` from ...)".
133    pub fn child_summary(&self) -> Option<String> {
134        if self.child_pct < 1.0 {
135            return None;
136        }
137        let Some(top) = self.child_processes.first() else {
138            return Some(format!(
139                "{:.0}% of the run waits on child processes.",
140                self.child_pct
141            ));
142        };
143        let from = match &top.command {
144            Some(c) => format!("`{c}` from `{}:{}`", top.file, top.line),
145            None => format!("from `{}` at `{}:{}`", top.function, top.file, top.line),
146        };
147        let mostly = if self.child_processes.len() > 1 {
148            "mostly "
149        } else {
150            ""
151        };
152        Some(format!(
153            "{:.0}% of the run waits on child processes ({mostly}{from}).",
154            self.child_pct
155        ))
156    }
157}
158
159#[derive(Debug, Clone, Serialize)]
160pub struct Compiled {
161    pub name: String,
162    pub file: String,
163    pub line: u32,
164    pub by: &'static str,
165}
166
167/// Every Python function in the repository a decorator compiles.
168fn compiled_in(root: &Path, lang: Lang) -> Vec<Compiled> {
169    if lang != Lang::Python {
170        return Vec::new();
171    }
172    let Ok(ws) = crate::lang::python::discover(root) else {
173        return Vec::new();
174    };
175    ws.files
176        .iter()
177        .filter(|f| f.kind == crate::ts::discover::FileKind::Source)
178        .flat_map(|f| {
179            let text = std::fs::read_to_string(root.join(&f.path)).unwrap_or_default();
180            crate::risks::python_compiled(&text)
181                .into_iter()
182                .map(|(name, line, by)| Compiled {
183                    name,
184                    file: f.path.clone(),
185                    line,
186                    by,
187                })
188                .collect::<Vec<_>>()
189        })
190        .collect()
191}
192
193/// The body of the Python function `name` defined at or just after `line`.
194fn python_body(text: &str, name: &str, line: u32) -> Option<String> {
195    let lines: Vec<&str> = text.lines().collect();
196    let start = (line as usize).saturating_sub(1);
197    let def = (start..lines.len().min(start + 20)).find(|&i| {
198        let t = lines[i].trim_start();
199        t.strip_prefix("def ")
200            .or_else(|| t.strip_prefix("async def "))
201            .is_some_and(|d| d.starts_with(name) && d[name.len()..].trim_start().starts_with('('))
202    })?;
203    let indent = |l: &str| l.len() - l.trim_start().len();
204    let base = indent(lines[def]);
205    let body: Vec<&str> = lines[def + 1..]
206        .iter()
207        .take_while(|l| l.trim().is_empty() || indent(l) > base)
208        .copied()
209        .collect();
210    Some(body.join("\n"))
211}
212
213fn calls(body: &str, name: &str) -> bool {
214    body.match_indices(&format!("{name}(")).any(|(i, _)| {
215        body[..i]
216            .chars()
217            .next_back()
218            .is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
219    })
220}
221
222/// Advice for a hot function that is compiled already, or that calls compiled code.
223fn compiled_advice(root: &Path, h: &Hot, compiled: &[Compiled]) -> Option<String> {
224    if let Some(c) = compiled
225        .iter()
226        .find(|c| c.file == h.file && c.name == h.name)
227    {
228        return Some(format!(
229            "Already compiled by {} (`{}:{}`): a Rust port is unlikely to run it much faster. \
230             Port it for a pure Rust app, not for speed.",
231            c.by, c.file, c.line
232        ));
233    }
234    let text = std::fs::read_to_string(root.join(&h.file)).ok()?;
235    let body = python_body(&text, &h.name, h.line)?;
236    let called: Vec<&Compiled> = compiled.iter().filter(|c| calls(&body, &c.name)).collect();
237    let first = called.first()?;
238    let names: Vec<String> = called.iter().map(|c| format!("`{}`", c.name)).collect();
239    Some(format!(
240        "{} It calls {} compiled by {} (`{}:{}`): the profiler counts that compiled time here, so \
241         porting this may gain little; port the Python around those calls, or measure without them.",
242        h.advice,
243        names.join(", "),
244        first.by,
245        first.file,
246        first.line
247    ))
248}
249
250/// Loads the project-wide types `lang::exports` reads on this thread (C typedefs, C# shapes), as
251/// `bridge` does before it judges a unit.
252pub fn use_project_types(root: &Path, lang: Lang) {
253    match lang {
254        Lang::C => crate::lang::c::use_typedefs(root),
255        Lang::Csharp => crate::lang::csharp::use_shapes(root),
256        _ => {}
257    }
258}
259
260/// The exported functions of `file`, read as `bridge` reads them (for TS/JS a sibling `.d.ts` and
261/// type aliases applied), each with the reason `bridge` would keep it in the source language. Call
262/// [`use_project_types`] first, as `bridge` does.
263pub fn exports_judged(
264    root: &Path,
265    lang: Lang,
266    file: &str,
267    text: &str,
268) -> Vec<(crate::ts::exports::ExportedFn, Option<String>)> {
269    if lang == Lang::Ts {
270        let types = crate::bridge::types_in_scope(root, file, text);
271        crate::bridge::ts_functions(root, file, text, &types)
272            .into_iter()
273            .map(|f| {
274                let reason = crate::bridge::js_only_reason(&f, &types);
275                (f, reason)
276            })
277            .collect()
278    } else {
279        crate::lang::exports(lang, file, text)
280            .0
281            .into_iter()
282            .map(|f| {
283                let reason = crate::bridge::js_only_reason(&f, &[]);
284                (f, reason)
285            })
286            .collect()
287    }
288}
289
290/// One function's numbers before advice: key is (file, name, line).
291#[derive(Default)]
292struct Acc {
293    self_ms: f64,
294    total_ms: f64,
295    calls: Option<u64>,
296    callers: HashMap<(String, String, u32), (f64, Option<u64>)>,
297    /// Waiting on child processes this function started itself.
298    spawn_ms: f64,
299    /// Waiting on child processes under this function, its callees' included.
300    waits_ms: f64,
301}
302
303type Key = (String, String, u32);
304
305pub fn profile(root: &Path, command: &[String], lang: Option<Lang>) -> Result<Report> {
306    if command.is_empty() {
307        bail!(
308            "give the workload to run after `--`, e.g. `rust-anything profile . -- node bench.mjs`"
309        );
310    }
311    let root = root
312        .canonical()
313        .with_context(|| format!("resolving {}", root.display()))?;
314    let lang = lang.unwrap_or_else(|| Lang::detect(&root));
315    let work = std::env::temp_dir().join(format!("rust-anything-profile-{}", std::process::id()));
316    let _ = std::fs::remove_dir_all(&work);
317    std::fs::create_dir_all(&work)?;
318    let no_waits = |(functions, total_ms)| (functions, 0.0, total_ms);
319    let (functions, unowned_ms, total_ms) = match lang {
320        Lang::Ts => node(&root, command, &work)?,
321        Lang::Python => python(&root, command, &work)?,
322        Lang::Go => no_waits(go(&root, command, &work)?),
323        Lang::Java => no_waits(java(&root, command, &work)?),
324        Lang::Kotlin => bail!(
325            "`profile` does not run Kotlin workloads yet; use JFR (`jfr print --stack-depth 256`) \
326             and port the hot loops it shows"
327        ),
328        Lang::Ruby => no_waits(ruby(&root, command, &work)?),
329        Lang::C => bail!(
330            "`profile` runs TS/JS, Python, Go, Java and Ruby workloads; for C, use `perf record -g` \
331             and port the hot loops it shows"
332        ),
333        Lang::Php => bail!(
334            "`profile` does not run PHP workloads yet; use SPX or Xdebug's profiler and port the \
335             hot loops it shows"
336        ),
337        Lang::Csharp => bail!(
338            "`profile` does not run C# workloads yet; use `dotnet-trace` or your IDE's profiler and \
339             port the hot loops it shows"
340        ),
341        Lang::Powershell => bail!(
342            "`profile` does not run PowerShell workloads yet. Time one `pwsh` start first \
343             (`Measure-Command {{ pwsh -NoProfile -c 1 }}`): when a tool starts a shell per \
344             command, start-up is the slow part and no port fixes it; keep one shell open. For a \
345             script whose own logic is slow, time its functions with `Measure-Command` and port \
346             those"
347        ),
348    };
349    let _ = std::fs::remove_dir_all(&work);
350    Ok(report(
351        &root, lang, command, functions, unowned_ms, total_ms,
352    ))
353}
354
355/// A frame's file: repository-relative, or absolute for user code elsewhere (a workload
356/// script); `None` for the runtime and installed libraries.
357fn relative(root: &Path, file: &str) -> Option<String> {
358    let decoded = crate::walk::file_url_path(file, root);
359    let path = decoded.as_deref().unwrap_or(file);
360    if !path.starts_with('/') && !crate::walk::has_drive(path) && !path.contains(":\\") {
361        let rel = path.trim_start_matches("./");
362        return (!rel.starts_with(['<', '~']) && !rel.contains(':') && root.join(rel).is_file())
363            .then(|| rel.replace('\\', "/")); // node:internal/..., <frozen ...>, ~
364    }
365    // Installed libraries and runtimes: npm, Python, Ruby gems and stdlib, Go modules and GOROOT.
366    if path.split(['/', '\\']).any(|p| {
367        matches!(
368            p,
369            "node_modules"
370                | "site-packages"
371                | "dist-packages"
372                | ".venv"
373                | "venv"
374                | "gems"
375                | "vendor"
376        )
377    }) || python_runtime(path)
378        || ["/lib/ruby/", "/pkg/mod/"].iter().any(|d| path.contains(d))
379        || goroot().is_some_and(|g| path.starts_with(g))
380    {
381        return None;
382    }
383    let p = PathBuf::from(path);
384    Some(match p.strip_prefix(root) {
385        Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
386        Err(_) => path.to_string(),
387    })
388}
389
390/// A Python installation's library: a `lib` or `lib64` folder holding `python3` or `python3.N`.
391fn python_runtime(path: &str) -> bool {
392    let parts: Vec<&str> = path.split(['/', '\\']).collect();
393    parts.windows(2).any(|w| {
394        matches!(w[0], "lib" | "lib64")
395            && w[1].strip_prefix("python3").is_some_and(|v| {
396                v.is_empty()
397                    || v.strip_prefix('.')
398                        .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
399            })
400    })
401}
402
403/// Go's own sources, which are not user code.
404fn goroot() -> Option<&'static str> {
405    static GOROOT: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
406    GOROOT
407        .get_or_init(|| {
408            let out = crate::process::output(
409                Command::new("go").args(["env", "GOROOT"]),
410                crate::process::QUICK,
411            )
412            .ok()?;
413            let root = String::from_utf8(out.stdout).ok()?.trim().to_string();
414            (!root.is_empty()).then(|| format!("{root}/"))
415        })
416        .as_deref()
417}
418
419/// Whether a frame file (a `relative` key) is inside the repository. A key that looks like a
420/// drive path is one only when it names a file under `root`: `relative` keeps `C:/src/a.mjs` for
421/// `/repo/C:/src/a.mjs` on Unix, while an unmatched `C:/Users/...` workload script stays out.
422fn in_repo(root: &Path, file: &str) -> bool {
423    if file.starts_with('/') {
424        return false;
425    }
426    if !crate::walk::has_drive(file) {
427        return true;
428    }
429    let joined = root.join(file);
430    joined.starts_with(root) && joined.is_file()
431}
432
433// ---- node --cpu-prof ------------------------------------------------------------------------
434
435/// Functions, ms of waits on child processes no user function owns, and the run's ms.
436type Waited = (HashMap<Key, Acc>, f64, f64);
437
438/// How the workload starts with the CPU profiler on.
439#[derive(Debug, PartialEq)]
440struct NodeLaunch {
441    /// Arguments after the program.
442    args: Vec<String>,
443    /// `NODE_OPTIONS` to set, which also reaches the node processes a wrapper starts.
444    node_options: Option<String>,
445}
446
447/// Whether `program` is node itself rather than a wrapper such as `npx` or `npm`.
448fn is_node(program: &str) -> bool {
449    Path::new(program).file_stem().is_some_and(|s| s == "node")
450}
451
452/// Asks `program` for its version and whether it allows `--cpu-prof` in `NODE_OPTIONS`. It runs
453/// in the workload's directory, where a relative path or a version manager's shim finds the node
454/// the workload gets, and without `NODE_OPTIONS`, so a preload named there runs once, in the
455/// workload.
456fn cpu_prof_probe(program: &str, root: &Path) -> Command {
457    let mut cmd = Command::new(program);
458    cmd.args([
459        "-p",
460        "process.version + ' ' + process.allowedNodeEnvironmentFlags.has('--cpu-prof')",
461    ])
462    .current_dir(root)
463    .env_remove("NODE_OPTIONS");
464    cmd
465}
466
467/// The version of a node that refuses `--cpu-prof` in `NODE_OPTIONS` (22.14 does; 22.23 and 26
468/// do not), asked of the node itself. `None` when it accepts the flag or could not be asked.
469fn node_refusing_cpu_prof_option(program: &str, root: &Path) -> Option<String> {
470    let out = crate::process::output(&mut cpu_prof_probe(program, root), crate::process::QUICK)
471        .ok()
472        .filter(|out| out.success())?;
473    let answer = out.stdout_text();
474    let (version, allowed) = answer.lines().next()?.trim().split_once(' ')?;
475    (allowed == "false").then(|| version.to_string())
476}
477
478/// `NODE_OPTIONS` reaches every node process, wrappers' children included, so it is used unless
479/// the node refuses `--cpu-prof` there (`refused` names that node's version). Such a node gets
480/// the flags as arguments, which every node accepts, and a wrapper is refused before it runs.
481fn node_launch(
482    command: &[String],
483    refused: Option<&str>,
484    dir: &Path,
485    inherited: &str,
486) -> Result<NodeLaunch> {
487    if let Some(version) = refused {
488        if !is_node(&command[0]) {
489            bail!(
490                "this Node ({version}) refuses --cpu-prof in NODE_OPTIONS, so `profile` cannot reach \
491                 the node that `{}` starts. Run the script with `node` directly, or use a newer Node \
492                 (24 allows it).",
493                command[0]
494            );
495        }
496        let mut args = vec![
497            "--cpu-prof".to_string(),
498            format!("--cpu-prof-dir={}", dir.to_string_lossy()),
499        ];
500        args.extend(command[1..].iter().cloned());
501        return Ok(NodeLaunch {
502            args,
503            node_options: None,
504        });
505    }
506    let dir_option = dir
507        .to_string_lossy()
508        .replace('\\', "\\\\")
509        .replace('"', "\\\"");
510    let options = format!("{inherited} --cpu-prof --cpu-prof-dir=\"{dir_option}\"");
511    Ok(NodeLaunch {
512        args: command[1..].to_vec(),
513        node_options: Some(options.trim().to_string()),
514    })
515}
516
517fn node(root: &Path, command: &[String], work: &Path) -> Result<Waited> {
518    let dir = work.join("node");
519    std::fs::create_dir_all(&dir)?;
520    let probed = if is_node(&command[0]) {
521        command[0].as_str()
522    } else {
523        "node"
524    };
525    let refused = node_refusing_cpu_prof_option(probed, root);
526    let inherited = std::env::var("NODE_OPTIONS").unwrap_or_default();
527    let launch = node_launch(command, refused.as_deref(), &dir, &inherited)?;
528    let mut run = Command::new(&command[0]);
529    run.stdout(std::io::stderr())
530        .args(&launch.args)
531        .current_dir(root);
532    if let Some(options) = &launch.node_options {
533        run.env("NODE_OPTIONS", options);
534    }
535    let status = crate::process::status(&mut run, crate::process::TESTS)
536        .with_context(|| format!("running {}", command[0]))?;
537    if !status.success() {
538        bail!("the workload failed ({status})");
539    }
540    let mut functions: HashMap<Key, Acc> = HashMap::new();
541    let mut total = 0.0;
542    let mut unowned = 0.0;
543    for entry in std::fs::read_dir(&dir)?.flatten() {
544        let profile: Value = serde_json::from_str(&std::fs::read_to_string(entry.path())?)?;
545        total += merge_cpuprofile(root, &profile, &mut functions, &mut unowned);
546    }
547    if total == 0.0 {
548        bail!("no CPU profile was written: is the workload a node process?");
549    }
550    Ok((functions, unowned, total))
551}
552
553/// A `.cpuprofile` node: its frame when it is user code, its own time, its children.
554struct Frame {
555    key: Option<Key>,
556    self_ms: f64,
557    children: Vec<u64>,
558    /// `execSync` and its kin: the thread blocks until the child process exits.
559    spawn: bool,
560}
561
562/// `node:child_process` functions that block until the child exits.
563const NODE_SPAWNS: [&str; 3] = ["execSync", "execFileSync", "spawnSync"];
564
565/// Adds one `.cpuprofile` to `functions`, and to `unowned` the waits on child processes with no
566/// user frame above them; returns its duration in ms.
567fn merge_cpuprofile(
568    root: &Path,
569    profile: &Value,
570    functions: &mut HashMap<Key, Acc>,
571    unowned: &mut f64,
572) -> f64 {
573    let Some(nodes) = profile["nodes"].as_array() else {
574        return 0.0;
575    };
576    let samples = profile["samples"].as_array().map_or(0, Vec::len).max(1);
577    let duration_ms = (profile["endTime"].as_f64().unwrap_or(0.0)
578        - profile["startTime"].as_f64().unwrap_or(0.0))
579        / 1000.0;
580    let per_sample = duration_ms / samples as f64;
581    let mut by_id: HashMap<u64, Frame> = HashMap::new();
582    let mut is_child = HashSet::new();
583    for n in nodes {
584        let id = n["id"].as_u64().unwrap_or(0);
585        let frame = &n["callFrame"];
586        let name = frame["functionName"].as_str().unwrap_or("").to_string();
587        let url = frame["url"].as_str().unwrap_or("");
588        let line = u32::try_from(frame["lineNumber"].as_i64().unwrap_or(0) + 1).unwrap_or(0);
589        let key = relative(root, url).map(|file| {
590            let shown = if name.is_empty() {
591                format!("(anonymous):{line}")
592            } else {
593                name.clone()
594            };
595            (file, shown, line)
596        });
597        let children: Vec<u64> = n["children"]
598            .as_array()
599            .map_or_else(Vec::new, |c| c.iter().filter_map(Value::as_u64).collect());
600        is_child.extend(children.iter().copied());
601        let self_ms = n["hitCount"].as_f64().unwrap_or(0.0) * per_sample;
602        let spawn = url == "node:child_process" && NODE_SPAWNS.contains(&name.as_str());
603        by_id.insert(
604            id,
605            Frame {
606                key,
607                self_ms,
608                children,
609                spawn,
610            },
611        );
612    }
613    // Inclusive time per node, depth first.
614    fn total(id: u64, by_id: &HashMap<u64, Frame>, memo: &mut HashMap<u64, f64>) -> f64 {
615        if let Some(t) = memo.get(&id) {
616            return *t;
617        }
618        let Some(frame) = by_id.get(&id) else {
619            return 0.0;
620        };
621        let t = frame.self_ms
622            + frame
623                .children
624                .iter()
625                .map(|c| total(*c, by_id, memo))
626                .sum::<f64>();
627        memo.insert(id, t);
628        t
629    }
630    let mut memo = HashMap::new();
631    // Walk from the roots, tracking the repo frames on the stack: recursion counts once, and a
632    // callee's caller is the nearest *named* repo frame above it (callbacks are skipped).
633    let roots: Vec<u64> = by_id
634        .keys()
635        .filter(|id| !is_child.contains(id))
636        .copied()
637        .collect();
638    let mut stack: Vec<(u64, Vec<Key>)> = roots.into_iter().map(|r| (r, Vec::new())).collect();
639    while let Some((id, active)) = stack.pop() {
640        let Some(Frame {
641            key,
642            self_ms,
643            children,
644            spawn,
645        }) = by_id.get(&id)
646        else {
647            continue;
648        };
649        if *spawn {
650            // The outermost blocking call: everything under it is the wait (`execSync` calls
651            // `spawnSync`). It goes to the nearest named user frame, as callers do, and counts
652            // once for each frame on the stack.
653            let waited = total(id, &by_id, &mut memo);
654            if let Some(caller) = active
655                .iter()
656                .rev()
657                .find(|c| !c.1.starts_with("(anonymous)"))
658                .or(active.last())
659            {
660                functions.entry(caller.clone()).or_default().spawn_ms += waited;
661                let mut seen = HashSet::new();
662                for k in active.iter().filter(|k| seen.insert(*k)) {
663                    functions.entry(k.clone()).or_default().waits_ms += waited;
664                }
665            } else {
666                *unowned += waited;
667            }
668            continue;
669        }
670        let mut next = active.clone();
671        if let Some(k) = key {
672            let inclusive = total(id, &by_id, &mut memo);
673            let acc = functions.entry(k.clone()).or_default();
674            acc.self_ms += self_ms;
675            if !active.contains(k) {
676                acc.total_ms += inclusive;
677                if let Some(caller) = active
678                    .iter()
679                    .rev()
680                    .find(|c| !c.1.starts_with("(anonymous)"))
681                    && caller != k
682                {
683                    acc.callers.entry(caller.clone()).or_default().0 += inclusive;
684                }
685            }
686            // Anonymous callbacks stay on the stack too; the caller lookup above skips them.
687            next.push(k.clone());
688        }
689        for c in children {
690            stack.push((*c, next.clone()));
691        }
692    }
693    duration_ms
694}
695
696// ---- Python cProfile ------------------------------------------------------------------------
697
698const PSTATS_PY: &str = r#"
699import json, os, pstats, sys, sysconfig
700stats = pstats.Stats(sys.argv[1]).stats
701stdlib = os.path.realpath(sysconfig.get_paths()["stdlib"])
702def in_stdlib(file):
703    return file[:1] not in ("", "<", "~") and os.path.dirname(os.path.realpath(file)) == stdlib
704out = []
705for (file, line, name), (cc, nc, tt, ct, callers) in stats.items():
706    out.append({
707        "file": file, "line": line, "name": name, "calls": nc, "self": tt * 1000, "total": ct * 1000,
708        "stdlib": in_stdlib(file),
709        "callers": [{"file": f, "line": l, "name": n, "calls": c[1], "total": c[3] * 1000} for (f, l, n), c in callers.items()],
710    })
711json.dump(out, open(sys.argv[2], "w"))
712"#;
713
714fn python(root: &Path, command: &[String], work: &Path) -> Result<Waited> {
715    let program = Path::new(&command[0])
716        .file_name()
717        .map(|n| n.to_string_lossy().into_owned())
718        .unwrap_or_default();
719    if !program.starts_with("python") {
720        bail!(
721            "for Python, give the interpreter and script: `rust-anything profile . -- python3 bench.py`"
722        );
723    }
724    let stats = work.join("profile.pstats");
725    let start = std::time::Instant::now();
726    let status = crate::process::status(
727        Command::new(&command[0])
728            .stdout(std::io::stderr())
729            .args(["-m", "cProfile", "-o"])
730            .arg(&stats)
731            .args(&command[1..])
732            .current_dir(root),
733        crate::process::TESTS,
734    )
735    .with_context(|| format!("running {}", command[0]))?;
736    let total_ms = start.elapsed().as_secs_f64() * 1000.0;
737    if !status.success() {
738        bail!("the workload failed ({status})");
739    }
740    let json = work.join("profile.json");
741    let script = work.join("pstats_json.py");
742    std::fs::write(&script, PSTATS_PY)?;
743    let status = crate::process::status(
744        Command::new(&command[0])
745            .stdout(std::io::stderr())
746            .arg(&script)
747            .arg(&stats)
748            .arg(&json),
749        crate::process::TESTS,
750    )?;
751    if !status.success() {
752        bail!("reading the cProfile output failed");
753    }
754    let entries: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(&json)?)?;
755    let (functions, unowned) = ingest_entries(root, &entries);
756    Ok((functions, unowned, total_ms))
757}
758
759/// Function entries from a tracing profiler (cProfile, the Ruby tracer): file, line, name,
760/// calls, self and total ms, and callers with their calls and ms. Also returns the ms of waits on
761/// child processes that no user function owns.
762fn ingest_entries(root: &Path, entries: &[Value]) -> (HashMap<Key, Acc>, f64) {
763    let mut functions: HashMap<Key, Acc> = HashMap::new();
764    for e in entries {
765        let raw_file = e["file"].as_str().unwrap_or("");
766        let Some(file) = relative(root, raw_file) else {
767            continue;
768        };
769        let key = (
770            file,
771            e["name"].as_str().unwrap_or("").to_string(),
772            u32::try_from(e["line"].as_u64().unwrap_or(0)).unwrap_or(0),
773        );
774        let acc = functions.entry(key).or_default();
775        acc.self_ms += e["self"].as_f64().unwrap_or(0.0);
776        acc.total_ms += e["total"].as_f64().unwrap_or(0.0);
777        acc.calls = Some(acc.calls.unwrap_or(0) + e["calls"].as_u64().unwrap_or(0));
778        for c in e["callers"].as_array().into_iter().flatten() {
779            let Some(cfile) = relative(root, c["file"].as_str().unwrap_or("")) else {
780                continue;
781            };
782            let ckey = (
783                cfile,
784                c["name"].as_str().unwrap_or("").to_string(),
785                u32::try_from(c["line"].as_u64().unwrap_or(0)).unwrap_or(0),
786            );
787            let slot = acc.callers.entry(ckey).or_default();
788            slot.0 += c["total"].as_f64().unwrap_or(0.0);
789            slot.1 = Some(slot.1.unwrap_or(0) + c["calls"].as_u64().unwrap_or(0));
790        }
791    }
792    let unowned = child_waits(root, entries, &mut functions);
793    (functions, unowned)
794}
795
796/// Python's calls that wait for a child process: `subprocess.run` and its kin, a `Popen`'s
797/// `communicate`, `wait` and `__exit__` (`with Popen(...)`), and `os.system` (a Python wrapper on some versions, a builtin on
798/// others).
799fn python_spawn(file: &str, name: &str) -> bool {
800    let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
801    (base == "subprocess.py"
802        && matches!(
803            name,
804            "run"
805                | "call"
806                | "check_call"
807                | "check_output"
808                | "getoutput"
809                | "getstatusoutput"
810                | "communicate"
811                | "wait"
812                | "__exit__"
813        ))
814        || (base == "os.py" && name == "system")
815        || (file == "~"
816            && matches!(
817                name,
818                "<built-in method posix.system>" | "<built-in method nt.system>"
819            ))
820}
821
822/// Waits on child processes in a tracing profile (Python's `subprocess` calls). The caller edges
823/// are followed through library frames too (`fetch` -> a library's `run_git` ->
824/// `subprocess.run`): each user function gets the waits under it (`waits_ms`) and the ones it
825/// starts with no user function in between (`spawn_ms`).
826fn child_waits(root: &Path, entries: &[Value], functions: &mut HashMap<Key, Acc>) -> f64 {
827    let raw = |v: &Value| -> Key {
828        (
829            v["file"].as_str().unwrap_or("").to_string(),
830            v["name"].as_str().unwrap_or("").to_string(),
831            u32::try_from(v["line"].as_u64().unwrap_or(0)).unwrap_or(0),
832        )
833    };
834    // The profiled interpreter's standard library, not a repository or dependency module that
835    // happens to be called `subprocess.py`.
836    let stdlib: HashSet<&str> = entries
837        .iter()
838        .filter(|e| e["stdlib"].as_bool() == Some(true))
839        .filter_map(|e| e["file"].as_str())
840        .collect();
841    let is_spawn =
842        |k: &Key| python_spawn(&k.0, &k.1) && (k.0 == "~" || stdlib.contains(k.0.as_str()));
843    if !entries.iter().any(|e| is_spawn(&raw(e))) {
844        return 0.0;
845    }
846    let mut ids: HashMap<Key, usize> = HashMap::new();
847    let mut keys: Vec<Key> = Vec::new();
848    let mut id = |k: Key| -> usize {
849        *ids.entry(k.clone()).or_insert_with(|| {
850            keys.push(k);
851            keys.len() - 1
852        })
853    };
854    let mut edges: Vec<(usize, usize, f64)> = Vec::new(); // (caller, callee, ms)
855    let mut spawn_edges: Vec<(usize, f64)> = Vec::new(); // (caller, ms)
856    let mut totals: Vec<(usize, f64)> = Vec::new();
857    for e in entries {
858        let me = raw(e);
859        let spawner = is_spawn(&me);
860        let i = id(me);
861        totals.push((i, e["total"].as_f64().unwrap_or(0.0)));
862        for c in e["callers"].as_array().into_iter().flatten() {
863            let ck = raw(c);
864            let ms = c["total"].as_f64().unwrap_or(0.0);
865            if spawner {
866                // The outermost waiting call: `subprocess.run` calls `communicate`, which calls
867                // `wait`; each wait counts once.
868                if !is_spawn(&ck) {
869                    spawn_edges.push((id(ck), ms));
870                }
871            } else if !is_spawn(&ck) {
872                edges.push((id(ck), i, ms));
873            }
874        }
875    }
876    let n = keys.len();
877    let mut g = Graph {
878        total: vec![0.0; n],
879        spawn: vec![0.0; n],
880        callees: vec![Vec::new(); n],
881        callers: vec![Vec::new(); n],
882    };
883    for (i, t) in totals {
884        g.total[i] += t;
885    }
886    for (c, ms) in spawn_edges {
887        g.spawn[c] += ms;
888    }
889    for (caller, callee, ms) in edges {
890        if caller != callee && g.total[callee] > 0.0 {
891            g.callees[caller].push((callee, (ms / g.total[callee]).min(1.0)));
892            g.callers[callee].push(caller);
893        }
894    }
895    let user: Vec<Option<Key>> = keys
896        .iter()
897        .map(|k| {
898            (!is_spawn(k))
899                .then(|| relative(root, &k.0).map(|f| (f, k.1.clone(), k.2)))
900                .flatten()
901        })
902        .collect();
903    let waits = g.confirmed();
904    // Waits started by library frames and reaching a frame through library frames only, so a
905    // user function's own waits are not listed again for its user caller, nor for itself when
906    // it recurses through a library (`ast.NodeVisitor`).
907    let foreign = g.waits(|c| user[c].is_none());
908    let mut owned = 0.0;
909    for (i, k) in user.iter().enumerate() {
910        let Some(acc) = k.as_ref().and_then(|k| functions.get_mut(k)) else {
911            continue;
912        };
913        acc.waits_ms += waits[i];
914        let started = g.spawn[i]
915            + g.callees[i]
916                .iter()
917                .filter(|(c, _)| user[*c].is_none())
918                .map(|(c, share)| share * foreign[*c])
919                .sum::<f64>();
920        acc.spawn_ms += started;
921        owned += started;
922    }
923    (g.spawn.iter().sum::<f64>() - owned).max(0.0)
924}
925
926/// A call graph over a tracing profile's frames.
927struct Graph {
928    total: Vec<f64>,
929    /// Waits on child processes started by this frame itself.
930    spawn: Vec<f64>,
931    /// caller -> [(callee, share of the callee's time spent under this caller)]
932    callees: Vec<Vec<(usize, f64)>>,
933    callers: Vec<Vec<usize>>,
934}
935
936impl Graph {
937    /// Waits under each frame, counting only the frames `only` accepts: its own, plus each
938    /// callee's in the share of the callee's time spent under it, never more than its own time.
939    /// Recursion (a cycle of calls) shares one total, so no wait goes around a cycle twice.
940    fn waits(&self, only: impl Fn(usize) -> bool) -> Vec<f64> {
941        let n = self.total.len();
942        // Only frames above a wait matter.
943        let mut relevant = vec![false; n];
944        let mut todo: Vec<usize> = (0..n).filter(|&i| self.spawn[i] > 0.0 && only(i)).collect();
945        while let Some(i) = todo.pop() {
946            if !std::mem::replace(&mut relevant[i], true) {
947                todo.extend(self.callers[i].iter().copied().filter(|&c| !relevant[c]));
948            }
949        }
950        let mut waits = vec![0.0; n];
951        let mut component = vec![usize::MAX; n];
952        for (id, scc) in sccs(&self.callees, &relevant).into_iter().enumerate() {
953            for &m in &scc {
954                component[m] = id;
955            }
956            let own: f64 = scc
957                .iter()
958                .filter(|&&m| only(m))
959                .map(|&m| self.spawn[m])
960                .sum();
961            let under: f64 = scc
962                .iter()
963                .flat_map(|&m| self.callees[m].iter())
964                .filter(|(c, _)| relevant[*c] && component[*c] != id && only(*c))
965                .map(|(c, share)| share * waits[*c])
966                .sum();
967            for &m in &scc {
968                waits[m] = (own + under).min(self.total[m].max(self.spawn[m]));
969            }
970        }
971        waits
972    }
973}
974
975impl Graph {
976    /// Waits known to happen under each frame: its own, plus from each callee the part the
977    /// callee's other callers cannot account for (its waits less the time it spent under them).
978    /// A per-caller share would charge a shared helper's waits to callers that only ran its CPU
979    /// work. Calls within a recursive component confirm nothing for the other members.
980    fn confirmed(&self) -> Vec<f64> {
981        let n = self.total.len();
982        let mut relevant = vec![false; n];
983        let mut todo: Vec<usize> = (0..n).filter(|&i| self.spawn[i] > 0.0).collect();
984        while let Some(i) = todo.pop() {
985            if !std::mem::replace(&mut relevant[i], true) {
986                todo.extend(self.callers[i].iter().copied().filter(|&c| !relevant[c]));
987            }
988        }
989        let mut waits = vec![0.0; n];
990        let mut component = vec![usize::MAX; n];
991        for (id, scc) in sccs(&self.callees, &relevant).into_iter().enumerate() {
992            for &m in &scc {
993                component[m] = id;
994            }
995            for &m in &scc {
996                let under: f64 = self.callees[m]
997                    .iter()
998                    .filter(|(c, _)| relevant[*c] && component[*c] != id)
999                    .map(|&(c, share)| (waits[c] - (1.0 - share) * self.total[c]).max(0.0))
1000                    .sum();
1001                waits[m] = (self.spawn[m] + under).min(self.total[m].max(self.spawn[m]));
1002            }
1003        }
1004        waits
1005    }
1006}
1007
1008/// Strongly connected components of the relevant frames, callees before their callers
1009/// (Tarjan's algorithm, without recursion).
1010fn sccs(edges: &[Vec<(usize, f64)>], relevant: &[bool]) -> Vec<Vec<usize>> {
1011    let n = edges.len();
1012    let mut index = vec![usize::MAX; n];
1013    let mut low = vec![0; n];
1014    let mut on_stack = vec![false; n];
1015    let mut stack = Vec::new();
1016    let mut out = Vec::new();
1017    let mut next = 0;
1018    for start in (0..n).filter(|&i| relevant[i]) {
1019        if index[start] != usize::MAX {
1020            continue;
1021        }
1022        index[start] = next;
1023        low[start] = next;
1024        next += 1;
1025        stack.push(start);
1026        on_stack[start] = true;
1027        // (frame, next edge to look at)
1028        let mut work = vec![(start, 0usize)];
1029        while let Some(&(v, e)) = work.last() {
1030            if let Some(&(w, _)) = edges[v].get(e) {
1031                if let Some(top) = work.last_mut() {
1032                    top.1 += 1;
1033                }
1034                if !relevant[w] {
1035                    continue;
1036                }
1037                if index[w] == usize::MAX {
1038                    index[w] = next;
1039                    low[w] = next;
1040                    next += 1;
1041                    stack.push(w);
1042                    on_stack[w] = true;
1043                    work.push((w, 0));
1044                } else if on_stack[w] {
1045                    low[v] = low[v].min(index[w]);
1046                }
1047                continue;
1048            }
1049            work.pop();
1050            if let Some(&(parent, _)) = work.last() {
1051                low[parent] = low[parent].min(low[v]);
1052            }
1053            if low[v] == index[v] {
1054                let mut scc = Vec::new();
1055                while let Some(w) = stack.pop() {
1056                    on_stack[w] = false;
1057                    scc.push(w);
1058                    if w == v {
1059                        break;
1060                    }
1061                }
1062                out.push(scc);
1063            }
1064        }
1065    }
1066    out
1067}
1068
1069// ---- stack samples (Go pprof, Java JFR) -----------------------------------------------------
1070
1071/// Adds sampled stacks, each root first with `None` for frames outside user code, and the time
1072/// it stands for. A function's total counts once per sample (recursion); its caller is the
1073/// nearest named user frame above it (lambdas and closures are skipped).
1074fn merge_samples(samples: &[(Vec<Option<Key>>, f64)], functions: &mut HashMap<Key, Acc>) {
1075    for (stack, ms) in samples {
1076        let mut seen: Vec<&Key> = Vec::new();
1077        let mut named: Option<&Key> = None;
1078        for frame in stack {
1079            let Some(k) = frame else { continue };
1080            if !seen.contains(&k) {
1081                seen.push(k);
1082                let acc = functions.entry(k.clone()).or_default();
1083                acc.total_ms += ms;
1084                if let Some(caller) = named.filter(|c| *c != k) {
1085                    acc.callers.entry(caller.clone()).or_default().0 += ms;
1086                }
1087            }
1088            if !k.1.starts_with("(anonymous)") {
1089                named = Some(k);
1090            }
1091        }
1092        if let Some(Some(leaf)) = stack.last() {
1093            functions.entry(leaf.clone()).or_default().self_ms += ms;
1094        }
1095    }
1096}
1097
1098/// A Go function's own name: `example.com/x/pkg.Slugify` is `Slugify`, `pkg.(*T).M` is `M`;
1099/// closures (`Outer.func1`) are anonymous.
1100fn go_name(full: &str) -> String {
1101    let tail = full.rsplit('/').next().unwrap_or(full);
1102    let rest = tail.split_once('.').map_or(tail, |(_, r)| r);
1103    let parts: Vec<&str> = rest.split('.').collect();
1104    match parts.as_slice() {
1105        [.., outer, f] if f.starts_with("func") && f[4..].chars().all(|c| c.is_ascii_digit()) => {
1106            format!("(anonymous) in {outer}")
1107        }
1108        [.., last] => last.to_string(),
1109        [] => rest.to_string(),
1110    }
1111}
1112
1113/// `go tool pprof -raw` output: samples (leaf first, by location id) and locations (each one or
1114/// more frames, innermost first: `func file:line:col s=start`).
1115fn parse_pprof_raw(root: &Path, raw: &str) -> Vec<(Vec<Option<Key>>, f64)> {
1116    let mut locations: HashMap<u64, Vec<Option<Key>>> = HashMap::new();
1117    let mut samples: Vec<(Vec<u64>, f64)> = Vec::new();
1118    let mut section = "";
1119    let mut current: Option<u64> = None;
1120    // Which sample value is CPU time: `samples/count cpu/nanoseconds` puts it second.
1121    let mut value_index = 1;
1122    for line in raw.lines() {
1123        match line.trim_end() {
1124            "Samples:" => {
1125                section = "samples";
1126                continue;
1127            }
1128            "Locations" => {
1129                section = "locations";
1130                continue;
1131            }
1132            "Mappings" => {
1133                section = "";
1134                continue;
1135            }
1136            _ => {}
1137        }
1138        match section {
1139            "samples" if line.contains(':') => {
1140                let (values, ids) = line.split_once(':').unwrap_or_default();
1141                let values: Vec<f64> = values
1142                    .split_whitespace()
1143                    .filter_map(|v| v.parse().ok())
1144                    .collect();
1145                let ids: Vec<u64> = ids
1146                    .split_whitespace()
1147                    .filter_map(|v| v.parse().ok())
1148                    .collect();
1149                if let Some(ns) = values.get(value_index).or(values.last()) {
1150                    samples.push((ids, ns / 1e6));
1151                }
1152            }
1153            "samples" => {
1154                let kinds: Vec<&str> = line.split_whitespace().collect();
1155                if let Some(i) = kinds.iter().position(|k| k.ends_with("/nanoseconds")) {
1156                    value_index = i;
1157                }
1158            }
1159            "locations" => {
1160                let text = line.trim_start();
1161                let frame_text = match text.split_once(": ") {
1162                    Some((id, rest)) if id.chars().all(|c| c.is_ascii_digit()) => {
1163                        current = id.parse().ok();
1164                        // `0x4c2ded M=1 func file:line:col s=start`
1165                        rest.split_whitespace()
1166                            .skip(2)
1167                            .collect::<Vec<_>>()
1168                            .join(" ")
1169                    }
1170                    _ => text.to_string(),
1171                };
1172                let Some(id) = current else { continue };
1173                let mut parts = frame_text.split_whitespace();
1174                let (Some(func), Some(place)) = (parts.next(), parts.next()) else {
1175                    continue;
1176                };
1177                let start = parts
1178                    .find_map(|p| p.strip_prefix("s="))
1179                    .and_then(|s| s.parse::<u32>().ok())
1180                    .unwrap_or(0);
1181                let file = place.rsplitn(3, ':').nth(2).unwrap_or(place);
1182                let key = relative(root, file).map(|f| (f, go_name(func), start));
1183                locations.entry(id).or_default().push(key);
1184            }
1185            _ => {}
1186        }
1187    }
1188    samples
1189        .into_iter()
1190        .map(|(ids, ms)| {
1191            // Leaf first, and inlined frames innermost first: reversed, the stack is root first.
1192            let mut stack: Vec<Option<Key>> = ids
1193                .iter()
1194                .flat_map(|id| locations.get(id).cloned().unwrap_or_default())
1195                .collect();
1196            stack.reverse();
1197            (stack, ms)
1198        })
1199        .collect()
1200}
1201
1202/// Go: `go test` with `-cpuprofile` (Go has no profiler to attach from outside), read with
1203/// `go tool pprof -raw`.
1204fn go(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
1205    let program = Path::new(&command[0])
1206        .file_name()
1207        .map(|n| n.to_string_lossy().into_owned())
1208        .unwrap_or_default();
1209    if program != "go" || command.get(1).map(String::as_str) != Some("test") {
1210        bail!(
1211            "for Go, profile a benchmark or test: `rust-anything profile . -- go test -run XXX -bench . ./pkg` \
1212             (Go profiles only from inside the process; `go test` adds -cpuprofile)"
1213        );
1214    }
1215    let out = work.join("cpu.pprof");
1216    let status = crate::process::status(
1217        Command::new(&command[0])
1218            .stdout(std::io::stderr())
1219            .arg("test")
1220            .arg(format!("-cpuprofile={}", out.display()))
1221            .args(&command[2..])
1222            .current_dir(root),
1223        crate::process::TESTS,
1224    )
1225    .with_context(|| format!("running {}", command[0]))?;
1226    if !status.success() {
1227        bail!("the workload failed ({status})");
1228    }
1229    let raw = crate::process::output(
1230        Command::new("go")
1231            .args(["tool", "pprof", "-raw"])
1232            .arg(&out)
1233            .current_dir(root),
1234        crate::process::TESTS,
1235    )?;
1236    if !raw.status.success() {
1237        bail!(
1238            "go tool pprof failed: {}",
1239            String::from_utf8_lossy(&raw.stderr)
1240        );
1241    }
1242    let samples = parse_pprof_raw(root, &String::from_utf8_lossy(&raw.stdout));
1243    let total: f64 = samples.iter().map(|(_, ms)| ms).sum();
1244    let mut functions = HashMap::new();
1245    merge_samples(&samples, &mut functions);
1246    Ok((functions, total))
1247}
1248
1249/// The line declaring method `name` in Java source: the nearest declaration at or above `near`.
1250fn java_declaration(text: &str, name: &str, near: u32) -> Option<u32> {
1251    let needle = format!("{name}(");
1252    let mut best = None;
1253    for (i, line) in text.lines().enumerate() {
1254        let n = u32::try_from(i + 1).unwrap_or(u32::MAX);
1255        if n > near.max(1) {
1256            break;
1257        }
1258        let Some(at) = line.find(&needle) else {
1259            continue;
1260        };
1261        let before = line[..at].trim_end();
1262        // A declaration names a type or modifier before the method: `static int pages(`.
1263        let declares = before
1264            .ends_with(|c: char| c.is_alphanumeric() || matches!(c, '>' | ']' | '_'))
1265            && !before.contains('=')
1266            && !before.contains("return")
1267            && !before.contains("new ")
1268            && !before.ends_with('.')
1269            && !line.trim_end().ends_with(';');
1270        if declares && at > 0 && line.as_bytes()[at - 1].is_ascii_whitespace() {
1271            best = Some(n);
1272        }
1273    }
1274    best
1275}
1276
1277/// Java: Flight Recorder's execution samples, read with `jfr print --json`.
1278fn java(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
1279    let recording = work.join("profile.jfr");
1280    let mut options = std::env::var("JAVA_TOOL_OPTIONS").unwrap_or_default();
1281    options.push_str(&format!(
1282        " -XX:StartFlightRecording=filename={},settings=profile -XX:FlightRecorderOptions=stackdepth=256",
1283        recording.display()
1284    ));
1285    let status = crate::process::status(
1286        Command::new(&command[0])
1287            .stdout(std::io::stderr())
1288            .args(&command[1..])
1289            .current_dir(root)
1290            .env("JAVA_TOOL_OPTIONS", options.trim()),
1291        crate::process::TESTS,
1292    )
1293    .with_context(|| format!("running {}", command[0]))?;
1294    if !status.success() {
1295        bail!("the workload failed ({status})");
1296    }
1297    let out = crate::process::output(
1298        Command::new("jfr")
1299            .args([
1300                "print",
1301                "--json",
1302                "--stack-depth",
1303                "256",
1304                "--events",
1305                "jdk.ExecutionSample",
1306            ])
1307            .arg(&recording),
1308        crate::process::TESTS,
1309    )
1310    .context("running jfr (it comes with the JDK)")?;
1311    if !out.status.success() {
1312        bail!("jfr print failed: {}", String::from_utf8_lossy(&out.stderr));
1313    }
1314    let json: Value = serde_json::from_slice(&out.stdout).context("jfr output")?;
1315    // Sources by class: `com/example/text/Strings` -> its file in the repository.
1316    let mut sources: HashMap<String, String> = HashMap::new();
1317    for entry in crate::walk::builder(root).build() {
1318        let Ok(entry) = entry else { continue };
1319        let path = entry.path();
1320        if path.extension().is_some_and(|e| e == "java")
1321            && let Ok(rel) = path.strip_prefix(root)
1322        {
1323            let rel = rel.to_string_lossy().replace('\\', "/");
1324            let text = std::fs::read_to_string(path).unwrap_or_default();
1325            let package = text
1326                .lines()
1327                .find_map(|l| {
1328                    l.trim()
1329                        .strip_prefix("package ")
1330                        .map(|p| p.trim_end_matches(';').trim().to_string())
1331                })
1332                .unwrap_or_default();
1333            let class = path
1334                .file_stem()
1335                .map(|s| s.to_string_lossy().into_owned())
1336                .unwrap_or_default();
1337            let fq = if package.is_empty() {
1338                class
1339            } else {
1340                format!("{}/{class}", package.replace('.', "/"))
1341            };
1342            sources.insert(fq, rel);
1343        }
1344    }
1345    const SAMPLE_MS: f64 = 10.0; // the `profile` settings sample Java threads every 10 ms
1346    let mut raw: Vec<Vec<Option<(String, String, u32)>>> = Vec::new();
1347    for event in json["recording"]["events"].as_array().into_iter().flatten() {
1348        let frames = event["values"]["stackTrace"]["frames"]
1349            .as_array()
1350            .cloned()
1351            .unwrap_or_default();
1352        let mut stack: Vec<Option<(String, String, u32)>> = frames
1353            .iter()
1354            .map(|f| {
1355                let class = f["method"]["type"]["name"].as_str()?;
1356                let outer = class.split('$').next().unwrap_or(class);
1357                let file = sources.get(outer)?;
1358                let name = f["method"]["name"].as_str()?.to_string();
1359                let line = u32::try_from(f["lineNumber"].as_i64().unwrap_or(0)).unwrap_or(0);
1360                Some((file.clone(), name, line))
1361            })
1362            .collect();
1363        stack.reverse();
1364        raw.push(stack);
1365    }
1366    // Key each method by its declaration line, found from the lowest sampled line.
1367    let mut lowest: HashMap<(String, String), u32> = HashMap::new();
1368    for (file, name, line) in raw.iter().flatten().flatten() {
1369        let e = lowest.entry((file.clone(), name.clone())).or_insert(*line);
1370        *e = (*e).min(*line);
1371    }
1372    let mut texts: HashMap<String, String> = HashMap::new();
1373    let mut key = |file: &str, name: &str| -> Key {
1374        if name.starts_with("lambda$") {
1375            return (file.to_string(), format!("(anonymous) {name}"), 0);
1376        }
1377        let text = texts
1378            .entry(file.to_string())
1379            .or_insert_with(|| std::fs::read_to_string(root.join(file)).unwrap_or_default());
1380        let near = lowest
1381            .get(&(file.to_string(), name.to_string()))
1382            .copied()
1383            .unwrap_or(0);
1384        let line = java_declaration(text, name, near).unwrap_or(near);
1385        (file.to_string(), name.to_string(), line)
1386    };
1387    let samples: Vec<(Vec<Option<Key>>, f64)> = raw
1388        .iter()
1389        .map(|stack| {
1390            let keys = stack
1391                .iter()
1392                .map(|f| f.as_ref().map(|(file, name, _)| key(file, name)))
1393                .collect();
1394            (keys, SAMPLE_MS)
1395        })
1396        .collect();
1397    let total = samples.len() as f64 * SAMPLE_MS;
1398    if samples.is_empty() {
1399        bail!("no samples were recorded: run the workload longer (Java is sampled every 10 ms)");
1400    }
1401    let mut functions = HashMap::new();
1402    merge_samples(&samples, &mut functions);
1403    Ok((functions, total))
1404}
1405
1406// ---- Ruby: a call tracer --------------------------------------------------------------------
1407
1408/// Loaded with `RUBYOPT=-r`: times every Ruby method call on the main thread (inclusive, self,
1409/// callers) and writes cProfile-like entries at exit. Tracing slows the program; the shares stay
1410/// comparable.
1411const RUBY_TRACER: &str = r#"
1412require "json"
1413
1414module RustAnythingProfile
1415  STATS = Hash.new { |h, k| h[k] = { calls: 0, self: 0.0, total: 0.0, callers: Hash.new { |c, ck| c[ck] = [0, 0.0] } } }
1416  STACK = []
1417  ACTIVE = Hash.new(0)
1418  MAIN = Thread.current
1419  TRACE = TracePoint.new(:call, :return) do |tp|
1420    next unless Thread.current == MAIN
1421    now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1422    if tp.event == :call
1423      path = tp.path
1424      path = File.expand_path(path) unless path.start_with?("<")
1425      key = [path, tp.lineno, tp.method_id.to_s]
1426      ACTIVE[key] += 1
1427      STACK << [key, now, 0.0]
1428    elsif (frame = STACK.pop)
1429      key, start, child = frame
1430      elapsed = now - start
1431      ACTIVE[key] -= 1
1432      outer = ACTIVE[key].zero?
1433      s = STATS[key]
1434      s[:calls] += 1
1435      s[:self] += elapsed - child
1436      s[:total] += elapsed if outer
1437      if (parent = STACK.last)
1438        parent[2] += elapsed
1439        c = s[:callers][parent[0]]
1440        c[0] += 1
1441        c[1] += elapsed if outer
1442      end
1443    end
1444  end
1445  TRACE.enable
1446
1447  at_exit do
1448    TRACE.disable
1449    out = STATS.map do |(file, line, name), s|
1450      { file: file, line: line, name: name, calls: s[:calls], self: s[:self] * 1000, total: s[:total] * 1000,
1451        callers: s[:callers].map { |(f, l, n), (calls, total)| { file: f, line: l, name: n, calls: calls, total: total * 1000 } } }
1452    end
1453    File.write(ENV.fetch("RUST_ANYTHING_PROFILE_OUT"), JSON.generate(out))
1454  end
1455end
1456"#;
1457
1458/// Ruby: the tracer above, loaded into any Ruby command through `RUBYOPT`.
1459fn ruby(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
1460    let tracer = work.join("rust_anything_profile.rb");
1461    std::fs::write(&tracer, RUBY_TRACER)?;
1462    let out = work.join("profile.json");
1463    let mut rubyopt = std::env::var("RUBYOPT").unwrap_or_default();
1464    rubyopt.push_str(&format!(" -r{}", tracer.display()));
1465    let start = std::time::Instant::now();
1466    let status = crate::process::status(
1467        Command::new(&command[0])
1468            .stdout(std::io::stderr())
1469            .args(&command[1..])
1470            .current_dir(root)
1471            .env("RUBYOPT", rubyopt.trim())
1472            .env("RUST_ANYTHING_PROFILE_OUT", &out),
1473        crate::process::TESTS,
1474    )
1475    .with_context(|| format!("running {}", command[0]))?;
1476    let total_ms = start.elapsed().as_secs_f64() * 1000.0;
1477    if !status.success() {
1478        bail!("the workload failed ({status})");
1479    }
1480    let entries: Vec<Value> = serde_json::from_str(
1481        &std::fs::read_to_string(&out)
1482            .context("the Ruby tracer wrote nothing: is the workload a Ruby process?")?,
1483    )?;
1484    Ok((ingest_entries(root, &entries).0, total_ms))
1485}
1486
1487// ---- the report -----------------------------------------------------------------------------
1488
1489/// The argument a caller passes per loop item: an arrow or for-of variable among `f`'s call
1490/// arguments in the caller's source. `None` when the source does not show one.
1491fn batch_param(root: &Path, caller: &Key, callee: &str, params: &[String]) -> Option<String> {
1492    let text = std::fs::read_to_string(root.join(&caller.0)).ok()?;
1493    let lines: Vec<&str> = text.lines().collect();
1494    let start = (caller.2 as usize).saturating_sub(1);
1495    let body = lines.get(start..(start + 80).min(lines.len()))?.join("\n");
1496    let mut loop_vars: Vec<String> = Vec::new();
1497    for (i, _) in body.match_indices("=>") {
1498        let before = body[..i].trim_end().trim_end_matches(')');
1499        let name: String = before
1500            .chars()
1501            .rev()
1502            .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$')
1503            .collect::<String>()
1504            .chars()
1505            .rev()
1506            .collect();
1507        if !name.is_empty() {
1508            loop_vars.push(name);
1509        }
1510    }
1511    for word in ["const ", "let ", "var ", "for "] {
1512        for (i, _) in body.match_indices(word) {
1513            let rest = &body[i + word.len()..];
1514            let name: String = rest
1515                .chars()
1516                .take_while(|c| c.is_alphanumeric() || *c == '_')
1517                .collect();
1518            if rest[name.len()..].trim_start().starts_with("of ")
1519                || rest[name.len()..].trim_start().starts_with("in ")
1520            {
1521                loop_vars.push(name);
1522            }
1523        }
1524    }
1525    let (more, index_vars) = loop_variables(&body);
1526    loop_vars.extend(more);
1527    let call = body.find(&format!("{callee}("))?;
1528    let args_text = &body[call + callee.len() + 1..];
1529    let mut depth = 0;
1530    let mut args = vec![String::new()];
1531    for c in args_text.chars() {
1532        match c {
1533            '(' | '[' | '{' => depth += 1,
1534            ')' | ']' | '}' if depth == 0 => break,
1535            ')' | ']' | '}' => depth -= 1,
1536            ',' if depth == 0 => {
1537                args.push(String::new());
1538                continue;
1539            }
1540            _ => {}
1541        }
1542        args.last_mut()?.push(c);
1543    }
1544    // The item itself (`t`), or the item at the loop index (`texts[i]`).
1545    let per_item = |a: &str| {
1546        let a = a.trim();
1547        loop_vars.iter().any(|v| v == a)
1548            || a.strip_suffix(']')
1549                .and_then(|a| a.split_once('['))
1550                .is_some_and(|(list, i)| {
1551                    !list.is_empty() && index_vars.iter().any(|v| v == i.trim())
1552                })
1553    };
1554    // In nested loops the innermost one runs over the items: its variable is declared last.
1555    let declared_at = |a: &str| {
1556        let a = a.trim();
1557        let var = a
1558            .strip_suffix(']')
1559            .and_then(|a| a.split_once('['))
1560            .map_or(a, |(_, i)| i.trim());
1561        regex::Regex::new(&format!(r"\b{}\b", regex::escape(var)))
1562            .ok()
1563            .and_then(|re| re.find(&body).map(|m| m.start()))
1564            .unwrap_or(0)
1565    };
1566    let position = args
1567        .iter()
1568        .enumerate()
1569        .filter(|(_, a)| per_item(a))
1570        .max_by_key(|(_, a)| declared_at(a))?
1571        .0;
1572    params.get(position).cloned()
1573}
1574
1575/// Loop variables in Go, Java and Ruby source: `(items, indexes)`. Items: `for _, t := range`,
1576/// `for (String t : texts)`, `|t|`; indexes: `for i := range`, `for (int i = 0;`.
1577fn loop_variables(body: &str) -> (Vec<String>, Vec<String>) {
1578    let ident = |s: &str| -> String {
1579        s.chars()
1580            .take_while(|c| c.is_alphanumeric() || *c == '_')
1581            .collect()
1582    };
1583    let last_ident = |s: &str| -> String {
1584        let s = s.trim_end();
1585        let rev: String = s
1586            .chars()
1587            .rev()
1588            .take_while(|c| c.is_alphanumeric() || *c == '_')
1589            .collect();
1590        rev.chars().rev().collect()
1591    };
1592    let (mut items, mut indexes) = (Vec::new(), Vec::new());
1593    for (i, _) in body.match_indices("for") {
1594        if body[..i]
1595            .chars()
1596            .last()
1597            .is_some_and(|c| c.is_alphanumeric() || c == '_')
1598        {
1599            continue;
1600        }
1601        let rest = &body[i + 3..];
1602        let line = rest.split(['{', '\n']).next().unwrap_or(rest);
1603        if let Some((vars, _)) = line.split_once(":= range") {
1604            // Go: `for i, t := range xs` (t is the item), `for i := range xs` (an index).
1605            let vars: Vec<String> = vars.split(',').map(|v| v.trim().to_string()).collect();
1606            match vars.as_slice() {
1607                [index, item] => {
1608                    items.push(item.clone());
1609                    indexes.push(index.clone());
1610                }
1611                [index] => indexes.push(index.clone()),
1612                _ => {}
1613            }
1614        } else if let Some(inner) = line.trim_start().strip_prefix('(') {
1615            // Java: `for (String t : texts)` or `for (int i = 0; ...)`.
1616            if let Some((decl, _)) = inner.split_once(" : ").filter(|(d, _)| !d.contains(';')) {
1617                items.push(last_ident(decl));
1618            } else if let Some((decl, _)) = inner.split_once('=') {
1619                indexes.push(last_ident(decl));
1620            }
1621        }
1622    }
1623    // Ruby blocks: `{ |t| ... }`, `do |t, i|`.
1624    for (i, _) in body.match_indices('|') {
1625        let before = body[..i].trim_end();
1626        if before.ends_with('{') || before.ends_with("do") {
1627            let first = ident(body[i + 1..].trim_start());
1628            if !first.is_empty() {
1629                items.push(first);
1630            }
1631        }
1632    }
1633    items.retain(|v| !v.is_empty() && v != "_");
1634    indexes.retain(|v| !v.is_empty() && v != "_");
1635    (items, indexes)
1636}
1637
1638fn report(
1639    root: &Path,
1640    lang: Lang,
1641    command: &[String],
1642    functions: HashMap<Key, Acc>,
1643    unowned_ms: f64,
1644    total_ms: f64,
1645) -> Report {
1646    let analysis = crate::analyze::analyze_lang(root, lang).ok();
1647    let unit_of = |file: &str| -> Option<(String, bool)> {
1648        let a = analysis.as_ref()?;
1649        let u = a.units.iter().find(|u| u.files.iter().any(|f| f == file))?;
1650        let portable = !matches!(
1651            u.status,
1652            crate::analyze::Status::Keep | crate::analyze::Status::Blocked
1653        );
1654        Some((u.id.clone(), portable))
1655    };
1656    // Each hot file's exported functions, read and judged once, as `bridge` reads and judges
1657    // them.
1658    use_project_types(root, lang);
1659    let mut judged: HashMap<String, Vec<(crate::ts::exports::ExportedFn, Option<String>)>> =
1660        HashMap::new();
1661    for ((file, _, _), a) in &functions {
1662        if in_repo(root, file)
1663            && total_ms > 0.0
1664            && a.total_ms / total_ms >= 0.01
1665            && !judged.contains_key(file)
1666        {
1667            let exports = std::fs::read_to_string(root.join(file))
1668                .map(|text| exports_judged(root, lang, file, &text))
1669                .unwrap_or_default();
1670            judged.insert(file.clone(), exports);
1671        }
1672    }
1673    let exports_of = |file: &str,
1674                      name: &str,
1675                      line: u32|
1676     -> Option<(crate::ts::exports::ExportedFn, Option<String>)> {
1677        let exports = judged.get(file)?;
1678        exports
1679            .iter()
1680            .find(|(f, _)| f.name == name && f.line == line)
1681            .or_else(|| exports.iter().find(|(f, _)| f.name == name))
1682            .cloned()
1683    };
1684    let repo_self: f64 = functions
1685        .iter()
1686        .filter(|(k, _)| in_repo(root, &k.0))
1687        .map(|(_, a)| a.self_ms)
1688        .sum();
1689    let mut calls_in: HashMap<&str, Vec<SpawnCall>> = HashMap::new();
1690    let mut child_processes: Vec<ChildProcess> = functions
1691        .iter()
1692        .filter(|(_, a)| total_ms > 0.0 && a.spawn_ms / total_ms >= 0.01)
1693        .map(|((file, name, line), a)| {
1694            let calls = calls_in
1695                .entry(file.as_str())
1696                .or_insert_with(|| spawn_calls_in(root, lang, file));
1697            let (line, command) = spawn_site(calls, name, *line).unwrap_or((*line, None));
1698            ChildProcess {
1699                command,
1700                file: file.clone(),
1701                line,
1702                function: name.clone(),
1703                ms: a.spawn_ms,
1704                share: 100.0 * a.spawn_ms / total_ms,
1705            }
1706        })
1707        .collect();
1708    child_processes.sort_by(|a, b| b.ms.total_cmp(&a.ms));
1709    // Every wait counts once, at the frame that starts it, so the parts add up to the whole.
1710    let child_pct = if total_ms > 0.0 {
1711        (100.0 * (unowned_ms + functions.values().map(|a| a.spawn_ms).sum::<f64>()) / total_ms)
1712            .min(100.0)
1713    } else {
1714        0.0
1715    };
1716    let child_pct = if child_pct >= 1.0 { child_pct } else { 0.0 };
1717    let mut hot: Vec<Hot> = functions
1718        .into_iter()
1719        .filter(|((file, _, _), a)| in_repo(root, file) && total_ms > 0.0 && a.total_ms / total_ms >= 0.01)
1720        .map(|((file, name, line), a)| {
1721            let unit = unit_of(&file);
1722            let (export, js_only) = match exports_of(&file, &name, line) {
1723                Some((f, reason)) => (Some(f), reason),
1724                None => (None, None),
1725            };
1726            let mut callers: Vec<Caller> = a
1727                .callers
1728                .iter()
1729                .map(|((f, n, l), (ms, calls))| Caller { name: n.clone(), file: f.clone(), line: *l, ms: *ms, calls: *calls })
1730                .collect();
1731            callers.sort_by(|x, y| y.ms.total_cmp(&x.ms));
1732            callers.truncate(5);
1733            let ns_per_call = a.calls.filter(|c| *c > 0).map(|c| a.total_ms * 1e6 / c as f64);
1734            let total_pct = 100.0 * a.total_ms / total_ms;
1735            let top = callers.first();
1736            let small_per_call = ns_per_call.is_some_and(|ns| ns < 20_000.0) || (a.calls.is_none() && top.is_some_and(|c| c.ms >= 0.5 * a.total_ms));
1737            let params: Vec<String> = export.as_ref().map(|e| e.params.iter().map(|p| p.name.clone()).collect()).unwrap_or_default();
1738            let child_pct = (a.total_ms > 0.0 && a.waits_ms / a.total_ms >= 0.01)
1739                .then(|| (100.0 * a.waits_ms / a.total_ms).min(100.0));
1740            let mut batch_spec = None;
1741            let port_it = |u: &str| {
1742                format!(
1743                    "Hot and exported by `{u}`: port it (`rust-anything bridge {} {u}`), then check `rust-anything bench`.",
1744                    root.display()
1745                )
1746            };
1747            let advice = match (&unit, &export) {
1748                _ if child_pct.is_some_and(|p| p >= 50.0) => format!(
1749                    "Hot, but {:.0}% of its time waits on child processes. {CHILD_ADVICE}",
1750                    child_pct.unwrap_or_default()
1751                ),
1752                _ if is_top_level(&name, line) => {
1753                    "The file's top level: nothing calls it and there is nothing to port. See the functions it calls.".into()
1754                }
1755                (Some((_, true)), Some(_)) if js_only.is_some() => format!(
1756                    "Hot, but `bridge` keeps `{name}` in {}: {}.",
1757                    lang.name(),
1758                    js_only.as_deref().unwrap_or_default()
1759                ),
1760                (Some((u, true)), Some(_)) if small_per_call && top.is_some() => {
1761                    let c = top.expect("checked");
1762                    let batch = batch_param(root, &(c.file.clone(), c.name.clone(), c.line), &name, &params);
1763                    batch_spec = batch.as_ref().map(|p| format!("{name}:{p}"));
1764                    let calls = a.calls.map_or_else(String::new, |n| format!(", {n} calls"));
1765                    // A file's top level is not a function anyone could port with it.
1766                    let portable_caller = !is_top_level(&c.name, c.line);
1767                    match batch {
1768                        Some(param) => format!(
1769                            "Called in a loop by `{}` ({}:{}{calls}): a call per item would cost more than the work. \
1770                             Batch it, keeping the items in Rust and using all cores: \
1771                             `rust-anything bridge {} {u} --batch {name}:{param}`, then prepare the items once in a \
1772                             `{}Index` in port.rs.{}",
1773                            c.name,
1774                            c.file,
1775                            c.line,
1776                            root.display(),
1777                            crate::codegen_batch::pascal(&name),
1778                            if portable_caller {
1779                                format!(" Better still, port `{}` with it.", c.name)
1780                            } else {
1781                                String::new()
1782                            }
1783                        ),
1784                        None if portable_caller => format!(
1785                            "Mostly called by `{}` ({}:{}{calls}): port `{}` together with `{name}`, so one call into Rust does the whole loop.",
1786                            c.name, c.file, c.line, c.name
1787                        ),
1788                        None => port_it(u),
1789                    }
1790                }
1791                (Some((u, true)), Some(_)) => port_it(u),
1792                (Some((u, true)), None) => format!("Hot inside `{u}`: port the exported function that calls it, with it."),
1793                (Some((u, false)), _) => format!("Hot, but `{u}` must stay in the source language (see `rust-anything analyze`)."),
1794                (None, _) => "Hot, outside the analyzed units.".into(),
1795            };
1796            Hot {
1797                portable: unit.as_ref().is_some_and(|(_, p)| *p),
1798                js_only,
1799                params,
1800                batch: batch_spec,
1801                child_pct,
1802                unit: unit.map(|(u, _)| u),
1803                exported: export.is_some(),
1804                name,
1805                file,
1806                line,
1807                self_ms: a.self_ms,
1808                total_ms: a.total_ms,
1809                total_pct,
1810                calls: a.calls,
1811                ns_per_call,
1812                callers,
1813                advice,
1814            }
1815        })
1816        .collect();
1817    hot.sort_by(|a, b| b.total_ms.total_cmp(&a.total_ms));
1818    let compiled = compiled_in(root, lang);
1819    for h in &mut hot {
1820        if let Some(advice) = compiled_advice(root, h, &compiled) {
1821            h.advice = advice;
1822        }
1823    }
1824    Report {
1825        schema: SCHEMA,
1826        language: lang,
1827        command: command.to_vec(),
1828        total_ms,
1829        repo_pct: if total_ms > 0.0 {
1830            (100.0 * repo_self / total_ms).min(100.0)
1831        } else {
1832            0.0
1833        },
1834        compiled,
1835        hot,
1836        child_pct,
1837        child_processes,
1838    }
1839}
1840
1841/// A file's top level: Python's `<module>`, Node's module function on line 1.
1842fn is_top_level(name: &str, line: u32) -> bool {
1843    name == "<module>" || (line == 1 && name.starts_with("(anonymous)"))
1844}
1845
1846/// Where the function `name` defined at `line` starts its child process: the call's line, and
1847/// the program when the call names it literally. A call in a callback counts for the function
1848/// around it, as the wait does. `None` when there is no such call, or several that start
1849/// different programs.
1850fn spawn_site(calls: &[SpawnCall], name: &str, line: u32) -> Option<(u32, Option<String>)> {
1851    let top = is_top_level(name, line);
1852    let own: Vec<&SpawnCall> = calls
1853        .iter()
1854        .filter(|c| {
1855            c.scopes.last() == Some(&line) || c.owner == Some(line) || (top && c.scopes.is_empty())
1856        })
1857        .collect();
1858    let sites = if own.is_empty() {
1859        calls.iter().filter(|c| c.scopes.contains(&line)).collect()
1860    } else {
1861        own
1862    };
1863    let first = sites.first()?;
1864    let same = sites
1865        .iter()
1866        .all(|s| s.program.is_some() && s.program == first.program);
1867    (sites.len() == 1 || same).then(|| (first.line, first.program.clone()))
1868}
1869
1870/// The calls in a repository file that start a child process and wait for it.
1871fn spawn_calls_in(root: &Path, lang: Lang, file: &str) -> Vec<SpawnCall> {
1872    let inside = Path::new(file)
1873        .components()
1874        .all(|c| matches!(c, std::path::Component::Normal(_)));
1875    if !inside {
1876        return Vec::new(); // `/abs/bench.py`, `../bench.py`, `C:\\...`: not the repository's
1877    }
1878    let Ok(text) = std::fs::read_to_string(root.join(file)) else {
1879        return Vec::new();
1880    };
1881    match lang {
1882        Lang::Ts => js_spawn_calls(file, &text),
1883        Lang::Python => python_spawn_calls(&text),
1884        _ => Vec::new(),
1885    }
1886}
1887
1888/// A call that starts a child process and waits for it.
1889#[derive(Debug, Clone, PartialEq)]
1890struct SpawnCall {
1891    /// First lines of the functions around the call, innermost last; empty at the top level.
1892    scopes: Vec<u32>,
1893    /// The function the profile charges the wait to: in JS the innermost named one (a callback
1894    /// passed as an argument has no name), else the innermost.
1895    owner: Option<u32>,
1896    line: u32,
1897    /// The program, when the call names it literally.
1898    program: Option<String>,
1899}
1900
1901/// The program in a command line: `sleep` in `sleep 0.2`. `interpolated` when the text goes on
1902/// with a computed part (`ls ${dir}` gives `ls`, `${bin} run` and `git${x}` give nothing).
1903/// Leading `NAME=value` words are the child's environment, not the program, and are never shown.
1904fn first_word(command: &str, interpolated: bool) -> Option<String> {
1905    let mut rest = command.trim_start();
1906    loop {
1907        let word = rest.split_whitespace().next()?;
1908        let assignment = word.split_once('=').is_some_and(|(name, _)| {
1909            !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1910        });
1911        let after = rest[word.len()..].trim_start();
1912        if assignment {
1913            if word.contains(['"', '\'']) {
1914                return None; // `TOKEN='a b' deploy`: where the value ends is the shell's business
1915            }
1916            rest = after;
1917            continue;
1918        }
1919        // The word must end before any computed part, and be safe in a markdown table.
1920        let complete = !interpolated || rest.len() > word.len();
1921        let plain = !word.contains(['|', '`', '$', '{']) && !word.chars().any(char::is_control);
1922        return (complete && plain).then(|| word.to_string());
1923    }
1924}
1925
1926/// The executable a call names on its own (`execFileSync(file, args)`, an argv list): the whole
1927/// text, spaces included, when it is safe in a markdown table.
1928fn whole_program(path: &str) -> Option<String> {
1929    (!path.trim().is_empty() && !path.contains(['|', '`']) && !path.chars().any(char::is_control))
1930        .then(|| path.to_string())
1931}
1932
1933/// Node's blocking `child_process` calls in a JS/TS file, read with oxc.
1934fn js_spawn_calls(path: &str, source: &str) -> Vec<SpawnCall> {
1935    use oxc_ast::ast::{Argument, ArrowFunctionExpression, CallExpression, Expression, Function};
1936    use oxc_ast_visit::{Visit, walk};
1937    use oxc_syntax::scope::ScopeFlags;
1938
1939    struct Calls {
1940        /// Byte offset of every newline, to turn offsets into lines without rescanning.
1941        newlines: Vec<usize>,
1942        /// First line of each enclosing function, and whether V8 gives it a name.
1943        scopes: Vec<(u32, bool)>,
1944        /// Where the functions passed straight to a call start: V8 shows them as anonymous.
1945        callbacks: HashSet<u32>,
1946        out: Vec<SpawnCall>,
1947    }
1948    impl Calls {
1949        fn line(&self, offset: u32) -> u32 {
1950            let before = self.newlines.partition_point(|&n| n < offset as usize);
1951            u32::try_from(before + 1).unwrap_or(u32::MAX)
1952        }
1953    }
1954    impl<'a> Visit<'a> for Calls {
1955        fn visit_function(&mut self, it: &Function<'a>, flags: ScopeFlags) {
1956            let named = it.id.is_some() || !self.callbacks.contains(&it.span.start);
1957            self.scopes.push((self.line(it.span.start), named));
1958            walk::walk_function(self, it, flags);
1959            self.scopes.pop();
1960        }
1961        fn visit_arrow_function_expression(&mut self, it: &ArrowFunctionExpression<'a>) {
1962            let named = !self.callbacks.contains(&it.span.start);
1963            self.scopes.push((self.line(it.span.start), named));
1964            walk::walk_arrow_function_expression(self, it);
1965            self.scopes.pop();
1966        }
1967        fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
1968            let callee = match &it.callee {
1969                Expression::Identifier(id) => Some(id.name.as_str()),
1970                Expression::StaticMemberExpression(m) => Some(m.property.name.as_str()),
1971                _ => None,
1972            };
1973            for a in &it.arguments {
1974                match a {
1975                    Argument::ArrowFunctionExpression(f) => {
1976                        self.callbacks.insert(f.span.start);
1977                    }
1978                    Argument::FunctionExpression(f) if f.id.is_none() => {
1979                        self.callbacks.insert(f.span.start);
1980                    }
1981                    _ => {}
1982                }
1983            }
1984            if let Some(callee) = callee.filter(|n| NODE_SPAWNS.contains(n)) {
1985                // `execSync` takes a shell command line; the others an executable and its args.
1986                let shell = callee == "execSync";
1987                let program = match it.arguments.first() {
1988                    Some(Argument::StringLiteral(s)) => {
1989                        let text = s.value.display().to_string();
1990                        if shell {
1991                            first_word(&text, false)
1992                        } else {
1993                            whole_program(&text)
1994                        }
1995                    }
1996                    Some(Argument::TemplateLiteral(t)) => t.quasis.first().and_then(|q| {
1997                        let text = q
1998                            .value
1999                            .cooked
2000                            .as_ref()
2001                            .map_or_else(|| q.value.raw.to_string(), |c| c.display().to_string());
2002                        let interpolated = !t.expressions.is_empty();
2003                        if shell {
2004                            first_word(&text, interpolated)
2005                        } else if interpolated {
2006                            None
2007                        } else {
2008                            whole_program(&text)
2009                        }
2010                    }),
2011                    _ => None,
2012                };
2013                let owner = self
2014                    .scopes
2015                    .iter()
2016                    .rev()
2017                    .find(|(_, named)| *named)
2018                    .or(self.scopes.last())
2019                    .map(|(l, _)| *l);
2020                self.out.push(SpawnCall {
2021                    scopes: self.scopes.iter().map(|(l, _)| *l).collect(),
2022                    owner,
2023                    line: self.line(it.span.start),
2024                    program,
2025                });
2026            }
2027            walk::walk_call_expression(self, it);
2028        }
2029    }
2030    let source_type =
2031        oxc_span::SourceType::from_path(path).unwrap_or_else(|_| oxc_span::SourceType::ts());
2032    let allocator = oxc_allocator::Allocator::default();
2033    let ret = oxc_parser::Parser::new(&allocator, source, source_type).parse();
2034    let mut calls = Calls {
2035        newlines: source.match_indices('\n').map(|(i, _)| i).collect(),
2036        scopes: Vec::new(),
2037        callbacks: HashSet::new(),
2038        out: Vec::new(),
2039    };
2040    calls.visit_program(&ret.program);
2041    calls.out
2042}
2043
2044/// Python's `subprocess` and `os.system` calls in a file, read with tree-sitter: through the
2045/// module under any name (`import subprocess as sp`), or a function imported from it.
2046fn python_spawn_calls(source: &str) -> Vec<SpawnCall> {
2047    use crate::lang::syntax;
2048    const SUBPROCESS: [&str; 7] = [
2049        "run",
2050        "call",
2051        "check_call",
2052        "check_output",
2053        "getoutput",
2054        "getstatusoutput",
2055        "Popen",
2056    ];
2057    let spawns = |module: &str, name: &str| {
2058        (module == "subprocess" && SUBPROCESS.contains(&name))
2059            || (module == "os" && name == "system")
2060    };
2061    let Some(tree) = syntax::parse(&tree_sitter_python::LANGUAGE.into(), source) else {
2062        return Vec::new();
2063    };
2064    let root = tree.root_node();
2065    let field = |n: tree_sitter::Node, f: &str| {
2066        n.child_by_field_name(f)
2067            .map_or("", |c| syntax::text(c, source))
2068    };
2069    let name_and_alias = |c: tree_sitter::Node| match c.kind() {
2070        "aliased_import" => (field(c, "name"), field(c, "alias")),
2071        _ => (syntax::text(c, source), syntax::text(c, source)),
2072    };
2073    let mut modules: HashMap<&str, &str> = HashMap::new();
2074    let mut imported: HashSet<&str> = HashSet::new();
2075    syntax::walk(root, |n| match n.kind() {
2076        "import_statement" => {
2077            for c in syntax::named_children(n) {
2078                let (module, alias) = name_and_alias(c);
2079                if matches!(module, "subprocess" | "os") {
2080                    modules.insert(alias, module);
2081                }
2082            }
2083        }
2084        "import_from_statement" => {
2085            let module = field(n, "module_name");
2086            let mut cursor = n.walk();
2087            for c in n.children_by_field_name("name", &mut cursor) {
2088                let (name, alias) = name_and_alias(c);
2089                if spawns(module, name) {
2090                    imported.insert(alias);
2091                }
2092            }
2093        }
2094        _ => {}
2095    });
2096    let mut out = Vec::new();
2097    syntax::walk(root, |n| {
2098        if n.kind() != "call" {
2099            return;
2100        }
2101        let Some(callee) = n.child_by_field_name("function") else {
2102            return;
2103        };
2104        let starts = match callee.kind() {
2105            "identifier" => imported.contains(syntax::text(callee, source)),
2106            "attribute" => modules
2107                .get(field(callee, "object"))
2108                .is_some_and(|m| spawns(m, field(callee, "attribute"))),
2109            _ => false,
2110        };
2111        if !starts {
2112            return;
2113        }
2114        // The functions around the call, by the line cProfile gives them: a decorated function
2115        // starts at its first decorator.
2116        let mut scopes = Vec::new();
2117        let mut up = n.parent();
2118        while let Some(p) = up {
2119            if matches!(
2120                p.kind(),
2121                "function_definition" | "class_definition" | "lambda"
2122            ) {
2123                let start = p
2124                    .parent()
2125                    .filter(|d| d.kind() == "decorated_definition")
2126                    .unwrap_or(p);
2127                scopes.push(syntax::line(start));
2128            }
2129            up = p.parent();
2130        }
2131        scopes.reverse();
2132        let program = n
2133            .child_by_field_name("arguments")
2134            .and_then(|args| {
2135                let all = syntax::named_children(args);
2136                all.iter()
2137                    .find(|a| a.kind() == "keyword_argument" && field(**a, "name") == "args")
2138                    .and_then(|a| a.child_by_field_name("value"))
2139                    .or_else(|| {
2140                        all.first()
2141                            .copied()
2142                            .filter(|a| a.kind() != "keyword_argument")
2143                    })
2144            })
2145            .and_then(|a| python_program(a, source));
2146        out.push(SpawnCall {
2147            owner: scopes.last().copied(),
2148            scopes,
2149            line: syntax::line(n),
2150            program,
2151        });
2152    });
2153    out
2154}
2155
2156/// The program a Python argument names: `"sleep 0.2"`, `["git", "log"]`, `("make",)`.
2157fn python_program(arg: tree_sitter::Node, source: &str) -> Option<String> {
2158    use crate::lang::syntax;
2159    let string = |s: tree_sitter::Node| {
2160        let parts = syntax::named_children(s);
2161        let content: String = parts
2162            .iter()
2163            .take_while(|p| p.kind() != "interpolation")
2164            .filter(|p| p.kind() == "string_content")
2165            .map(|p| syntax::text(*p, source))
2166            .collect();
2167        (content, parts.iter().any(|p| p.kind() == "interpolation"))
2168    };
2169    match arg.kind() {
2170        // An argv list: its first item is the executable, spaces and all.
2171        "list" | "tuple" => {
2172            let first = *syntax::named_children(arg).first()?;
2173            let (content, interpolated) = (first.kind() == "string").then(|| string(first))?;
2174            if interpolated {
2175                None
2176            } else {
2177                whole_program(&content)
2178            }
2179        }
2180        "string" => {
2181            let (content, interpolated) = string(arg);
2182            first_word(&content, interpolated)
2183        }
2184        _ => None,
2185    }
2186}
2187
2188pub fn markdown(r: &Report) -> String {
2189    use std::fmt::Write as _;
2190    let mut out = format!(
2191        "# Profile: `{}`\n\n{:.0} ms in all; {:.0}% of it in the repository's own code.\n\n\
2192         | Function | File | Total | Self | Calls | Unit |\n| --- | --- | ---: | ---: | ---: | --- |\n",
2193        r.command.join(" "),
2194        r.total_ms,
2195        r.repo_pct
2196    );
2197    for h in r.hot.iter().take(SHOWN) {
2198        let _ = writeln!(
2199            out,
2200            "| `{}` | `{}:{}` | {:.0}% ({:.0} ms) | {:.0} ms | {} | {} |",
2201            h.name,
2202            h.file,
2203            h.line,
2204            h.total_pct,
2205            h.total_ms,
2206            h.self_ms,
2207            h.calls.map_or_else(|| "-".into(), |c| c.to_string()),
2208            h.unit
2209                .as_deref()
2210                .map_or_else(|| "-".into(), |u| format!("`{u}`"))
2211        );
2212    }
2213    if let Some(summary) = r.child_summary() {
2214        let _ = write!(out, "\n## Child processes\n\n{summary} {CHILD_ADVICE}\n");
2215        if !r.child_processes.is_empty() {
2216            out.push_str("\n| Command | Called from | Time |\n| --- | --- | ---: |\n");
2217        }
2218        for c in &r.child_processes {
2219            let _ = writeln!(
2220                out,
2221                "| {} | `{}` (`{}:{}`) | {:.0}% ({:.0} ms) |",
2222                c.command
2223                    .as_deref()
2224                    .map_or_else(|| "-".into(), |c| format!("`{c}`")),
2225                c.function,
2226                c.file,
2227                c.line,
2228                c.share,
2229                c.ms
2230            );
2231        }
2232    }
2233    if !r.compiled.is_empty() {
2234        out.push_str(
2235            "\n## Already compiled\n\nThese run as machine code already; Rust is unlikely to make them \
2236             much faster:\n\n",
2237        );
2238        for c in &r.compiled {
2239            let _ = writeln!(out, "- `{}` (`{}:{}`): {}", c.name, c.file, c.line, c.by);
2240        }
2241    }
2242    out.push_str("\n## What to port\n\n");
2243    let mut seen = BTreeMap::new();
2244    for h in r
2245        .hot
2246        .iter()
2247        .take(SHOWN)
2248        .filter(|h| h.unit.is_some() && !is_top_level(&h.name, h.line))
2249    {
2250        if seen.insert(h.name.clone(), ()).is_some() {
2251            continue;
2252        }
2253        let _ = writeln!(
2254            out,
2255            "- **`{}`** ({:.0}%): {}",
2256            h.name, h.total_pct, h.advice
2257        );
2258    }
2259    out
2260}
2261
2262#[cfg(test)]
2263mod tests {
2264    use super::*;
2265    use serde_json::json;
2266
2267    #[test]
2268    fn compiled_code_changes_the_advice() {
2269        let root = std::env::temp_dir().join(format!("rust-anything-numba-{}", std::process::id()));
2270        let _ = std::fs::remove_dir_all(&root);
2271        std::fs::create_dir_all(root.join("sim")).unwrap();
2272        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"sim\"\n").unwrap();
2273        std::fs::write(
2274            root.join("sim/physics.py"),
2275            "from numba import njit\n\n@njit(cache=True)\ndef step(x, dt):\n    return x + dt\n\n\
2276             def run(xs):\n    out = []\n    for x in xs:\n        out.append(step(x, 0.1))\n    return out\n\n\
2277             def other(xs):\n    return [x * 2 for x in xs]\n",
2278        )
2279        .unwrap();
2280        let compiled = compiled_in(&root, Lang::Python);
2281        assert_eq!(compiled.len(), 1);
2282        assert_eq!(
2283            (compiled[0].name.as_str(), compiled[0].line, compiled[0].by),
2284            ("step", 4, "numba")
2285        );
2286        let hot = |name: &str, line: u32| Hot {
2287            name: name.into(),
2288            file: "sim/physics.py".into(),
2289            line,
2290            unit: None,
2291            exported: true,
2292            self_ms: 1.0,
2293            total_ms: 1.0,
2294            total_pct: 50.0,
2295            calls: None,
2296            ns_per_call: None,
2297            callers: Vec::new(),
2298            advice: "Port it.".into(),
2299            portable: true,
2300            js_only: None,
2301            params: vec!["x".into()],
2302            batch: None,
2303            child_pct: None,
2304        };
2305        let own = compiled_advice(&root, &hot("step", 3), &compiled).unwrap();
2306        assert!(
2307            own.starts_with("Already compiled by numba (`sim/physics.py:4`)"),
2308            "{own}"
2309        );
2310        let caller = compiled_advice(&root, &hot("run", 7), &compiled).unwrap();
2311        assert!(
2312            caller.starts_with("Port it. It calls `step` compiled by numba"),
2313            "{caller}"
2314        );
2315        assert!(compiled_advice(&root, &hot("other", 13), &compiled).is_none());
2316        assert!(compiled_in(&root, Lang::Ts).is_empty());
2317        std::fs::remove_dir_all(&root).unwrap();
2318    }
2319
2320    #[test]
2321    fn functions_bridge_keeps_in_js_are_not_offered_for_porting() {
2322        let root =
2323            std::env::temp_dir().join(format!("rust-anything-js-only-{}", std::process::id()));
2324        let _ = std::fs::remove_dir_all(&root);
2325        std::fs::create_dir_all(&root).unwrap();
2326        std::fs::write(
2327            root.join("package.json"),
2328            r#"{"name":"demo","type":"module"}"#,
2329        )
2330        .unwrap();
2331        // A typed callback in TypeScript, and the same shape in JS typed by a sibling `.d.ts`.
2332        std::fs::write(
2333            root.join("lib.ts"),
2334            "export function sumBy<T>(items: T[], pick: (item: T) => number): number {\n  \
2335             let s = 0;\n  for (const it of items) s += pick(it);\n  return s;\n}\n\
2336             export function double(n: number): number { return n * 2; }\n",
2337        )
2338        .unwrap();
2339        std::fs::write(
2340            root.join("plug.js"),
2341            "export function each(items, visit) { for (const it of items) visit(it); }\n\
2342             export function half(n) { return n / 2; }\n",
2343        )
2344        .unwrap();
2345        std::fs::write(
2346            root.join("plug.d.ts"),
2347            "export declare function each<T>(items: T[], visit: (item: T) => void): void;\n\
2348             export declare function half(n: number): number;\n",
2349        )
2350        .unwrap();
2351        let acc = |total_ms: f64| Acc {
2352            self_ms: total_ms,
2353            total_ms,
2354            ..Default::default()
2355        };
2356        let functions: HashMap<Key, Acc> = [
2357            (("lib.ts".to_string(), "sumBy".to_string(), 1), acc(60.0)),
2358            (("plug.js".to_string(), "each".to_string(), 1), acc(20.0)),
2359            (("plug.js".to_string(), "half".to_string(), 2), acc(10.0)),
2360            (("lib.ts".to_string(), "double".to_string(), 6), acc(5.0)),
2361        ]
2362        .into_iter()
2363        .collect();
2364        let r = report(
2365            &root,
2366            Lang::Ts,
2367            &["node".into(), "bench.mjs".into()],
2368            functions,
2369            0.0,
2370            100.0,
2371        );
2372        std::fs::remove_dir_all(&root).unwrap();
2373
2374        let hot = |name: &str| r.hot.iter().find(|h| h.name == name).unwrap();
2375        for name in ["sumBy", "each"] {
2376            let h = hot(name);
2377            assert_eq!(
2378                h.js_only.as_deref(),
2379                Some("takes or returns a function"),
2380                "{name}"
2381            );
2382            assert!(
2383                h.advice.starts_with(&format!("Hot, but `bridge` keeps `{name}` in TypeScript/JavaScript: takes or returns a function.")),
2384                "{}",
2385                h.advice
2386            );
2387        }
2388        for name in ["half", "double"] {
2389            let h = hot(name);
2390            assert_eq!(h.js_only, None, "{name}");
2391            assert!(h.advice.starts_with("Hot and exported by"), "{}", h.advice);
2392        }
2393        // `go` passes over the hottest functions, which `bridge` would keep in JS.
2394        assert_eq!(crate::go::pick(&r, None).unwrap().function, "half");
2395        let named = crate::go::pick(&r, Some("sumBy")).unwrap_err().to_string();
2396        assert!(named.contains("takes or returns a function"), "{named}");
2397    }
2398
2399    #[test]
2400    fn a_python_generator_is_not_offered_for_porting() {
2401        let root =
2402            std::env::temp_dir().join(format!("rust-anything-py-js-only-{}", std::process::id()));
2403        let _ = std::fs::remove_dir_all(&root);
2404        std::fs::create_dir_all(root.join("demo")).unwrap();
2405        std::fs::write(
2406            root.join("pyproject.toml"),
2407            "[project]\nname = \"demo\"\nversion = \"0.1.0\"\n",
2408        )
2409        .unwrap();
2410        std::fs::write(root.join("demo/__init__.py"), "").unwrap();
2411        std::fs::write(
2412            root.join("demo/mod.py"),
2413            "def squares(xs):\n    for x in xs:\n        yield x * x\n\n\n\
2414             def collatz(n):\n    steps = 0\n    while n != 1:\n        n = n // 2 if n % 2 == 0 else 3 * n + 1\n        steps += 1\n    return steps\n",
2415        )
2416        .unwrap();
2417        let acc = |total_ms: f64| Acc {
2418            self_ms: total_ms,
2419            total_ms,
2420            ..Default::default()
2421        };
2422        let functions: HashMap<Key, Acc> = [
2423            (
2424                ("demo/mod.py".to_string(), "squares".to_string(), 1),
2425                acc(60.0),
2426            ),
2427            (
2428                ("demo/mod.py".to_string(), "collatz".to_string(), 6),
2429                acc(30.0),
2430            ),
2431        ]
2432        .into_iter()
2433        .collect();
2434        let r = report(
2435            &root,
2436            Lang::Python,
2437            &["python3".into(), "bench.py".into()],
2438            functions,
2439            0.0,
2440            100.0,
2441        );
2442        std::fs::remove_dir_all(&root).unwrap();
2443
2444        let squares = r.hot.iter().find(|h| h.name == "squares").unwrap();
2445        assert!(
2446            squares
2447                .js_only
2448                .as_deref()
2449                .is_some_and(|r| r.starts_with("generator")),
2450            "{:?}",
2451            squares.js_only
2452        );
2453        assert!(
2454            squares
2455                .advice
2456                .starts_with("Hot, but `bridge` keeps `squares` in Python: generator"),
2457            "{}",
2458            squares.advice
2459        );
2460        assert_eq!(crate::go::pick(&r, None).unwrap().function, "collatz");
2461    }
2462
2463    #[test]
2464    fn a_redefined_python_function_is_judged_by_the_definition_that_ran() {
2465        let root =
2466            std::env::temp_dir().join(format!("rust-anything-py-redef-{}", std::process::id()));
2467        let _ = std::fs::remove_dir_all(&root);
2468        std::fs::create_dir_all(root.join("demo")).unwrap();
2469        std::fs::write(
2470            root.join("pyproject.toml"),
2471            "[project]\nname = \"demo\"\nversion = \"0.1.0\"\n",
2472        )
2473        .unwrap();
2474        std::fs::write(root.join("demo/__init__.py"), "").unwrap();
2475        std::fs::write(
2476            root.join("demo/mod.py"),
2477            "def calc(xs):\n    for x in xs:\n        yield x * x\n\n\n\
2478             def calc(n):\n    steps = 0\n    while n != 1:\n        n = n // 2 if n % 2 == 0 else 3 * n + 1\n        steps += 1\n    return steps\n",
2479        )
2480        .unwrap();
2481        let functions: HashMap<Key, Acc> = [(
2482            ("demo/mod.py".to_string(), "calc".to_string(), 6),
2483            Acc {
2484                self_ms: 90.0,
2485                total_ms: 90.0,
2486                ..Default::default()
2487            },
2488        )]
2489        .into_iter()
2490        .collect();
2491        let r = report(
2492            &root,
2493            Lang::Python,
2494            &["python3".into(), "bench.py".into()],
2495            functions,
2496            0.0,
2497            100.0,
2498        );
2499        std::fs::remove_dir_all(&root).unwrap();
2500
2501        let calc = r.hot.iter().find(|h| h.name == "calc").unwrap();
2502        assert_eq!(calc.js_only, None, "{}", calc.advice);
2503        assert_eq!(crate::go::pick(&r, None).unwrap().function, "calc");
2504    }
2505
2506    #[test]
2507    fn frames_outside_user_code_are_dropped() {
2508        let root = Path::new("/repo");
2509        assert_eq!(relative(root, "node:internal/main"), None);
2510        assert_eq!(relative(root, "file:///repo/node_modules/x/index.js"), None);
2511        assert_eq!(relative(root, "/usr/lib/python3.13/json/__init__.py"), None);
2512        assert_eq!(
2513            relative(root, "file:///repo/src/fuzzy.ts").as_deref(),
2514            Some("src/fuzzy.ts")
2515        );
2516        // A workload script elsewhere is user code, shown with its full path.
2517        assert_eq!(
2518            relative(root, "/tmp/bench.ts").as_deref(),
2519            Some("/tmp/bench.ts")
2520        );
2521        assert!(in_repo(root, "src/fuzzy.ts") && !in_repo(root, "/tmp/bench.ts"));
2522    }
2523
2524    #[test]
2525    fn windows_file_urls_resolve_against_the_project_root() {
2526        // Node on Windows writes `file:///C:/...`; the root is `C:\...` (here `C:/...`, which
2527        // splits into the same components on every platform).
2528        let root = Path::new("C:/repo");
2529        assert_eq!(
2530            relative(root, "file:///C:/repo/src/fuzzy.ts").as_deref(),
2531            Some("src/fuzzy.ts")
2532        );
2533        assert_eq!(
2534            relative(root, "file:///C:/repo/node_modules/x/index.js"),
2535            None
2536        );
2537        let bench = relative(root, "file:///C:/Users/me/AppData/Local/Temp/bench.mjs");
2538        assert_eq!(
2539            bench.as_deref(),
2540            Some("C:/Users/me/AppData/Local/Temp/bench.mjs")
2541        );
2542        assert!(
2543            in_repo(root, "src/fuzzy.ts")
2544                && !in_repo(root, "C:/Users/me/AppData/Local/Temp/bench.mjs")
2545        );
2546        assert_eq!(
2547            crate::walk::file_url_path("file:///C:/My%20Repo/a.ts", root).as_deref(),
2548            Some("C:/My Repo/a.ts")
2549        );
2550        assert_eq!(
2551            crate::walk::file_url_path("file:///repo/a.ts", root).as_deref(),
2552            Some("/repo/a.ts")
2553        );
2554    }
2555
2556    #[test]
2557    fn a_unix_root_that_looks_like_a_drive_path_keeps_its_leading_slash() {
2558        let root = Path::new("/C:/repo");
2559        assert_eq!(
2560            relative(root, "file:///C:/repo/src/a.ts").as_deref(),
2561            Some("src/a.ts")
2562        );
2563        assert_eq!(
2564            crate::walk::file_url_path("file:///C:/repo/src/a.ts", root).as_deref(),
2565            Some("/C:/repo/src/a.ts")
2566        );
2567    }
2568
2569    #[cfg(unix)]
2570    #[test]
2571    fn a_drive_looking_folder_inside_a_unix_root_stays_in_the_repository() {
2572        let root = std::env::temp_dir().join(format!("ra-profile-drive-{}", std::process::id()));
2573        std::fs::create_dir_all(root.join("C:/src")).unwrap();
2574        std::fs::write(root.join("C:/src/hot.mjs"), "").unwrap();
2575        let url = format!("file://{}/C:/src/hot.mjs", root.display());
2576        let key = relative(&root, &url);
2577        assert_eq!(key.as_deref(), Some("C:/src/hot.mjs"));
2578        assert!(in_repo(&root, &key.unwrap()));
2579        // A Windows drive path that does not match the root stays out of the repository.
2580        let other = relative(&root, "file:///C:/Users/me/bench.mjs");
2581        assert_eq!(other.as_deref(), Some("/C:/Users/me/bench.mjs"));
2582        assert!(!in_repo(&root, "C:/Users/me/bench.mjs"));
2583        std::fs::remove_dir_all(&root).unwrap();
2584    }
2585
2586    #[test]
2587    fn a_relative_script_path_under_the_repository_is_kept() {
2588        let root = std::env::temp_dir().join(format!("ra-profile-rel-{}", std::process::id()));
2589        std::fs::create_dir_all(&root).unwrap();
2590        std::fs::write(root.join("bench.py"), "").unwrap();
2591        assert_eq!(relative(&root, "bench.py").as_deref(), Some("bench.py"));
2592        assert_eq!(relative(&root, "./bench.py").as_deref(), Some("bench.py"));
2593        assert_eq!(relative(&root, "missing.py"), None);
2594        assert_eq!(relative(&root, "<frozen runpy>"), None);
2595        assert_eq!(relative(&root, "~"), None);
2596        std::fs::remove_dir_all(&root).unwrap();
2597    }
2598
2599    fn node(id: u64, name: &str, url: &str, line: i64, hits: u64, children: &[u64]) -> Value {
2600        json!({ "id": id, "hitCount": hits, "children": children,
2601                "callFrame": { "functionName": name, "url": url, "lineNumber": line - 1 } })
2602    }
2603
2604    #[test]
2605    fn node_writes_profile_to_a_temp_path_with_spaces() {
2606        if !Command::new("node")
2607            .arg("--version")
2608            .status()
2609            .is_ok_and(|s| s.success())
2610        {
2611            return;
2612        }
2613        let dir = crate::app::temp_dir("profile with spaces").unwrap();
2614        let root = dir.canonicalize().unwrap();
2615        let command = ["node".into(), "-e".into(), "console.log('workload')".into()];
2616        let result = super::node(&root, &command, &root);
2617        std::fs::remove_dir_all(dir).unwrap();
2618        assert!(result.unwrap().2 > 0.0);
2619    }
2620
2621    #[test]
2622    fn cpuprofile_times_and_callers() {
2623        let f = "file:///repo/src/search.ts";
2624        // (root) -> matched -> (anonymous) -> fuzzyScore -> fuzzyScore (recursion); 1 ms a sample.
2625        let profile = json!({
2626            "startTime": 0, "endTime": 10_000, "samples": vec![0; 10],
2627            "nodes": [
2628                node(1, "(root)", "", 0, 0, &[2]),
2629                node(2, "matched", f, 9, 1, &[3]),
2630                node(3, "", f, 10, 1, &[4]),
2631                node(4, "fuzzyScore", f, 2, 5, &[5]),
2632                node(5, "fuzzyScore", f, 2, 3, &[]),
2633            ],
2634        });
2635        let mut functions = HashMap::new();
2636        let ms = merge_cpuprofile(Path::new("/repo"), &profile, &mut functions, &mut 0.0);
2637        assert_eq!(ms, 10.0);
2638        let key = |n: &str, l: u32| ("src/search.ts".to_string(), n.to_string(), l);
2639        let fuzzy = &functions[&key("fuzzyScore", 2)];
2640        assert_eq!(
2641            (fuzzy.self_ms, fuzzy.total_ms),
2642            (8.0, 8.0),
2643            "recursion counts once"
2644        );
2645        // The caller is the named function, not the arrow callback in between.
2646        assert_eq!(
2647            fuzzy.callers.keys().collect::<Vec<_>>(),
2648            [&key("matched", 9)]
2649        );
2650        assert_eq!(functions[&key("matched", 9)].total_ms, 10.0);
2651        assert!(functions.contains_key(&key("(anonymous):10", 10)));
2652    }
2653
2654    #[test]
2655    fn cpuprofile_blocking_child_processes_go_to_the_caller() {
2656        let f = "file:///repo/lib.js";
2657        let cp = "node:child_process";
2658        // main -> runAll -> execSync -> spawnSync (6 ms waiting); main -> crunch (3 ms);
2659        // main -> spawn (async: starting it is all the profile sees).
2660        let profile = json!({
2661            "startTime": 0, "endTime": 10_000, "samples": vec![0; 10],
2662            "nodes": [
2663                node(1, "(root)", "", 0, 0, &[2]),
2664                node(2, "main", f, 1, 0, &[3, 6, 7]),
2665                node(3, "runAll", f, 3, 0, &[4]),
2666                // runAll's `xs.map((x) => execSync(...))`: the wait is runAll's, as callers are.
2667                node(4, "", f, 4, 0, &[8]),
2668                node(8, "execSync", cp, 945, 0, &[5]),
2669                node(5, "spawnSync", cp, 823, 6, &[]),
2670                node(6, "crunch", f, 11, 3, &[]),
2671                node(7, "spawn", cp, 700, 1, &[]),
2672            ],
2673        });
2674        let mut functions = HashMap::new();
2675        merge_cpuprofile(Path::new("/repo"), &profile, &mut functions, &mut 0.0);
2676        let at = |n: &str, l: u32| &functions[&("lib.js".to_string(), n.to_string(), l)];
2677        assert_eq!(
2678            (at("runAll", 3).spawn_ms, at("runAll", 3).waits_ms),
2679            (6.0, 6.0)
2680        );
2681        assert_eq!((at("main", 1).spawn_ms, at("main", 1).waits_ms), (0.0, 6.0));
2682        assert_eq!(
2683            at("main", 1).total_ms,
2684            10.0,
2685            "the wait is still the caller's time"
2686        );
2687        assert_eq!(
2688            (at("crunch", 11).spawn_ms, at("crunch", 11).waits_ms),
2689            (0.0, 0.0)
2690        );
2691        let callback = at("(anonymous):4", 4);
2692        assert_eq!((callback.spawn_ms, callback.waits_ms), (0.0, 6.0));
2693    }
2694
2695    #[test]
2696    fn python_waits_on_subprocess_go_to_the_repository_caller() {
2697        let root = Path::new("/repo");
2698        let sp = "/usr/lib64/python3.12/subprocess.py";
2699        let lib = "/repo/.venv/lib/python3.12/site-packages/gitlib/cmd.py";
2700        let entry = |file: &str, name: &str, line: u64, total: f64, callers: Value| {
2701            json!({"file": file, "line": line, "name": name, "calls": 1, "self": 0.0,
2702                   "total": total, "stdlib": file.starts_with("/usr/lib64/python3.12/"),
2703                   "callers": callers})
2704        };
2705        let caller = |file: &str, name: &str, line: u64, total: f64| json!({"file": file, "line": line, "name": name, "calls": 1, "total": total});
2706        let (bench, tool) = ("/repo/bench.py", "/repo/tool.py");
2707        let entries = [
2708            entry(bench, "<module>", 1, 200.0, json!([])),
2709            entry(
2710                tool,
2711                "run_all",
2712                5,
2713                90.0,
2714                json!([caller(bench, "<module>", 1, 90.0)]),
2715            ),
2716            entry(
2717                tool,
2718                "shell_all",
2719                12,
2720                10.0,
2721                json!([caller(bench, "<module>", 1, 10.0)]),
2722            ),
2723            entry(
2724                sp,
2725                "run",
2726                464,
2727                85.0,
2728                json!([caller(tool, "run_all", 5, 85.0)]),
2729            ),
2730            // Called from `subprocess.run`, not from user code: counted once, through `run`.
2731            entry(
2732                sp,
2733                "communicate",
2734                1090,
2735                84.0,
2736                json!([caller(sp, "run", 464, 84.0)]),
2737            ),
2738            entry(
2739                "~",
2740                "<built-in method posix.system>",
2741                0,
2742                9.0,
2743                json!([caller(tool, "shell_all", 12, 9.0)]),
2744            ),
2745            // Mutual recursion, a wait at the bottom: the wait is not fed around the cycle, and
2746            // only the function that starts it is known to wait.
2747            entry(
2748                tool,
2749                "even",
2750                20,
2751                40.0,
2752                json!([
2753                    caller(bench, "<module>", 1, 40.0),
2754                    caller(tool, "odd", 25, 40.0)
2755                ]),
2756            ),
2757            entry(
2758                tool,
2759                "odd",
2760                25,
2761                40.0,
2762                json!([caller(tool, "even", 20, 40.0)]),
2763            ),
2764            entry(
2765                sp,
2766                "check_output",
2767                400,
2768                2.0,
2769                json!([caller(tool, "even", 20, 2.0)]),
2770            ),
2771            // A library between user code and the wait: `fetch` -> `gitlib.execute` ->
2772            // `with Popen(...)`, which waits in `__exit__`.
2773            entry(
2774                tool,
2775                "fetch",
2776                30,
2777                30.0,
2778                json!([caller(bench, "<module>", 1, 30.0)]),
2779            ),
2780            entry(
2781                lib,
2782                "execute",
2783                10,
2784                30.0,
2785                json!([caller(tool, "fetch", 30, 30.0)]),
2786            ),
2787            entry(
2788                sp,
2789                "__exit__",
2790                1100,
2791                25.0,
2792                json!([caller(lib, "execute", 10, 25.0)]),
2793            ),
2794            // A user function recursing through a library (`ast.NodeVisitor`): its wait is its
2795            // own, once.
2796            entry(
2797                tool,
2798                "visit_Call",
2799                40,
2800                12.0,
2801                json!([
2802                    caller(bench, "<module>", 1, 12.0),
2803                    caller("/usr/lib64/python3.12/ast.py", "visit", 410, 12.0)
2804                ]),
2805            ),
2806            entry(
2807                "/usr/lib64/python3.12/ast.py",
2808                "visit",
2809                410,
2810                12.0,
2811                json!([caller(
2812                    "/usr/lib64/python3.12/ast.py",
2813                    "generic_visit",
2814                    420,
2815                    12.0
2816                )]),
2817            ),
2818            entry(
2819                "/usr/lib64/python3.12/ast.py",
2820                "generic_visit",
2821                420,
2822                12.0,
2823                json!([caller(tool, "visit_Call", 40, 12.0)]),
2824            ),
2825            entry(
2826                sp,
2827                "run",
2828                464,
2829                10.0,
2830                json!([caller(tool, "visit_Call", 40, 10.0)]),
2831            ),
2832            // A repository module that happens to be called `subprocess.py` is user code.
2833            entry(
2834                "/repo/pkg/subprocess.py",
2835                "run",
2836                3,
2837                20.0,
2838                json!([caller(bench, "<module>", 1, 20.0)]),
2839            ),
2840        ];
2841        let (functions, _) = ingest_entries(root, &entries);
2842        let at = |file: &str, n: &str, l: u32| {
2843            let a = &functions[&(file.to_string(), n.to_string(), l)];
2844            (a.spawn_ms, a.waits_ms)
2845        };
2846        assert_eq!(at("tool.py", "run_all", 5), (85.0, 85.0));
2847        assert_eq!(at("tool.py", "shell_all", 12), (9.0, 9.0));
2848        assert_eq!(at("tool.py", "even", 20), (2.0, 2.0));
2849        assert_eq!(at("tool.py", "odd", 25), (0.0, 0.0));
2850        assert_eq!(at("tool.py", "fetch", 30), (25.0, 25.0));
2851        assert_eq!(at("tool.py", "visit_Call", 40), (10.0, 10.0));
2852        assert_eq!(
2853            at("bench.py", "<module>", 1),
2854            (0.0, 85.0 + 9.0 + 2.0 + 25.0 + 10.0)
2855        );
2856        assert_eq!(at("pkg/subprocess.py", "run", 3), (0.0, 0.0));
2857        assert_eq!(
2858            functions[&("pkg/subprocess.py".into(), "run".into(), 3)].total_ms,
2859            20.0
2860        );
2861        assert!(
2862            !functions
2863                .keys()
2864                .any(|k| k.0.ends_with("cmd.py") || k.0.contains("lib64")),
2865            "{:?}",
2866            functions.keys()
2867        );
2868        // Each wait is started by one user function, so the parts add up.
2869        let started: f64 = functions.values().map(|a| a.spawn_ms).sum();
2870        assert_eq!(started, 85.0 + 9.0 + 2.0 + 25.0 + 10.0);
2871    }
2872
2873    #[test]
2874    fn time_waiting_on_child_processes_is_reported_and_not_offered_for_porting() {
2875        let root =
2876            std::env::temp_dir().join(format!("rust-anything-children-{}", std::process::id()));
2877        let _ = std::fs::remove_dir_all(&root);
2878        std::fs::create_dir_all(&root).unwrap();
2879        std::fs::write(
2880            root.join("package.json"),
2881            r#"{"name":"demo","type":"module"}"#,
2882        )
2883        .unwrap();
2884        std::fs::write(
2885            root.join("lib.js"),
2886            "import { execSync } from \"node:child_process\";\n\n\
2887             export function runAll(n) {\n  let out = 0;\n  for (let i = 0; i < n; i++) {\n    \
2888             out += execSync(\"sleep 0.2\").length;\n  }\n  return out;\n}\n\n\
2889             export function crunch(n) {\n  let s = 0;\n  for (let i = 0; i < n; i++) s = (s + i * i) % 1000003;\n  return s;\n}\n",
2890        )
2891        .unwrap();
2892        let build = |wait: f64, cpu: f64| {
2893            let functions: HashMap<Key, Acc> = [
2894                (
2895                    ("lib.js".to_string(), "runAll".to_string(), 3),
2896                    Acc {
2897                        total_ms: wait,
2898                        spawn_ms: wait,
2899                        waits_ms: wait,
2900                        ..Default::default()
2901                    },
2902                ),
2903                (
2904                    ("lib.js".to_string(), "crunch".to_string(), 11),
2905                    Acc {
2906                        self_ms: cpu,
2907                        total_ms: cpu,
2908                        ..Default::default()
2909                    },
2910                ),
2911            ]
2912            .into_iter()
2913            .collect();
2914            report(
2915                &root,
2916                Lang::Ts,
2917                &["node".into(), "bench.mjs".into()],
2918                functions,
2919                0.0,
2920                100.0,
2921            )
2922        };
2923        let r = build(40.0, 55.0);
2924        let r_spawns = build(60.0, 30.0);
2925        let quiet = build(0.0, 90.0);
2926        assert_eq!(
2927            (r.child_pct, r_spawns.child_pct, quiet.child_pct),
2928            (40.0, 60.0, 0.0)
2929        );
2930        std::fs::remove_dir_all(&root).unwrap();
2931
2932        let c = &r.child_processes[0];
2933        assert_eq!(
2934            (
2935                c.command.as_deref(),
2936                c.file.as_str(),
2937                c.line,
2938                c.function.as_str(),
2939                c.share
2940            ),
2941            (Some("sleep"), "lib.js", 6, "runAll", 40.0)
2942        );
2943        let run_all = r.hot.iter().find(|h| h.name == "runAll").unwrap();
2944        assert_eq!(run_all.child_pct, Some(100.0));
2945        assert!(run_all.advice.contains(CHILD_ADVICE), "{}", run_all.advice);
2946        assert_eq!(
2947            r.hot.iter().find(|h| h.name == "crunch").unwrap().child_pct,
2948            None
2949        );
2950        let md = markdown(&r);
2951        assert!(
2952            md.contains("## Child processes\n\n40% of the run waits on child processes (`sleep` from `lib.js:6`). Porting code will not speed this up"),
2953            "{md}"
2954        );
2955        assert!(
2956            md.contains("| `sleep` | `runAll` (`lib.js:6`) | 40% (40 ms) |"),
2957            "{md}"
2958        );
2959        let json = serde_json::to_value(&r).unwrap();
2960        assert_eq!(json["child_processes"][0]["command"], "sleep");
2961        // `go` passes over the waiting function; named, it says why.
2962        assert_eq!(crate::go::pick(&r, None).unwrap().function, "crunch");
2963        let named = crate::go::pick(&r, Some("runAll")).unwrap_err().to_string();
2964        assert!(
2965            named.contains("100% of its time waiting on child processes"),
2966            "{named}"
2967        );
2968        // When child processes take most of the run, `go` stops unless a function is named.
2969        let stop = crate::go::pick(&r_spawns, None).unwrap_err().to_string();
2970        assert!(
2971            stop.starts_with("60% of the run waits on child processes"),
2972            "{stop}"
2973        );
2974        assert!(stop.contains("--function"), "{stop}");
2975        assert_eq!(
2976            crate::go::pick(&r_spawns, Some("crunch")).unwrap().function,
2977            "crunch"
2978        );
2979        // Nothing waits: no section, no field.
2980        assert!(quiet.child_processes.is_empty());
2981        assert!(!markdown(&quiet).contains("Child processes"));
2982        assert!(
2983            serde_json::to_value(&quiet)
2984                .unwrap()
2985                .get("child_processes")
2986                .is_none()
2987        );
2988        assert!(
2989            serde_json::to_value(&quiet)
2990                .unwrap()
2991                .get("child_pct")
2992                .is_none()
2993        );
2994        assert!(
2995            serde_json::to_value(&quiet).unwrap()["hot"][0]
2996                .get("child_pct")
2997                .is_none()
2998        );
2999    }
3000
3001    #[test]
3002    fn runtime_library_paths_are_matched_by_component() {
3003        let root = Path::new("/repo");
3004        assert_eq!(
3005            relative(root, "/repo/lib64/python3_tools/work.py").as_deref(),
3006            Some("lib64/python3_tools/work.py")
3007        );
3008        assert_eq!(
3009            relative(root, "/repo/lib/python3_tools/work.py").as_deref(),
3010            Some("lib/python3_tools/work.py")
3011        );
3012        for installed in [
3013            "/usr/lib64/python3.12/subprocess.py",
3014            "/usr/lib/python3.9/os.py",
3015            "/usr/lib/python3/dist-packages/yaml/__init__.py",
3016            "/usr/lib/python3/apt/package.py",
3017        ] {
3018            assert_eq!(relative(root, installed), None, "{installed}");
3019        }
3020    }
3021
3022    #[test]
3023    fn cpuprofile_waits_with_no_user_frame_still_count_for_the_run() {
3024        let lib = "file:///repo/node_modules/timers-lib/index.js";
3025        let cp = "node:child_process";
3026        // A library's timer callback blocks in execSync for 7 ms; no user frame is on the stack.
3027        let profile = json!({
3028            "startTime": 0, "endTime": 10_000, "samples": vec![0; 10],
3029            "nodes": [
3030                node(1, "(root)", "", 0, 0, &[2, 6]),
3031                node(2, "tick", lib, 3, 0, &[3]),
3032                node(3, "execSync", cp, 945, 0, &[4]),
3033                node(4, "spawnSync", cp, 823, 7, &[]),
3034                node(6, "main", "file:///repo/app.js", 1, 0, &[7]),
3035                node(7, "execSync", cp, 945, 2, &[]),
3036            ],
3037        });
3038        let mut functions = HashMap::new();
3039        let mut unowned = 0.0;
3040        merge_cpuprofile(Path::new("/repo"), &profile, &mut functions, &mut unowned);
3041        assert_eq!(unowned, 7.0, "only the wait no user function owns");
3042        assert_eq!(
3043            functions[&("app.js".to_string(), "main".to_string(), 1)].spawn_ms,
3044            2.0
3045        );
3046        let r = report(
3047            Path::new("/nonexistent-rust-anything"),
3048            Lang::Ts,
3049            &["node".into()],
3050            functions,
3051            unowned,
3052            10.0,
3053        );
3054        assert_eq!(r.child_pct, 90.0);
3055    }
3056
3057    #[test]
3058    fn python_waits_come_from_the_standard_library_only() {
3059        let root = Path::new("/repo");
3060        let sp = "/usr/lib/python3.12/subprocess.py";
3061        let fake = "/repo/.venv/lib/python3.12/site-packages/runner/subprocess.py";
3062        let lib = "/repo/.venv/lib/python3.12/site-packages/sched/jobs.py";
3063        let entry = |file: &str, name: &str, total: f64, stdlib: bool, callers: Value| {
3064            json!({"file": file, "line": 1, "name": name, "calls": 1, "self": 0.0,
3065                   "total": total, "stdlib": stdlib, "callers": callers})
3066        };
3067        let caller = |file: &str, name: &str, total: f64| json!({"file": file, "line": 1, "name": name, "calls": 1, "total": total});
3068        let entries = [
3069            entry("/repo/app.py", "crunch", 50.0, false, json!([])),
3070            // A dependency's own `subprocess.py` with a CPU-bound `run`.
3071            entry(
3072                fake,
3073                "run",
3074                45.0,
3075                false,
3076                json!([caller("/repo/app.py", "crunch", 45.0)]),
3077            ),
3078            // A library job with no user frame above it waits 20 ms.
3079            entry(lib, "job", 20.0, false, json!([])),
3080            entry(sp, "run", 20.0, true, json!([caller(lib, "job", 20.0)])),
3081        ];
3082        let (functions, unowned) = ingest_entries(root, &entries);
3083        let crunch = &functions[&("app.py".to_string(), "crunch".to_string(), 1)];
3084        assert_eq!((crunch.spawn_ms, crunch.waits_ms), (0.0, 0.0));
3085        assert_eq!(unowned, 20.0);
3086    }
3087
3088    #[test]
3089    fn shared_helpers_and_recursion_do_not_confirm_a_wait() {
3090        let root = Path::new("/repo");
3091        let sp = "/usr/lib/python3.12/subprocess.py";
3092        let entry = |name: &str, total: f64, callers: Value| {
3093            json!({"file": "/repo/app.py", "line": 1, "name": name, "calls": 1, "self": 0.0,
3094                   "total": total, "stdlib": false, "callers": callers})
3095        };
3096        let caller = |name: &str, total: f64| json!({"file": "/repo/app.py", "line": 1, "name": name, "calls": 1, "total": total});
3097        let spawn = |total: f64, by: &str| {
3098            json!({"file": sp, "line": 506, "name": "run", "calls": 1, "self": 0.0,
3099                   "total": total, "stdlib": true, "callers": [caller(by, total)]})
3100        };
3101        let entries = [
3102            entry("<module>", 400.0, json!([])),
3103            // `parse` runs `helper` for 80 ms of CPU, `fetch` for 80 ms of waiting.
3104            entry("parse", 80.0, json!([caller("<module>", 80.0)])),
3105            entry("fetch", 80.0, json!([caller("<module>", 80.0)])),
3106            entry(
3107                "helper",
3108                160.0,
3109                json!([caller("parse", 80.0), caller("fetch", 80.0)]),
3110            ),
3111            spawn(80.0, "helper"),
3112        ];
3113        let (functions, _) = ingest_entries(root, &entries);
3114        let waits = |n: &str| functions[&("app.py".to_string(), n.to_string(), 1)].waits_ms;
3115        assert_eq!(waits("helper"), 80.0);
3116        assert_eq!(waits("parse"), 0.0, "no wait is confirmed under parse");
3117
3118        // One call of `a` waits 60 ms; `a -> b` and `b -> a` only compute.
3119        let entries = [
3120            entry("<module>", 200.0, json!([])),
3121            entry(
3122                "a",
3123                100.0,
3124                json!([caller("<module>", 100.0), caller("b", 30.0)]),
3125            ),
3126            entry("b", 80.0, json!([caller("a", 80.0)])),
3127            spawn(60.0, "a"),
3128        ];
3129        let (functions, _) = ingest_entries(root, &entries);
3130        let waits = |n: &str| functions[&("app.py".to_string(), n.to_string(), 1)].waits_ms;
3131        assert_eq!((waits("a"), waits("b")), (60.0, 0.0));
3132    }
3133
3134    #[test]
3135    fn go_looks_past_the_rows_the_report_shows() {
3136        let root = std::env::temp_dir().join(format!("rust-anything-rows-{}", std::process::id()));
3137        let _ = std::fs::remove_dir_all(&root);
3138        std::fs::create_dir_all(&root).unwrap();
3139        std::fs::write(
3140            root.join("package.json"),
3141            r#"{"name":"demo","type":"module"}"#,
3142        )
3143        .unwrap();
3144        std::fs::write(
3145            root.join("lib.js"),
3146            "export function parse(text) {\n  return text.split(\",\").length;\n}\n",
3147        )
3148        .unwrap();
3149        let mut functions: HashMap<Key, Acc> = (0..25)
3150            .map(|i| {
3151                (
3152                    ("lib.js".to_string(), format!("wait{i}"), 100 + i),
3153                    Acc {
3154                        total_ms: 40.0,
3155                        waits_ms: 40.0,
3156                        spawn_ms: if i == 0 { 40.0 } else { 0.0 },
3157                        ..Default::default()
3158                    },
3159                )
3160            })
3161            .collect();
3162        functions.insert(
3163            ("lib.js".to_string(), "parse".to_string(), 1),
3164            Acc {
3165                self_ms: 30.0,
3166                total_ms: 30.0,
3167                ..Default::default()
3168            },
3169        );
3170        let r = report(&root, Lang::Ts, &["node".into()], functions, 0.0, 100.0);
3171        std::fs::remove_dir_all(&root).unwrap();
3172        let json = serde_json::to_value(&r).unwrap();
3173        assert_eq!(json["hot"].as_array().unwrap().len(), 25);
3174        assert!(!markdown(&r).contains("`parse`"));
3175        assert_eq!(crate::go::pick(&r, None).unwrap().function, "parse");
3176    }
3177
3178    #[test]
3179    fn a_node_that_refuses_the_option_is_profiled_through_arguments() {
3180        let dir = Path::new("/tmp/prof dir");
3181        let cmd = |c: &[&str]| c.iter().map(|s| s.to_string()).collect::<Vec<_>>();
3182
3183        // Node 22.14 refuses --cpu-prof in NODE_OPTIONS, so a `node` command gets it as arguments.
3184        let launch = node_launch(
3185            &cmd(&["node", "app.mjs", "--n", "3"]),
3186            Some("v22.14.0"),
3187            dir,
3188            "",
3189        )
3190        .unwrap();
3191        assert_eq!(
3192            launch,
3193            NodeLaunch {
3194                args: cmd(&[
3195                    "--cpu-prof",
3196                    "--cpu-prof-dir=/tmp/prof dir",
3197                    "app.mjs",
3198                    "--n",
3199                    "3"
3200                ]),
3201                node_options: None,
3202            }
3203        );
3204        let by_path = node_launch(
3205            &cmd(&["/usr/bin/node", "app.mjs"]),
3206            Some("v20.0.0"),
3207            dir,
3208            "",
3209        )
3210        .unwrap();
3211        assert_eq!(by_path.args[0], "--cpu-prof");
3212
3213        // A wrapper starts node itself, so only NODE_OPTIONS could reach it: say why it cannot.
3214        let err =
3215            node_launch(&cmd(&["npx", "tsx", "app.ts"]), Some("v22.14.0"), dir, "").unwrap_err();
3216        let err = err.to_string();
3217        assert!(
3218            err.contains("v22.14.0") && err.contains("`npx`") && err.contains("`node` directly"),
3219            "{err}"
3220        );
3221
3222        // A node that accepts it, or one that could not be asked, keeps NODE_OPTIONS and what was in it.
3223        let launch = node_launch(
3224            &cmd(&["npm", "run", "bench"]),
3225            None,
3226            dir,
3227            "--max-old-space-size=4096",
3228        )
3229        .unwrap();
3230        assert_eq!(launch.args, cmd(&["run", "bench"]));
3231        assert_eq!(
3232            launch.node_options.as_deref(),
3233            Some("--max-old-space-size=4096 --cpu-prof --cpu-prof-dir=\"/tmp/prof dir\"")
3234        );
3235    }
3236
3237    #[test]
3238    fn the_node_is_asked_where_the_workload_runs_and_without_node_options() {
3239        // In the workload's directory a relative `./bin/node`, or a version manager's shim, is
3240        // the node the workload gets. A `--require` in NODE_OPTIONS must run once, in the workload.
3241        let root = Path::new("/repo");
3242        let probe = cpu_prof_probe("./bin/node", root);
3243        assert_eq!(probe.get_program(), "./bin/node");
3244        assert_eq!(probe.get_current_dir(), Some(root));
3245        assert!(
3246            probe
3247                .get_envs()
3248                .any(|(key, value)| key == "NODE_OPTIONS" && value.is_none()),
3249            "{probe:?}"
3250        );
3251    }
3252
3253    #[test]
3254    fn a_script_top_level_is_not_offered_for_porting() {
3255        let root = std::env::temp_dir().join(format!("rust-anything-top-{}", std::process::id()));
3256        let _ = std::fs::remove_dir_all(&root);
3257        std::fs::create_dir_all(&root).unwrap();
3258        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"lev\"\n").unwrap();
3259        std::fs::write(
3260            root.join("lib.py"),
3261            "def lev(a, b):\n    return abs(len(a) - len(b))\n",
3262        )
3263        .unwrap();
3264        std::fs::write(
3265            root.join("app.py"),
3266            "from lib import lev\n\nfor _ in range(3000):\n    lev(\"kitten\", \"sitting\")\n",
3267        )
3268        .unwrap();
3269        let functions: HashMap<Key, Acc> = [
3270            (
3271                ("app.py".to_string(), "<module>".to_string(), 1),
3272                Acc {
3273                    self_ms: 1.0,
3274                    total_ms: 118.0,
3275                    calls: Some(1),
3276                    ..Default::default()
3277                },
3278            ),
3279            (
3280                ("lib.py".to_string(), "lev".to_string(), 1),
3281                Acc {
3282                    self_ms: 76.0,
3283                    total_ms: 116.0,
3284                    calls: Some(3000),
3285                    ..Default::default()
3286                },
3287            ),
3288        ]
3289        .into_iter()
3290        .collect();
3291        let r = report(
3292            &root,
3293            Lang::Python,
3294            &["python3".into()],
3295            functions,
3296            0.0,
3297            274.0,
3298        );
3299        std::fs::remove_dir_all(&root).unwrap();
3300        let top = r
3301            .hot
3302            .iter()
3303            .find(|h| h.name == "<module>")
3304            .expect("the top level is still measured");
3305        assert!(
3306            !top.advice.contains("port the exported function"),
3307            "advice for a top level: {}",
3308            top.advice
3309        );
3310        let to_port = markdown(&r);
3311        let to_port = to_port.split("## What to port").nth(1).expect("section");
3312        assert!(!to_port.contains("`<module>`"), "{to_port}");
3313        assert!(to_port.contains("`lev`"), "{to_port}");
3314    }
3315
3316    #[test]
3317    fn a_top_level_caller_is_not_offered_for_porting() {
3318        let root =
3319            std::env::temp_dir().join(format!("rust-anything-top-caller-{}", std::process::id()));
3320        let _ = std::fs::remove_dir_all(&root);
3321        std::fs::create_dir_all(&root).unwrap();
3322        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"lev\"\n").unwrap();
3323        std::fs::write(
3324            root.join("lib.py"),
3325            "def lev(a, b):\n    return abs(len(a) - len(b))\n",
3326        )
3327        .unwrap();
3328        std::fs::write(
3329            root.join("app.py"),
3330            "from lib import lev\n\nfor _ in range(3000):\n    lev(\"kitten\", \"sitting\")\n",
3331        )
3332        .unwrap();
3333        // 10 us a call, called from the script's top level: the loop-caller advice applies.
3334        let module = ("app.py".to_string(), "<module>".to_string(), 1);
3335        let functions: HashMap<Key, Acc> = [
3336            (
3337                module.clone(),
3338                Acc {
3339                    self_ms: 5.0,
3340                    total_ms: 35.0,
3341                    calls: Some(1),
3342                    ..Default::default()
3343                },
3344            ),
3345            (
3346                ("lib.py".to_string(), "lev".to_string(), 1),
3347                Acc {
3348                    self_ms: 30.0,
3349                    total_ms: 30.0,
3350                    calls: Some(3000),
3351                    callers: [(module, (30.0, Some(3000)))].into_iter().collect(),
3352                    ..Default::default()
3353                },
3354            ),
3355        ]
3356        .into_iter()
3357        .collect();
3358        let r = report(
3359            &root,
3360            Lang::Python,
3361            &["python3".into()],
3362            functions,
3363            0.0,
3364            35.0,
3365        );
3366        std::fs::remove_dir_all(&root).unwrap();
3367        let lev = r.hot.iter().find(|h| h.name == "lev").expect("lev is hot");
3368        assert!(!lev.advice.contains("port `<module>`"), "{}", lev.advice);
3369        assert!(
3370            lev.advice.contains("port it (`rust-anything bridge"),
3371            "{}",
3372            lev.advice
3373        );
3374    }
3375
3376    #[test]
3377    fn executable_paths_stay_whole() {
3378        let js = "import { execFileSync, spawnSync, execSync } from \"node:child_process\";\n\
3379                  execFileSync(\"/opt/My Tools/worker\", []);\n\
3380                  spawnSync(\"ffmpeg\", [\"-i\", \"a b\"]);\n\
3381                  execSync(\"sleep 0.2\");\n\
3382                  execFileSync(`/opt/${dir}/worker`, []);\n";
3383        let programs: Vec<Option<String>> = js_spawn_calls("a.js", js)
3384            .into_iter()
3385            .map(|c| c.program)
3386            .collect();
3387        assert_eq!(
3388            programs,
3389            [
3390                Some("/opt/My Tools/worker".into()),
3391                Some("ffmpeg".into()),
3392                Some("sleep".into()),
3393                None
3394            ]
3395        );
3396        let py = "import subprocess\nsubprocess.run([\"/opt/My Tools/worker\", \"-x\"])\n\
3397                  subprocess.run(\"git status\", shell=True)\n";
3398        let programs: Vec<Option<String>> = python_spawn_calls(py)
3399            .into_iter()
3400            .map(|c| c.program)
3401            .collect();
3402        assert_eq!(
3403            programs,
3404            [Some("/opt/My Tools/worker".into()), Some("git".into())]
3405        );
3406    }
3407
3408    #[test]
3409    fn a_callback_wait_and_a_direct_call_that_disagree_name_no_program() {
3410        let src = "import { execSync } from \"node:child_process\";\n\
3411                   export function sync(xs, cold) {\n\
3412                   \x20 if (cold) execSync(\"git status\");\n\
3413                   \x20 xs.forEach((x) => execSync(`sleep ${x}`));\n\
3414                   }\n\
3415                   export function outer() {\n\
3416                   \x20 function inner() { return execSync(\"git log\"); }\n\
3417                   \x20 execSync(\"make\");\n\
3418                   \x20 return inner();\n\
3419                   }\n";
3420        let calls = js_spawn_calls("a.js", src);
3421        assert_eq!(spawn_site(&calls, "sync", 2), None);
3422        assert_eq!(
3423            spawn_site(&calls, "outer", 6),
3424            Some((8, Some("make".into()))),
3425            "a named inner function owns its own wait"
3426        );
3427        assert_eq!(
3428            spawn_site(&calls, "inner", 7),
3429            Some((7, Some("git".into())))
3430        );
3431    }
3432
3433    #[test]
3434    fn the_program_in_a_command_line() {
3435        assert_eq!(first_word("sleep 0.2", false).as_deref(), Some("sleep"));
3436        assert_eq!(
3437            first_word("TOKEN=abc LANG=C deploy --now", false).as_deref(),
3438            Some("deploy")
3439        );
3440        assert_eq!(
3441            first_word("TOKEN=abc", false),
3442            None,
3443            "never shows an assignment"
3444        );
3445        assert_eq!(first_word("TOKEN='abc def' deploy", false), None);
3446        assert_eq!(first_word("ls ", true).as_deref(), Some("ls"));
3447        assert_eq!(
3448            first_word("git", true),
3449            None,
3450            "`git${{x}}`: the program is computed"
3451        );
3452        assert_eq!(first_word("a|b c", false), None);
3453        assert_eq!(first_word("$HOME/bin/x run", false), None);
3454    }
3455
3456    #[test]
3457    fn javascript_spawn_calls_and_their_programs() {
3458        let src = "import { execSync, execFileSync } from \"node:child_process\";\n\
3459                   import * as cp from \"node:child_process\";\n\
3460                   execSync(\"make\");\n\
3461                   export function runAll(xs) {\n\
3462                   \x20 // old: execSync(\"echo hi\")\n\
3463                   \x20 const sep = '}';\n\
3464                   \x20 return xs.map((x) =>\n\
3465                   \x20   execSync(`sleep ${x}`).length);\n\
3466                   }\n\
3467                   export function both() { return execSync(\"git status\") + cp.execSync(\"npm test\"); }\n\
3468                   export function many(\n\
3469                   \x20 opts: { cwd: string },\n\
3470                   ): void {\n\
3471                   \x20 execFileSync(\n\
3472                   \x20   \"ffmpeg\",\n\
3473                   \x20   [\"-i\", opts.cwd],\n\
3474                   \x20 );\n\
3475                   \x20 cp.spawnSync(`${opts.cwd}/bin`, []);\n\
3476                   }\n";
3477        let calls = js_spawn_calls("lib.ts", src);
3478        let summary: Vec<(Vec<u32>, u32, Option<&str>)> = calls
3479            .iter()
3480            .map(|c| (c.scopes.clone(), c.line, c.program.as_deref()))
3481            .collect();
3482        assert_eq!(
3483            summary,
3484            [
3485                (vec![], 3, Some("make")),
3486                (vec![4, 7], 8, Some("sleep")),
3487                (vec![10], 10, Some("git")),
3488                (vec![10], 10, Some("npm")),
3489                (vec![11], 14, Some("ffmpeg")),
3490                (vec![11], 18, None),
3491            ]
3492        );
3493    }
3494
3495    #[test]
3496    fn python_spawn_calls_and_their_programs() {
3497        let src = "import os\nimport subprocess as sp\nfrom subprocess import check_output as co\n\n\
3498                   sp.run([\"make\"])\n\n\
3499                   def run_all(\n    n: int,\n) -> None:\n    \"\"\"e.g. sp.run([\"echo\"])\"\"\"\n    \
3500                   sp.run(\n        [\"git\", \"status\"],\n    )\n\n\n\
3501                   @cache\ndef shell():\n    os.system(\"\"\"sleep 0.1\"\"\")\n    co(args=(\"ls\", \"-l\"))\n    \
3502                   sp.check_call(f\"{tool} run\")\n    sp.Popen(f\"tar {flags}\")\n    \
3503                   other.run(\"nope\")\n    run(\"not imported\")\n";
3504        let calls = python_spawn_calls(src);
3505        let summary: Vec<(Vec<u32>, u32, Option<&str>)> = calls
3506            .iter()
3507            .map(|c| (c.scopes.clone(), c.line, c.program.as_deref()))
3508            .collect();
3509        assert_eq!(
3510            summary,
3511            [
3512                (vec![], 5, Some("make")),
3513                (vec![7], 11, Some("git")),
3514                (vec![16], 18, Some("sleep")),
3515                (vec![16], 19, Some("ls")),
3516                (vec![16], 20, None),
3517                (vec![16], 21, Some("tar")),
3518            ]
3519        );
3520    }
3521
3522    #[test]
3523    fn the_site_of_a_functions_child_process() {
3524        let root = std::env::temp_dir().join(format!("rust-anything-sites-{}", std::process::id()));
3525        let _ = std::fs::remove_dir_all(&root);
3526        std::fs::create_dir_all(&root).unwrap();
3527        std::fs::write(
3528            root.join("tool.py"),
3529            "import os, subprocess\n\nsubprocess.run([\"make\"])\n\n\
3530             def same():\n    subprocess.run([\"git\", \"fetch\"])\n    subprocess.check_output([\"git\", \"log\"])\n\n\
3531             def mixed(x):\n    os.system(\"make\")\n    subprocess.run(x)\n\n\
3532             def other(p):\n    return p.check_output()\n",
3533        )
3534        .unwrap();
3535        std::fs::write(
3536            root.join("lib.js"),
3537            "import { execSync } from \"node:child_process\";\nexecSync(\"make\");\n\
3538             export function runAll(xs) {\n  return xs.map((x) => execSync(`sleep ${x}`));\n}\n",
3539        )
3540        .unwrap();
3541        let (py_calls, js_calls) = (
3542            spawn_calls_in(&root, Lang::Python, "tool.py"),
3543            spawn_calls_in(&root, Lang::Ts, "lib.js"),
3544        );
3545        let py = |name: &str, line| spawn_site(&py_calls, name, line);
3546        let js = |name: &str, line| spawn_site(&js_calls, name, line);
3547        assert!(spawn_calls_in(&root, Lang::Python, "/elsewhere/tool.py").is_empty());
3548        assert!(spawn_calls_in(&root, Lang::Python, "../tool.py").is_empty());
3549        let got = (
3550            py("<module>", 1),
3551            py("same", 5),
3552            py("mixed", 9),
3553            py("other", 13),
3554            js("(anonymous):1", 1),
3555            js("runAll", 3),
3556            js("(anonymous):4", 4),
3557        );
3558        std::fs::remove_dir_all(&root).unwrap();
3559        assert_eq!(
3560            got.0,
3561            Some((3, Some("make".into()))),
3562            "the top level of a script"
3563        );
3564        assert_eq!(
3565            got.1,
3566            Some((6, Some("git".into()))),
3567            "two calls, one program"
3568        );
3569        assert_eq!(
3570            got.2, None,
3571            "two calls, two programs: the function's line is shown"
3572        );
3573        assert_eq!(
3574            got.3, None,
3575            "`p.check_output()` is not `subprocess.check_output`"
3576        );
3577        assert_eq!(got.4, Some((2, Some("make".into()))));
3578        assert_eq!(
3579            got.5,
3580            Some((4, Some("sleep".into()))),
3581            "a call in a callback"
3582        );
3583        assert_eq!(got.6, Some((4, Some("sleep".into()))));
3584    }
3585
3586    #[test]
3587    fn cpuprofile_recognizes_encoded_paths_in_the_repository() {
3588        let root = Path::new("/repo/work area");
3589        let profile = json!({
3590            "startTime": 0,
3591            "endTime": 10_000,
3592            "samples": [1],
3593            "nodes": [node(1, "hot", "file:///repo/work%20area/step%23one%25.mjs", 0, 1, &[])],
3594        });
3595        let mut functions = HashMap::new();
3596        merge_cpuprofile(root, &profile, &mut functions, &mut 0.0);
3597        assert!(
3598            functions.contains_key(&("step#one%.mjs".into(), "hot".into(), 0)),
3599            "{:?}",
3600            functions.keys()
3601        );
3602        assert_eq!(
3603            relative(root, "/repo/work area/step%20.mjs").as_deref(),
3604            Some("step%20.mjs")
3605        );
3606    }
3607
3608    #[test]
3609    fn finds_the_argument_that_varies_per_item() {
3610        let root =
3611            std::env::temp_dir().join(format!("rust-anything-profile-{}", std::process::id()));
3612        std::fs::create_dir_all(&root).unwrap();
3613        std::fs::write(
3614            root.join("search.ts"),
3615            "export function matched(query: string, all: string[]) {\n  return all.map(key => ({ key, score: fuzzyScore(query, key) }))\n}\n",
3616        )
3617        .unwrap();
3618        std::fs::write(
3619            root.join("search.py"),
3620            "def best(q, keys):\n    for k in keys:\n        yield score(q, k)\n",
3621        )
3622        .unwrap();
3623        let params = ["query".to_string(), "text".to_string()];
3624        let caller = |file: &str, name: &str| (file.to_string(), name.to_string(), 1);
3625        assert_eq!(
3626            batch_param(
3627                &root,
3628                &caller("search.ts", "matched"),
3629                "fuzzyScore",
3630                &params
3631            )
3632            .as_deref(),
3633            Some("text")
3634        );
3635        assert_eq!(
3636            batch_param(&root, &caller("search.py", "best"), "score", &params).as_deref(),
3637            Some("text")
3638        );
3639        std::fs::write(
3640            root.join("nested.ts"),
3641            "function main() {\n  for (const query of queries) {\n    for (const text of items) {\n      if (score(query, text) > 0) hits++\n    }\n  }\n}\n",
3642        )
3643        .unwrap();
3644        assert_eq!(
3645            batch_param(&root, &caller("nested.ts", "main"), "score", &params).as_deref(),
3646            Some("text"),
3647            "the innermost loop runs over the items"
3648        );
3649        // `query` is the same for every item: no batch parameter to give.
3650        assert_eq!(
3651            batch_param(&root, &caller("search.ts", "matched"), "missing", &params),
3652            None
3653        );
3654        std::fs::remove_dir_all(&root).unwrap();
3655    }
3656
3657    #[test]
3658    fn go_names_and_pprof() {
3659        assert_eq!(go_name("example.com/strkit/strkit.Slugify"), "Slugify");
3660        assert_eq!(go_name("testing.(*B).runN"), "runN");
3661        assert_eq!(
3662            go_name("example.com/x/pkg.Outer.func2"),
3663            "(anonymous) in Outer"
3664        );
3665        let raw = "Samples:\nsamples/count cpu/nanoseconds\n          2   20000000: 1 2 \n          1   10000000: 3 2 \n\
3666                   Locations\n     1: 0x1 M=1 golang.org/x/text.Map /home/u/go/pkg/mod/golang.org/x/text/map.go:568:0 s=528\n\
3667                   \x20            example.com/x/pkg.Slugify /repo/pkg/a.go:21:0 s=18\n\
3668                   \x20    2: 0x2 M=1 example.com/x/pkg.slugAll /repo/pkg/a_test.go:24:0 s=21\n\
3669                   \x20    3: 0x3 M=1 example.com/x/pkg.Slugify /repo/pkg/a.go:25:0 s=18\nMappings\n";
3670        let samples = parse_pprof_raw(Path::new("/repo"), raw);
3671        assert_eq!(samples.len(), 2);
3672        let key = |f: &str, n: &str, l: u32| Some((f.to_string(), n.to_string(), l));
3673        // Root first; the inlined Slugify sits between slugAll and strings.Map (not user code).
3674        assert_eq!(
3675            samples[0],
3676            (
3677                vec![
3678                    key("pkg/a_test.go", "slugAll", 21),
3679                    key("pkg/a.go", "Slugify", 18),
3680                    None
3681                ],
3682                20.0
3683            )
3684        );
3685        let mut functions = HashMap::new();
3686        merge_samples(&samples, &mut functions);
3687        let slug = &functions[&("pkg/a.go".to_string(), "Slugify".to_string(), 18)];
3688        assert_eq!((slug.total_ms, slug.self_ms), (30.0, 10.0));
3689        assert_eq!(slug.callers.values().map(|c| c.0).sum::<f64>(), 30.0);
3690    }
3691
3692    #[test]
3693    fn java_declarations() {
3694        let src = "class Strings {\n    public static String slugify(String text, int max) {\n        \
3695                   String s = slugify(text, 0);\n        return s;\n    }\n}\n";
3696        assert_eq!(java_declaration(src, "slugify", 4), Some(2));
3697        assert_eq!(java_declaration(src, "slugify", 1), None);
3698    }
3699
3700    #[test]
3701    fn loop_variables_in_go_java_ruby() {
3702        let (items, indexes) = loop_variables(
3703            "for _, t := range texts {\n\tSlugify(t, 30)\n}\nfor i := range xs {}\n\
3704             for (String w : words) {}\nfor (int j = 0; j < n; j++) {}\ntexts.map { |x| f(x) }\nxs.each do |y, k|\n",
3705        );
3706        assert_eq!(items, ["t", "w", "x", "y"]);
3707        assert_eq!(
3708            indexes,
3709            ["_", "i", "j"]
3710                .into_iter()
3711                .filter(|v| *v != "_")
3712                .collect::<Vec<_>>()
3713        );
3714    }
3715}