Skip to main content

rust_anything/
profile.rs

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