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