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}
51
52#[derive(Debug, Serialize)]
53pub struct Report {
54    pub schema: &'static str,
55    pub language: Lang,
56    pub command: Vec<String>,
57    pub total_ms: f64,
58    /// Share of the run spent in the repository's own code (the rest: runtime, libraries).
59    pub repo_pct: f64,
60    pub hot: Vec<Hot>,
61    /// Functions the repository already compiles to machine code (numba, Cython, JAX).
62    #[serde(skip_serializing_if = "Vec::is_empty")]
63    pub compiled: Vec<Compiled>,
64}
65
66#[derive(Debug, Clone, Serialize)]
67pub struct Compiled {
68    pub name: String,
69    pub file: String,
70    pub line: u32,
71    pub by: &'static str,
72}
73
74/// Every Python function in the repository a decorator compiles.
75fn compiled_in(root: &Path, lang: Lang) -> Vec<Compiled> {
76    if lang != Lang::Python {
77        return Vec::new();
78    }
79    let Ok(ws) = crate::lang::python::discover(root) else {
80        return Vec::new();
81    };
82    ws.files
83        .iter()
84        .filter(|f| f.kind == crate::ts::discover::FileKind::Source)
85        .flat_map(|f| {
86            let text = std::fs::read_to_string(root.join(&f.path)).unwrap_or_default();
87            crate::risks::python_compiled(&text)
88                .into_iter()
89                .map(|(name, line, by)| Compiled {
90                    name,
91                    file: f.path.clone(),
92                    line,
93                    by,
94                })
95                .collect::<Vec<_>>()
96        })
97        .collect()
98}
99
100/// The body of the Python function `name` defined at or just after `line`.
101fn python_body(text: &str, name: &str, line: u32) -> Option<String> {
102    let lines: Vec<&str> = text.lines().collect();
103    let start = (line as usize).saturating_sub(1);
104    let def = (start..lines.len().min(start + 20)).find(|&i| {
105        let t = lines[i].trim_start();
106        t.strip_prefix("def ")
107            .or_else(|| t.strip_prefix("async def "))
108            .is_some_and(|d| d.starts_with(name) && d[name.len()..].trim_start().starts_with('('))
109    })?;
110    let indent = |l: &str| l.len() - l.trim_start().len();
111    let base = indent(lines[def]);
112    let body: Vec<&str> = lines[def + 1..]
113        .iter()
114        .take_while(|l| l.trim().is_empty() || indent(l) > base)
115        .copied()
116        .collect();
117    Some(body.join("\n"))
118}
119
120fn calls(body: &str, name: &str) -> bool {
121    body.match_indices(&format!("{name}(")).any(|(i, _)| {
122        body[..i]
123            .chars()
124            .next_back()
125            .is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
126    })
127}
128
129/// Advice for a hot function that is compiled already, or that calls compiled code.
130fn compiled_advice(root: &Path, h: &Hot, compiled: &[Compiled]) -> Option<String> {
131    if let Some(c) = compiled
132        .iter()
133        .find(|c| c.file == h.file && c.name == h.name)
134    {
135        return Some(format!(
136            "Already compiled by {} (`{}:{}`): a Rust port is unlikely to run it much faster. \
137             Port it for a pure Rust app, not for speed.",
138            c.by, c.file, c.line
139        ));
140    }
141    let text = std::fs::read_to_string(root.join(&h.file)).ok()?;
142    let body = python_body(&text, &h.name, h.line)?;
143    let called: Vec<&Compiled> = compiled.iter().filter(|c| calls(&body, &c.name)).collect();
144    let first = called.first()?;
145    let names: Vec<String> = called.iter().map(|c| format!("`{}`", c.name)).collect();
146    Some(format!(
147        "{} It calls {} compiled by {} (`{}:{}`): the profiler counts that compiled time here, so \
148         porting this may gain little; port the Python around those calls, or measure without them.",
149        h.advice,
150        names.join(", "),
151        first.by,
152        first.file,
153        first.line
154    ))
155}
156
157/// One function's numbers before advice: key is (file, name, line).
158#[derive(Default)]
159struct Acc {
160    self_ms: f64,
161    total_ms: f64,
162    calls: Option<u64>,
163    callers: HashMap<(String, String, u32), (f64, Option<u64>)>,
164}
165
166type Key = (String, String, u32);
167
168pub fn profile(root: &Path, command: &[String], lang: Option<Lang>) -> Result<Report> {
169    if command.is_empty() {
170        bail!(
171            "give the workload to run after `--`, e.g. `rust-anything profile . -- node bench.mjs`"
172        );
173    }
174    let root = root
175        .canonical()
176        .with_context(|| format!("resolving {}", root.display()))?;
177    let lang = lang.unwrap_or_else(|| Lang::detect(&root));
178    let work = std::env::temp_dir().join(format!("rust-anything-profile-{}", std::process::id()));
179    let _ = std::fs::remove_dir_all(&work);
180    std::fs::create_dir_all(&work)?;
181    let (functions, total_ms) = match lang {
182        Lang::Ts => node(&root, command, &work)?,
183        Lang::Python => python(&root, command, &work)?,
184        Lang::Go => go(&root, command, &work)?,
185        Lang::Java => java(&root, command, &work)?,
186        Lang::Ruby => ruby(&root, command, &work)?,
187        Lang::C => bail!(
188            "`profile` runs TS/JS, Python, Go, Java and Ruby workloads; for C, use `perf record -g` \
189             and port the hot loops it shows"
190        ),
191        Lang::Php => bail!(
192            "`profile` does not run PHP workloads yet; use SPX or Xdebug's profiler and port the \
193             hot loops it shows"
194        ),
195        Lang::Csharp => bail!(
196            "`profile` does not run C# workloads yet; use `dotnet-trace` or your IDE's profiler and \
197             port the hot loops it shows"
198        ),
199    };
200    let _ = std::fs::remove_dir_all(&work);
201    Ok(report(&root, lang, command, functions, total_ms))
202}
203
204/// A frame's file: repository-relative, or absolute for user code elsewhere (a workload
205/// script); `None` for the runtime and installed libraries.
206fn relative(root: &Path, file: &str) -> Option<String> {
207    let decoded;
208    let path = if let Some(url_path) = file.strip_prefix("file://") {
209        decoded = percent_encoding::percent_decode_str(url_path).decode_utf8_lossy();
210        decoded.as_ref()
211    } else {
212        file
213    };
214    if !path.starts_with('/') && !path.contains(":\\") {
215        let rel = path.trim_start_matches("./");
216        return (!rel.starts_with(['<', '~']) && !rel.contains(':') && root.join(rel).is_file())
217            .then(|| rel.replace('\\', "/")); // node:internal/..., <frozen ...>, ~
218    }
219    // Installed libraries and runtimes: npm, Python, Ruby gems and stdlib, Go modules and GOROOT.
220    if path.split(['/', '\\']).any(|p| {
221        matches!(
222            p,
223            "node_modules"
224                | "site-packages"
225                | "dist-packages"
226                | ".venv"
227                | "venv"
228                | "gems"
229                | "vendor"
230        )
231    }) || ["/lib/python3", "/lib/ruby/", "/pkg/mod/"]
232        .iter()
233        .any(|d| path.contains(d))
234        || goroot().is_some_and(|g| path.starts_with(g))
235    {
236        return None;
237    }
238    let p = PathBuf::from(path);
239    Some(match p.strip_prefix(root) {
240        Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
241        Err(_) => path.to_string(),
242    })
243}
244
245/// Go's own sources, which are not user code.
246fn goroot() -> Option<&'static str> {
247    static GOROOT: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
248    GOROOT
249        .get_or_init(|| {
250            let out = crate::process::output(
251                Command::new("go").args(["env", "GOROOT"]),
252                crate::process::QUICK,
253            )
254            .ok()?;
255            let root = String::from_utf8(out.stdout).ok()?.trim().to_string();
256            (!root.is_empty()).then(|| format!("{root}/"))
257        })
258        .as_deref()
259}
260
261/// Whether a frame file is inside the repository (relative).
262fn in_repo(file: &str) -> bool {
263    !file.starts_with('/')
264}
265
266// ---- node --cpu-prof ------------------------------------------------------------------------
267
268fn node(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
269    let dir = work.join("node");
270    std::fs::create_dir_all(&dir)?;
271    let mut options = std::env::var("NODE_OPTIONS").unwrap_or_default();
272    let dir_option = dir
273        .to_string_lossy()
274        .replace('\\', "\\\\")
275        .replace('"', "\\\"");
276    options.push_str(&format!(" --cpu-prof --cpu-prof-dir=\"{dir_option}\""));
277    let status = crate::process::status(
278        Command::new(&command[0])
279            .args(&command[1..])
280            .current_dir(root)
281            .env("NODE_OPTIONS", options.trim()),
282        crate::process::TESTS,
283    )
284    .with_context(|| format!("running {}", command[0]))?;
285    if !status.success() {
286        bail!("the workload failed ({status})");
287    }
288    let mut functions: HashMap<Key, Acc> = HashMap::new();
289    let mut total = 0.0;
290    for entry in std::fs::read_dir(&dir)?.flatten() {
291        let profile: Value = serde_json::from_str(&std::fs::read_to_string(entry.path())?)?;
292        total += merge_cpuprofile(root, &profile, &mut functions);
293    }
294    if total == 0.0 {
295        bail!("no CPU profile was written: is the workload a node process?");
296    }
297    Ok((functions, total))
298}
299
300/// A `.cpuprofile` node: its frame when it is user code, its own time, its children.
301struct Frame {
302    key: Option<Key>,
303    self_ms: f64,
304    children: Vec<u64>,
305}
306
307/// Adds one `.cpuprofile` to `functions`; returns its duration in ms.
308fn merge_cpuprofile(root: &Path, profile: &Value, functions: &mut HashMap<Key, Acc>) -> f64 {
309    let Some(nodes) = profile["nodes"].as_array() else {
310        return 0.0;
311    };
312    let samples = profile["samples"].as_array().map_or(0, Vec::len).max(1);
313    let duration_ms = (profile["endTime"].as_f64().unwrap_or(0.0)
314        - profile["startTime"].as_f64().unwrap_or(0.0))
315        / 1000.0;
316    let per_sample = duration_ms / samples as f64;
317    let mut by_id: HashMap<u64, Frame> = HashMap::new();
318    let mut is_child = HashSet::new();
319    for n in nodes {
320        let id = n["id"].as_u64().unwrap_or(0);
321        let frame = &n["callFrame"];
322        let name = frame["functionName"].as_str().unwrap_or("").to_string();
323        let url = frame["url"].as_str().unwrap_or("");
324        let line = u32::try_from(frame["lineNumber"].as_i64().unwrap_or(0) + 1).unwrap_or(0);
325        let key = relative(root, url).map(|file| {
326            let shown = if name.is_empty() {
327                format!("(anonymous):{line}")
328            } else {
329                name.clone()
330            };
331            (file, shown, line)
332        });
333        let children: Vec<u64> = n["children"]
334            .as_array()
335            .map_or_else(Vec::new, |c| c.iter().filter_map(Value::as_u64).collect());
336        is_child.extend(children.iter().copied());
337        let self_ms = n["hitCount"].as_f64().unwrap_or(0.0) * per_sample;
338        by_id.insert(
339            id,
340            Frame {
341                key,
342                self_ms,
343                children,
344            },
345        );
346    }
347    // Inclusive time per node, depth first.
348    fn total(id: u64, by_id: &HashMap<u64, Frame>, memo: &mut HashMap<u64, f64>) -> f64 {
349        if let Some(t) = memo.get(&id) {
350            return *t;
351        }
352        let Some(frame) = by_id.get(&id) else {
353            return 0.0;
354        };
355        let t = frame.self_ms
356            + frame
357                .children
358                .iter()
359                .map(|c| total(*c, by_id, memo))
360                .sum::<f64>();
361        memo.insert(id, t);
362        t
363    }
364    let mut memo = HashMap::new();
365    // Walk from the roots, tracking the repo frames on the stack: recursion counts once, and a
366    // callee's caller is the nearest *named* repo frame above it (callbacks are skipped).
367    let roots: Vec<u64> = by_id
368        .keys()
369        .filter(|id| !is_child.contains(id))
370        .copied()
371        .collect();
372    let mut stack: Vec<(u64, Vec<Key>)> = roots.into_iter().map(|r| (r, Vec::new())).collect();
373    while let Some((id, active)) = stack.pop() {
374        let Some(Frame {
375            key,
376            self_ms,
377            children,
378        }) = by_id.get(&id)
379        else {
380            continue;
381        };
382        let mut next = active.clone();
383        if let Some(k) = key {
384            let inclusive = total(id, &by_id, &mut memo);
385            let acc = functions.entry(k.clone()).or_default();
386            acc.self_ms += self_ms;
387            if !active.contains(k) {
388                acc.total_ms += inclusive;
389                if let Some(caller) = active
390                    .iter()
391                    .rev()
392                    .find(|c| !c.1.starts_with("(anonymous)"))
393                    && caller != k
394                {
395                    acc.callers.entry(caller.clone()).or_default().0 += inclusive;
396                }
397            }
398            // Anonymous callbacks stay on the stack too; the caller lookup above skips them.
399            next.push(k.clone());
400        }
401        for c in children {
402            stack.push((*c, next.clone()));
403        }
404    }
405    duration_ms
406}
407
408// ---- Python cProfile ------------------------------------------------------------------------
409
410const PSTATS_PY: &str = r#"
411import json, pstats, sys
412stats = pstats.Stats(sys.argv[1]).stats
413out = []
414for (file, line, name), (cc, nc, tt, ct, callers) in stats.items():
415    out.append({
416        "file": file, "line": line, "name": name, "calls": nc, "self": tt * 1000, "total": ct * 1000,
417        "callers": [{"file": f, "line": l, "name": n, "calls": c[1], "total": c[3] * 1000} for (f, l, n), c in callers.items()],
418    })
419json.dump(out, open(sys.argv[2], "w"))
420"#;
421
422fn python(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
423    let program = Path::new(&command[0])
424        .file_name()
425        .map(|n| n.to_string_lossy().into_owned())
426        .unwrap_or_default();
427    if !program.starts_with("python") {
428        bail!(
429            "for Python, give the interpreter and script: `rust-anything profile . -- python3 bench.py`"
430        );
431    }
432    let stats = work.join("profile.pstats");
433    let start = std::time::Instant::now();
434    let status = crate::process::status(
435        Command::new(&command[0])
436            .args(["-m", "cProfile", "-o"])
437            .arg(&stats)
438            .args(&command[1..])
439            .current_dir(root),
440        crate::process::TESTS,
441    )
442    .with_context(|| format!("running {}", command[0]))?;
443    let total_ms = start.elapsed().as_secs_f64() * 1000.0;
444    if !status.success() {
445        bail!("the workload failed ({status})");
446    }
447    let json = work.join("profile.json");
448    let script = work.join("pstats_json.py");
449    std::fs::write(&script, PSTATS_PY)?;
450    let status = crate::process::status(
451        Command::new(&command[0])
452            .arg(&script)
453            .arg(&stats)
454            .arg(&json),
455        crate::process::TESTS,
456    )?;
457    if !status.success() {
458        bail!("reading the cProfile output failed");
459    }
460    let entries: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(&json)?)?;
461    Ok((ingest_entries(root, &entries), total_ms))
462}
463
464/// Function entries from a tracing profiler (cProfile, the Ruby tracer): file, line, name,
465/// calls, self and total ms, and callers with their calls and ms.
466fn ingest_entries(root: &Path, entries: &[Value]) -> HashMap<Key, Acc> {
467    let mut functions: HashMap<Key, Acc> = HashMap::new();
468    for e in entries {
469        let Some(file) = relative(root, e["file"].as_str().unwrap_or("")) else {
470            continue;
471        };
472        let key = (
473            file,
474            e["name"].as_str().unwrap_or("").to_string(),
475            u32::try_from(e["line"].as_u64().unwrap_or(0)).unwrap_or(0),
476        );
477        let acc = functions.entry(key).or_default();
478        acc.self_ms += e["self"].as_f64().unwrap_or(0.0);
479        acc.total_ms += e["total"].as_f64().unwrap_or(0.0);
480        acc.calls = Some(acc.calls.unwrap_or(0) + e["calls"].as_u64().unwrap_or(0));
481        for c in e["callers"].as_array().into_iter().flatten() {
482            let Some(cfile) = relative(root, c["file"].as_str().unwrap_or("")) else {
483                continue;
484            };
485            let ckey = (
486                cfile,
487                c["name"].as_str().unwrap_or("").to_string(),
488                u32::try_from(c["line"].as_u64().unwrap_or(0)).unwrap_or(0),
489            );
490            let slot = acc.callers.entry(ckey).or_default();
491            slot.0 += c["total"].as_f64().unwrap_or(0.0);
492            slot.1 = Some(slot.1.unwrap_or(0) + c["calls"].as_u64().unwrap_or(0));
493        }
494    }
495    functions
496}
497
498// ---- stack samples (Go pprof, Java JFR) -----------------------------------------------------
499
500/// Adds sampled stacks, each root first with `None` for frames outside user code, and the time
501/// it stands for. A function's total counts once per sample (recursion); its caller is the
502/// nearest named user frame above it (lambdas and closures are skipped).
503fn merge_samples(samples: &[(Vec<Option<Key>>, f64)], functions: &mut HashMap<Key, Acc>) {
504    for (stack, ms) in samples {
505        let mut seen: Vec<&Key> = Vec::new();
506        let mut named: Option<&Key> = None;
507        for frame in stack {
508            let Some(k) = frame else { continue };
509            if !seen.contains(&k) {
510                seen.push(k);
511                let acc = functions.entry(k.clone()).or_default();
512                acc.total_ms += ms;
513                if let Some(caller) = named.filter(|c| *c != k) {
514                    acc.callers.entry(caller.clone()).or_default().0 += ms;
515                }
516            }
517            if !k.1.starts_with("(anonymous)") {
518                named = Some(k);
519            }
520        }
521        if let Some(Some(leaf)) = stack.last() {
522            functions.entry(leaf.clone()).or_default().self_ms += ms;
523        }
524    }
525}
526
527/// A Go function's own name: `example.com/x/pkg.Slugify` is `Slugify`, `pkg.(*T).M` is `M`;
528/// closures (`Outer.func1`) are anonymous.
529fn go_name(full: &str) -> String {
530    let tail = full.rsplit('/').next().unwrap_or(full);
531    let rest = tail.split_once('.').map_or(tail, |(_, r)| r);
532    let parts: Vec<&str> = rest.split('.').collect();
533    match parts.as_slice() {
534        [.., outer, f] if f.starts_with("func") && f[4..].chars().all(|c| c.is_ascii_digit()) => {
535            format!("(anonymous) in {outer}")
536        }
537        [.., last] => last.to_string(),
538        [] => rest.to_string(),
539    }
540}
541
542/// `go tool pprof -raw` output: samples (leaf first, by location id) and locations (each one or
543/// more frames, innermost first: `func file:line:col s=start`).
544fn parse_pprof_raw(root: &Path, raw: &str) -> Vec<(Vec<Option<Key>>, f64)> {
545    let mut locations: HashMap<u64, Vec<Option<Key>>> = HashMap::new();
546    let mut samples: Vec<(Vec<u64>, f64)> = Vec::new();
547    let mut section = "";
548    let mut current: Option<u64> = None;
549    // Which sample value is CPU time: `samples/count cpu/nanoseconds` puts it second.
550    let mut value_index = 1;
551    for line in raw.lines() {
552        match line.trim_end() {
553            "Samples:" => {
554                section = "samples";
555                continue;
556            }
557            "Locations" => {
558                section = "locations";
559                continue;
560            }
561            "Mappings" => {
562                section = "";
563                continue;
564            }
565            _ => {}
566        }
567        match section {
568            "samples" if line.contains(':') => {
569                let (values, ids) = line.split_once(':').unwrap_or_default();
570                let values: Vec<f64> = values
571                    .split_whitespace()
572                    .filter_map(|v| v.parse().ok())
573                    .collect();
574                let ids: Vec<u64> = ids
575                    .split_whitespace()
576                    .filter_map(|v| v.parse().ok())
577                    .collect();
578                if let Some(ns) = values.get(value_index).or(values.last()) {
579                    samples.push((ids, ns / 1e6));
580                }
581            }
582            "samples" => {
583                let kinds: Vec<&str> = line.split_whitespace().collect();
584                if let Some(i) = kinds.iter().position(|k| k.ends_with("/nanoseconds")) {
585                    value_index = i;
586                }
587            }
588            "locations" => {
589                let text = line.trim_start();
590                let frame_text = match text.split_once(": ") {
591                    Some((id, rest)) if id.chars().all(|c| c.is_ascii_digit()) => {
592                        current = id.parse().ok();
593                        // `0x4c2ded M=1 func file:line:col s=start`
594                        rest.split_whitespace()
595                            .skip(2)
596                            .collect::<Vec<_>>()
597                            .join(" ")
598                    }
599                    _ => text.to_string(),
600                };
601                let Some(id) = current else { continue };
602                let mut parts = frame_text.split_whitespace();
603                let (Some(func), Some(place)) = (parts.next(), parts.next()) else {
604                    continue;
605                };
606                let start = parts
607                    .find_map(|p| p.strip_prefix("s="))
608                    .and_then(|s| s.parse::<u32>().ok())
609                    .unwrap_or(0);
610                let file = place.rsplitn(3, ':').nth(2).unwrap_or(place);
611                let key = relative(root, file).map(|f| (f, go_name(func), start));
612                locations.entry(id).or_default().push(key);
613            }
614            _ => {}
615        }
616    }
617    samples
618        .into_iter()
619        .map(|(ids, ms)| {
620            // Leaf first, and inlined frames innermost first: reversed, the stack is root first.
621            let mut stack: Vec<Option<Key>> = ids
622                .iter()
623                .flat_map(|id| locations.get(id).cloned().unwrap_or_default())
624                .collect();
625            stack.reverse();
626            (stack, ms)
627        })
628        .collect()
629}
630
631/// Go: `go test` with `-cpuprofile` (Go has no profiler to attach from outside), read with
632/// `go tool pprof -raw`.
633fn go(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
634    let program = Path::new(&command[0])
635        .file_name()
636        .map(|n| n.to_string_lossy().into_owned())
637        .unwrap_or_default();
638    if program != "go" || command.get(1).map(String::as_str) != Some("test") {
639        bail!(
640            "for Go, profile a benchmark or test: `rust-anything profile . -- go test -run XXX -bench . ./pkg` \
641             (Go profiles only from inside the process; `go test` adds -cpuprofile)"
642        );
643    }
644    let out = work.join("cpu.pprof");
645    let status = crate::process::status(
646        Command::new(&command[0])
647            .arg("test")
648            .arg(format!("-cpuprofile={}", out.display()))
649            .args(&command[2..])
650            .current_dir(root),
651        crate::process::TESTS,
652    )
653    .with_context(|| format!("running {}", command[0]))?;
654    if !status.success() {
655        bail!("the workload failed ({status})");
656    }
657    let raw = crate::process::output(
658        Command::new("go")
659            .args(["tool", "pprof", "-raw"])
660            .arg(&out)
661            .current_dir(root),
662        crate::process::TESTS,
663    )?;
664    if !raw.status.success() {
665        bail!(
666            "go tool pprof failed: {}",
667            String::from_utf8_lossy(&raw.stderr)
668        );
669    }
670    let samples = parse_pprof_raw(root, &String::from_utf8_lossy(&raw.stdout));
671    let total: f64 = samples.iter().map(|(_, ms)| ms).sum();
672    let mut functions = HashMap::new();
673    merge_samples(&samples, &mut functions);
674    Ok((functions, total))
675}
676
677/// The line declaring method `name` in Java source: the nearest declaration at or above `near`.
678fn java_declaration(text: &str, name: &str, near: u32) -> Option<u32> {
679    let needle = format!("{name}(");
680    let mut best = None;
681    for (i, line) in text.lines().enumerate() {
682        let n = u32::try_from(i + 1).unwrap_or(u32::MAX);
683        if n > near.max(1) {
684            break;
685        }
686        let Some(at) = line.find(&needle) else {
687            continue;
688        };
689        let before = line[..at].trim_end();
690        // A declaration names a type or modifier before the method: `static int pages(`.
691        let declares = before
692            .ends_with(|c: char| c.is_alphanumeric() || matches!(c, '>' | ']' | '_'))
693            && !before.contains('=')
694            && !before.contains("return")
695            && !before.contains("new ")
696            && !before.ends_with('.')
697            && !line.trim_end().ends_with(';');
698        if declares && at > 0 && line.as_bytes()[at - 1].is_ascii_whitespace() {
699            best = Some(n);
700        }
701    }
702    best
703}
704
705/// Java: Flight Recorder's execution samples, read with `jfr print --json`.
706fn java(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
707    let recording = work.join("profile.jfr");
708    let mut options = std::env::var("JAVA_TOOL_OPTIONS").unwrap_or_default();
709    options.push_str(&format!(
710        " -XX:StartFlightRecording=filename={},settings=profile -XX:FlightRecorderOptions=stackdepth=256",
711        recording.display()
712    ));
713    let status = crate::process::status(
714        Command::new(&command[0])
715            .args(&command[1..])
716            .current_dir(root)
717            .env("JAVA_TOOL_OPTIONS", options.trim()),
718        crate::process::TESTS,
719    )
720    .with_context(|| format!("running {}", command[0]))?;
721    if !status.success() {
722        bail!("the workload failed ({status})");
723    }
724    let out = crate::process::output(
725        Command::new("jfr")
726            .args([
727                "print",
728                "--json",
729                "--stack-depth",
730                "256",
731                "--events",
732                "jdk.ExecutionSample",
733            ])
734            .arg(&recording),
735        crate::process::TESTS,
736    )
737    .context("running jfr (it comes with the JDK)")?;
738    if !out.status.success() {
739        bail!("jfr print failed: {}", String::from_utf8_lossy(&out.stderr));
740    }
741    let json: Value = serde_json::from_slice(&out.stdout).context("jfr output")?;
742    // Sources by class: `com/example/text/Strings` -> its file in the repository.
743    let mut sources: HashMap<String, String> = HashMap::new();
744    for entry in crate::walk::builder(root).build() {
745        let Ok(entry) = entry else { continue };
746        let path = entry.path();
747        if path.extension().is_some_and(|e| e == "java")
748            && let Ok(rel) = path.strip_prefix(root)
749        {
750            let rel = rel.to_string_lossy().replace('\\', "/");
751            let text = std::fs::read_to_string(path).unwrap_or_default();
752            let package = text
753                .lines()
754                .find_map(|l| {
755                    l.trim()
756                        .strip_prefix("package ")
757                        .map(|p| p.trim_end_matches(';').trim().to_string())
758                })
759                .unwrap_or_default();
760            let class = path
761                .file_stem()
762                .map(|s| s.to_string_lossy().into_owned())
763                .unwrap_or_default();
764            let fq = if package.is_empty() {
765                class
766            } else {
767                format!("{}/{class}", package.replace('.', "/"))
768            };
769            sources.insert(fq, rel);
770        }
771    }
772    const SAMPLE_MS: f64 = 10.0; // the `profile` settings sample Java threads every 10 ms
773    let mut raw: Vec<Vec<Option<(String, String, u32)>>> = Vec::new();
774    for event in json["recording"]["events"].as_array().into_iter().flatten() {
775        let frames = event["values"]["stackTrace"]["frames"]
776            .as_array()
777            .cloned()
778            .unwrap_or_default();
779        let mut stack: Vec<Option<(String, String, u32)>> = frames
780            .iter()
781            .map(|f| {
782                let class = f["method"]["type"]["name"].as_str()?;
783                let outer = class.split('$').next().unwrap_or(class);
784                let file = sources.get(outer)?;
785                let name = f["method"]["name"].as_str()?.to_string();
786                let line = u32::try_from(f["lineNumber"].as_i64().unwrap_or(0)).unwrap_or(0);
787                Some((file.clone(), name, line))
788            })
789            .collect();
790        stack.reverse();
791        raw.push(stack);
792    }
793    // Key each method by its declaration line, found from the lowest sampled line.
794    let mut lowest: HashMap<(String, String), u32> = HashMap::new();
795    for (file, name, line) in raw.iter().flatten().flatten() {
796        let e = lowest.entry((file.clone(), name.clone())).or_insert(*line);
797        *e = (*e).min(*line);
798    }
799    let mut texts: HashMap<String, String> = HashMap::new();
800    let mut key = |file: &str, name: &str| -> Key {
801        if name.starts_with("lambda$") {
802            return (file.to_string(), format!("(anonymous) {name}"), 0);
803        }
804        let text = texts
805            .entry(file.to_string())
806            .or_insert_with(|| std::fs::read_to_string(root.join(file)).unwrap_or_default());
807        let near = lowest
808            .get(&(file.to_string(), name.to_string()))
809            .copied()
810            .unwrap_or(0);
811        let line = java_declaration(text, name, near).unwrap_or(near);
812        (file.to_string(), name.to_string(), line)
813    };
814    let samples: Vec<(Vec<Option<Key>>, f64)> = raw
815        .iter()
816        .map(|stack| {
817            let keys = stack
818                .iter()
819                .map(|f| f.as_ref().map(|(file, name, _)| key(file, name)))
820                .collect();
821            (keys, SAMPLE_MS)
822        })
823        .collect();
824    let total = samples.len() as f64 * SAMPLE_MS;
825    if samples.is_empty() {
826        bail!("no samples were recorded: run the workload longer (Java is sampled every 10 ms)");
827    }
828    let mut functions = HashMap::new();
829    merge_samples(&samples, &mut functions);
830    Ok((functions, total))
831}
832
833// ---- Ruby: a call tracer --------------------------------------------------------------------
834
835/// Loaded with `RUBYOPT=-r`: times every Ruby method call on the main thread (inclusive, self,
836/// callers) and writes cProfile-like entries at exit. Tracing slows the program; the shares stay
837/// comparable.
838const RUBY_TRACER: &str = r#"
839require "json"
840
841module RustAnythingProfile
842  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] } } }
843  STACK = []
844  ACTIVE = Hash.new(0)
845  MAIN = Thread.current
846  TRACE = TracePoint.new(:call, :return) do |tp|
847    next unless Thread.current == MAIN
848    now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
849    if tp.event == :call
850      path = tp.path
851      path = File.expand_path(path) unless path.start_with?("<")
852      key = [path, tp.lineno, tp.method_id.to_s]
853      ACTIVE[key] += 1
854      STACK << [key, now, 0.0]
855    elsif (frame = STACK.pop)
856      key, start, child = frame
857      elapsed = now - start
858      ACTIVE[key] -= 1
859      outer = ACTIVE[key].zero?
860      s = STATS[key]
861      s[:calls] += 1
862      s[:self] += elapsed - child
863      s[:total] += elapsed if outer
864      if (parent = STACK.last)
865        parent[2] += elapsed
866        c = s[:callers][parent[0]]
867        c[0] += 1
868        c[1] += elapsed if outer
869      end
870    end
871  end
872  TRACE.enable
873
874  at_exit do
875    TRACE.disable
876    out = STATS.map do |(file, line, name), s|
877      { file: file, line: line, name: name, calls: s[:calls], self: s[:self] * 1000, total: s[:total] * 1000,
878        callers: s[:callers].map { |(f, l, n), (calls, total)| { file: f, line: l, name: n, calls: calls, total: total * 1000 } } }
879    end
880    File.write(ENV.fetch("RUST_ANYTHING_PROFILE_OUT"), JSON.generate(out))
881  end
882end
883"#;
884
885/// Ruby: the tracer above, loaded into any Ruby command through `RUBYOPT`.
886fn ruby(root: &Path, command: &[String], work: &Path) -> Result<(HashMap<Key, Acc>, f64)> {
887    let tracer = work.join("rust_anything_profile.rb");
888    std::fs::write(&tracer, RUBY_TRACER)?;
889    let out = work.join("profile.json");
890    let mut rubyopt = std::env::var("RUBYOPT").unwrap_or_default();
891    rubyopt.push_str(&format!(" -r{}", tracer.display()));
892    let start = std::time::Instant::now();
893    let status = crate::process::status(
894        Command::new(&command[0])
895            .args(&command[1..])
896            .current_dir(root)
897            .env("RUBYOPT", rubyopt.trim())
898            .env("RUST_ANYTHING_PROFILE_OUT", &out),
899        crate::process::TESTS,
900    )
901    .with_context(|| format!("running {}", command[0]))?;
902    let total_ms = start.elapsed().as_secs_f64() * 1000.0;
903    if !status.success() {
904        bail!("the workload failed ({status})");
905    }
906    let entries: Vec<Value> = serde_json::from_str(
907        &std::fs::read_to_string(&out)
908            .context("the Ruby tracer wrote nothing: is the workload a Ruby process?")?,
909    )?;
910    Ok((ingest_entries(root, &entries), total_ms))
911}
912
913// ---- the report -----------------------------------------------------------------------------
914
915/// The argument a caller passes per loop item: an arrow or for-of variable among `f`'s call
916/// arguments in the caller's source. `None` when the source does not show one.
917fn batch_param(root: &Path, caller: &Key, callee: &str, params: &[String]) -> Option<String> {
918    let text = std::fs::read_to_string(root.join(&caller.0)).ok()?;
919    let lines: Vec<&str> = text.lines().collect();
920    let start = (caller.2 as usize).saturating_sub(1);
921    let body = lines.get(start..(start + 80).min(lines.len()))?.join("\n");
922    let mut loop_vars: Vec<String> = Vec::new();
923    for (i, _) in body.match_indices("=>") {
924        let before = body[..i].trim_end().trim_end_matches(')');
925        let name: String = before
926            .chars()
927            .rev()
928            .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$')
929            .collect::<String>()
930            .chars()
931            .rev()
932            .collect();
933        if !name.is_empty() {
934            loop_vars.push(name);
935        }
936    }
937    for word in ["const ", "let ", "var ", "for "] {
938        for (i, _) in body.match_indices(word) {
939            let rest = &body[i + word.len()..];
940            let name: String = rest
941                .chars()
942                .take_while(|c| c.is_alphanumeric() || *c == '_')
943                .collect();
944            if rest[name.len()..].trim_start().starts_with("of ")
945                || rest[name.len()..].trim_start().starts_with("in ")
946            {
947                loop_vars.push(name);
948            }
949        }
950    }
951    let (more, index_vars) = loop_variables(&body);
952    loop_vars.extend(more);
953    let call = body.find(&format!("{callee}("))?;
954    let args_text = &body[call + callee.len() + 1..];
955    let mut depth = 0;
956    let mut args = vec![String::new()];
957    for c in args_text.chars() {
958        match c {
959            '(' | '[' | '{' => depth += 1,
960            ')' | ']' | '}' if depth == 0 => break,
961            ')' | ']' | '}' => depth -= 1,
962            ',' if depth == 0 => {
963                args.push(String::new());
964                continue;
965            }
966            _ => {}
967        }
968        args.last_mut()?.push(c);
969    }
970    // The item itself (`t`), or the item at the loop index (`texts[i]`).
971    let per_item = |a: &str| {
972        let a = a.trim();
973        loop_vars.iter().any(|v| v == a)
974            || a.strip_suffix(']')
975                .and_then(|a| a.split_once('['))
976                .is_some_and(|(list, i)| {
977                    !list.is_empty() && index_vars.iter().any(|v| v == i.trim())
978                })
979    };
980    let position = args.iter().position(|a| per_item(a))?;
981    params.get(position).cloned()
982}
983
984/// Loop variables in Go, Java and Ruby source: `(items, indexes)`. Items: `for _, t := range`,
985/// `for (String t : texts)`, `|t|`; indexes: `for i := range`, `for (int i = 0;`.
986fn loop_variables(body: &str) -> (Vec<String>, Vec<String>) {
987    let ident = |s: &str| -> String {
988        s.chars()
989            .take_while(|c| c.is_alphanumeric() || *c == '_')
990            .collect()
991    };
992    let last_ident = |s: &str| -> String {
993        let s = s.trim_end();
994        let rev: String = s
995            .chars()
996            .rev()
997            .take_while(|c| c.is_alphanumeric() || *c == '_')
998            .collect();
999        rev.chars().rev().collect()
1000    };
1001    let (mut items, mut indexes) = (Vec::new(), Vec::new());
1002    for (i, _) in body.match_indices("for") {
1003        if body[..i]
1004            .chars()
1005            .last()
1006            .is_some_and(|c| c.is_alphanumeric() || c == '_')
1007        {
1008            continue;
1009        }
1010        let rest = &body[i + 3..];
1011        let line = rest.split(['{', '\n']).next().unwrap_or(rest);
1012        if let Some((vars, _)) = line.split_once(":= range") {
1013            // Go: `for i, t := range xs` (t is the item), `for i := range xs` (an index).
1014            let vars: Vec<String> = vars.split(',').map(|v| v.trim().to_string()).collect();
1015            match vars.as_slice() {
1016                [index, item] => {
1017                    items.push(item.clone());
1018                    indexes.push(index.clone());
1019                }
1020                [index] => indexes.push(index.clone()),
1021                _ => {}
1022            }
1023        } else if let Some(inner) = line.trim_start().strip_prefix('(') {
1024            // Java: `for (String t : texts)` or `for (int i = 0; ...)`.
1025            if let Some((decl, _)) = inner.split_once(" : ").filter(|(d, _)| !d.contains(';')) {
1026                items.push(last_ident(decl));
1027            } else if let Some((decl, _)) = inner.split_once('=') {
1028                indexes.push(last_ident(decl));
1029            }
1030        }
1031    }
1032    // Ruby blocks: `{ |t| ... }`, `do |t, i|`.
1033    for (i, _) in body.match_indices('|') {
1034        let before = body[..i].trim_end();
1035        if before.ends_with('{') || before.ends_with("do") {
1036            let first = ident(body[i + 1..].trim_start());
1037            if !first.is_empty() {
1038                items.push(first);
1039            }
1040        }
1041    }
1042    items.retain(|v| !v.is_empty() && v != "_");
1043    indexes.retain(|v| !v.is_empty() && v != "_");
1044    (items, indexes)
1045}
1046
1047fn report(
1048    root: &Path,
1049    lang: Lang,
1050    command: &[String],
1051    functions: HashMap<Key, Acc>,
1052    total_ms: f64,
1053) -> Report {
1054    let analysis = crate::analyze::analyze_lang(root, lang).ok();
1055    let unit_of = |file: &str| -> Option<(String, bool)> {
1056        let a = analysis.as_ref()?;
1057        let u = a.units.iter().find(|u| u.files.iter().any(|f| f == file))?;
1058        let portable = !matches!(
1059            u.status,
1060            crate::analyze::Status::Keep | crate::analyze::Status::Blocked
1061        );
1062        Some((u.id.clone(), portable))
1063    };
1064    let exports_of = |file: &str, name: &str| -> Option<crate::ts::exports::ExportedFn> {
1065        let text = std::fs::read_to_string(root.join(file)).ok()?;
1066        let fns = if lang == Lang::Ts {
1067            crate::ts::exports::exported_functions(file, &text)
1068        } else {
1069            crate::lang::exports(lang, file, &text).0
1070        };
1071        fns.into_iter().find(|f| f.name == name)
1072    };
1073    let repo_self: f64 = functions
1074        .iter()
1075        .filter(|(k, _)| in_repo(&k.0))
1076        .map(|(_, a)| a.self_ms)
1077        .sum();
1078    let mut hot: Vec<Hot> = functions
1079        .into_iter()
1080        .filter(|((file, _, _), a)| in_repo(file) && total_ms > 0.0 && a.total_ms / total_ms >= 0.01)
1081        .map(|((file, name, line), a)| {
1082            let unit = unit_of(&file);
1083            let export = exports_of(&file, &name);
1084            let mut callers: Vec<Caller> = a
1085                .callers
1086                .iter()
1087                .map(|((f, n, l), (ms, calls))| Caller { name: n.clone(), file: f.clone(), line: *l, ms: *ms, calls: *calls })
1088                .collect();
1089            callers.sort_by(|x, y| y.ms.total_cmp(&x.ms));
1090            callers.truncate(5);
1091            let ns_per_call = a.calls.filter(|c| *c > 0).map(|c| a.total_ms * 1e6 / c as f64);
1092            let total_pct = 100.0 * a.total_ms / total_ms;
1093            let top = callers.first();
1094            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));
1095            let advice = match (&unit, &export) {
1096                (Some((u, true)), Some(e)) if small_per_call && top.is_some() => {
1097                    let c = top.expect("checked");
1098                    let params: Vec<String> = e.params.iter().map(|p| p.name.clone()).collect();
1099                    let batch = batch_param(root, &(c.file.clone(), c.name.clone(), c.line), &name, &params);
1100                    let calls = a.calls.map_or_else(String::new, |n| format!(", {n} calls"));
1101                    match batch {
1102                        Some(param) => format!(
1103                            "Called in a loop by `{}` ({}:{}{calls}): a call per item would cost more than the work. \
1104                             Batch it, keeping the items in Rust and using all cores: \
1105                             `rust-anything bridge {} {u} --batch {name}:{param}`, then prepare the items once in a \
1106                             `{}Index` in port.rs. Better still, port `{}` with it.",
1107                            c.name, c.file, c.line, root.display(), crate::codegen_batch::pascal(&name), c.name
1108                        ),
1109                        None => format!(
1110                            "Mostly called by `{}` ({}:{}{calls}): port `{}` together with `{name}`, so one call into Rust does the whole loop.",
1111                            c.name, c.file, c.line, c.name
1112                        ),
1113                    }
1114                }
1115                (Some((u, true)), Some(_)) => format!(
1116                    "Hot and exported by `{u}`: port it (`rust-anything bridge {} {u}`), then check `rust-anything bench`.",
1117                    root.display()
1118                ),
1119                (Some((u, true)), None) => format!("Hot inside `{u}`: port the exported function that calls it, with it."),
1120                (Some((u, false)), _) => format!("Hot, but `{u}` must stay in the source language (see `rust-anything analyze`)."),
1121                (None, _) => "Hot, outside the analyzed units.".into(),
1122            };
1123            Hot {
1124                unit: unit.map(|(u, _)| u),
1125                exported: export.is_some(),
1126                name,
1127                file,
1128                line,
1129                self_ms: a.self_ms,
1130                total_ms: a.total_ms,
1131                total_pct,
1132                calls: a.calls,
1133                ns_per_call,
1134                callers,
1135                advice,
1136            }
1137        })
1138        .collect();
1139    hot.sort_by(|a, b| b.total_ms.total_cmp(&a.total_ms));
1140    hot.truncate(25);
1141    let compiled = compiled_in(root, lang);
1142    for h in &mut hot {
1143        if let Some(advice) = compiled_advice(root, h, &compiled) {
1144            h.advice = advice;
1145        }
1146    }
1147    Report {
1148        schema: SCHEMA,
1149        language: lang,
1150        command: command.to_vec(),
1151        total_ms,
1152        repo_pct: if total_ms > 0.0 {
1153            (100.0 * repo_self / total_ms).min(100.0)
1154        } else {
1155            0.0
1156        },
1157        compiled,
1158        hot,
1159    }
1160}
1161
1162pub fn markdown(r: &Report) -> String {
1163    use std::fmt::Write as _;
1164    let mut out = format!(
1165        "# Profile: `{}`\n\n{:.0} ms in all; {:.0}% of it in the repository's own code.\n\n\
1166         | Function | File | Total | Self | Calls | Unit |\n| --- | --- | ---: | ---: | ---: | --- |\n",
1167        r.command.join(" "),
1168        r.total_ms,
1169        r.repo_pct
1170    );
1171    for h in &r.hot {
1172        let _ = writeln!(
1173            out,
1174            "| `{}` | `{}:{}` | {:.0}% ({:.0} ms) | {:.0} ms | {} | {} |",
1175            h.name,
1176            h.file,
1177            h.line,
1178            h.total_pct,
1179            h.total_ms,
1180            h.self_ms,
1181            h.calls.map_or_else(|| "-".into(), |c| c.to_string()),
1182            h.unit
1183                .as_deref()
1184                .map_or_else(|| "-".into(), |u| format!("`{u}`"))
1185        );
1186    }
1187    if !r.compiled.is_empty() {
1188        out.push_str(
1189            "\n## Already compiled\n\nThese run as machine code already; Rust is unlikely to make them \
1190             much faster:\n\n",
1191        );
1192        for c in &r.compiled {
1193            let _ = writeln!(out, "- `{}` (`{}:{}`): {}", c.name, c.file, c.line, c.by);
1194        }
1195    }
1196    out.push_str("\n## What to port\n\n");
1197    let mut seen = BTreeMap::new();
1198    for h in r.hot.iter().filter(|h| h.unit.is_some()) {
1199        if seen.insert(h.name.clone(), ()).is_some() {
1200            continue;
1201        }
1202        let _ = writeln!(
1203            out,
1204            "- **`{}`** ({:.0}%): {}",
1205            h.name, h.total_pct, h.advice
1206        );
1207    }
1208    out
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213    use super::*;
1214    use serde_json::json;
1215
1216    #[test]
1217    fn compiled_code_changes_the_advice() {
1218        let root = std::env::temp_dir().join(format!("rust-anything-numba-{}", std::process::id()));
1219        let _ = std::fs::remove_dir_all(&root);
1220        std::fs::create_dir_all(root.join("sim")).unwrap();
1221        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"sim\"\n").unwrap();
1222        std::fs::write(
1223            root.join("sim/physics.py"),
1224            "from numba import njit\n\n@njit(cache=True)\ndef step(x, dt):\n    return x + dt\n\n\
1225             def run(xs):\n    out = []\n    for x in xs:\n        out.append(step(x, 0.1))\n    return out\n\n\
1226             def other(xs):\n    return [x * 2 for x in xs]\n",
1227        )
1228        .unwrap();
1229        let compiled = compiled_in(&root, Lang::Python);
1230        assert_eq!(compiled.len(), 1);
1231        assert_eq!(
1232            (compiled[0].name.as_str(), compiled[0].line, compiled[0].by),
1233            ("step", 4, "numba")
1234        );
1235        let hot = |name: &str, line: u32| Hot {
1236            name: name.into(),
1237            file: "sim/physics.py".into(),
1238            line,
1239            unit: None,
1240            exported: true,
1241            self_ms: 1.0,
1242            total_ms: 1.0,
1243            total_pct: 50.0,
1244            calls: None,
1245            ns_per_call: None,
1246            callers: Vec::new(),
1247            advice: "Port it.".into(),
1248        };
1249        let own = compiled_advice(&root, &hot("step", 3), &compiled).unwrap();
1250        assert!(
1251            own.starts_with("Already compiled by numba (`sim/physics.py:4`)"),
1252            "{own}"
1253        );
1254        let caller = compiled_advice(&root, &hot("run", 7), &compiled).unwrap();
1255        assert!(
1256            caller.starts_with("Port it. It calls `step` compiled by numba"),
1257            "{caller}"
1258        );
1259        assert!(compiled_advice(&root, &hot("other", 13), &compiled).is_none());
1260        assert!(compiled_in(&root, Lang::Ts).is_empty());
1261        std::fs::remove_dir_all(&root).unwrap();
1262    }
1263
1264    #[test]
1265    fn frames_outside_user_code_are_dropped() {
1266        let root = Path::new("/repo");
1267        assert_eq!(relative(root, "node:internal/main"), None);
1268        assert_eq!(relative(root, "file:///repo/node_modules/x/index.js"), None);
1269        assert_eq!(relative(root, "/usr/lib/python3.13/json/__init__.py"), None);
1270        assert_eq!(
1271            relative(root, "file:///repo/src/fuzzy.ts").as_deref(),
1272            Some("src/fuzzy.ts")
1273        );
1274        // A workload script elsewhere is user code, shown with its full path.
1275        assert_eq!(
1276            relative(root, "/tmp/bench.ts").as_deref(),
1277            Some("/tmp/bench.ts")
1278        );
1279        assert!(in_repo("src/fuzzy.ts") && !in_repo("/tmp/bench.ts"));
1280    }
1281
1282    #[test]
1283    fn a_relative_script_path_under_the_repository_is_kept() {
1284        let root = std::env::temp_dir().join(format!("ra-profile-rel-{}", std::process::id()));
1285        std::fs::create_dir_all(&root).unwrap();
1286        std::fs::write(root.join("bench.py"), "").unwrap();
1287        assert_eq!(relative(&root, "bench.py").as_deref(), Some("bench.py"));
1288        assert_eq!(relative(&root, "./bench.py").as_deref(), Some("bench.py"));
1289        assert_eq!(relative(&root, "missing.py"), None);
1290        assert_eq!(relative(&root, "<frozen runpy>"), None);
1291        assert_eq!(relative(&root, "~"), None);
1292        std::fs::remove_dir_all(&root).unwrap();
1293    }
1294
1295    fn node(id: u64, name: &str, url: &str, line: i64, hits: u64, children: &[u64]) -> Value {
1296        json!({ "id": id, "hitCount": hits, "children": children,
1297                "callFrame": { "functionName": name, "url": url, "lineNumber": line - 1 } })
1298    }
1299
1300    #[test]
1301    fn node_writes_profile_to_a_temp_path_with_spaces() {
1302        if !Command::new("node")
1303            .arg("--version")
1304            .status()
1305            .is_ok_and(|s| s.success())
1306        {
1307            return;
1308        }
1309        let dir = crate::app::temp_dir("profile with spaces").unwrap();
1310        let root = dir.canonicalize().unwrap();
1311        let command = ["node".into(), "-e".into(), "console.log('workload')".into()];
1312        let result = super::node(&root, &command, &root);
1313        std::fs::remove_dir_all(dir).unwrap();
1314        assert!(result.unwrap().1 > 0.0);
1315    }
1316
1317    #[test]
1318    fn cpuprofile_times_and_callers() {
1319        let f = "file:///repo/src/search.ts";
1320        // (root) -> matched -> (anonymous) -> fuzzyScore -> fuzzyScore (recursion); 1 ms a sample.
1321        let profile = json!({
1322            "startTime": 0, "endTime": 10_000, "samples": vec![0; 10],
1323            "nodes": [
1324                node(1, "(root)", "", 0, 0, &[2]),
1325                node(2, "matched", f, 9, 1, &[3]),
1326                node(3, "", f, 10, 1, &[4]),
1327                node(4, "fuzzyScore", f, 2, 5, &[5]),
1328                node(5, "fuzzyScore", f, 2, 3, &[]),
1329            ],
1330        });
1331        let mut functions = HashMap::new();
1332        let ms = merge_cpuprofile(Path::new("/repo"), &profile, &mut functions);
1333        assert_eq!(ms, 10.0);
1334        let key = |n: &str, l: u32| ("src/search.ts".to_string(), n.to_string(), l);
1335        let fuzzy = &functions[&key("fuzzyScore", 2)];
1336        assert_eq!(
1337            (fuzzy.self_ms, fuzzy.total_ms),
1338            (8.0, 8.0),
1339            "recursion counts once"
1340        );
1341        // The caller is the named function, not the arrow callback in between.
1342        assert_eq!(
1343            fuzzy.callers.keys().collect::<Vec<_>>(),
1344            [&key("matched", 9)]
1345        );
1346        assert_eq!(functions[&key("matched", 9)].total_ms, 10.0);
1347        assert!(functions.contains_key(&key("(anonymous):10", 10)));
1348    }
1349
1350    #[test]
1351    fn cpuprofile_recognizes_encoded_paths_in_the_repository() {
1352        let root = Path::new("/repo/work area");
1353        let profile = json!({
1354            "startTime": 0,
1355            "endTime": 10_000,
1356            "samples": [1],
1357            "nodes": [node(1, "hot", "file:///repo/work%20area/step%23one%25.mjs", 0, 1, &[])],
1358        });
1359        let mut functions = HashMap::new();
1360        merge_cpuprofile(root, &profile, &mut functions);
1361        assert!(
1362            functions.contains_key(&("step#one%.mjs".into(), "hot".into(), 0)),
1363            "{:?}",
1364            functions.keys()
1365        );
1366        assert_eq!(
1367            relative(root, "/repo/work area/step%20.mjs").as_deref(),
1368            Some("step%20.mjs")
1369        );
1370    }
1371
1372    #[test]
1373    fn finds_the_argument_that_varies_per_item() {
1374        let root =
1375            std::env::temp_dir().join(format!("rust-anything-profile-{}", std::process::id()));
1376        std::fs::create_dir_all(&root).unwrap();
1377        std::fs::write(
1378            root.join("search.ts"),
1379            "export function matched(query: string, all: string[]) {\n  return all.map(key => ({ key, score: fuzzyScore(query, key) }))\n}\n",
1380        )
1381        .unwrap();
1382        std::fs::write(
1383            root.join("search.py"),
1384            "def best(q, keys):\n    for k in keys:\n        yield score(q, k)\n",
1385        )
1386        .unwrap();
1387        let params = ["query".to_string(), "text".to_string()];
1388        let caller = |file: &str, name: &str| (file.to_string(), name.to_string(), 1);
1389        assert_eq!(
1390            batch_param(
1391                &root,
1392                &caller("search.ts", "matched"),
1393                "fuzzyScore",
1394                &params
1395            )
1396            .as_deref(),
1397            Some("text")
1398        );
1399        assert_eq!(
1400            batch_param(&root, &caller("search.py", "best"), "score", &params).as_deref(),
1401            Some("text")
1402        );
1403        // `query` is the same for every item: no batch parameter to give.
1404        assert_eq!(
1405            batch_param(&root, &caller("search.ts", "matched"), "missing", &params),
1406            None
1407        );
1408        std::fs::remove_dir_all(&root).unwrap();
1409    }
1410
1411    #[test]
1412    fn go_names_and_pprof() {
1413        assert_eq!(go_name("example.com/strkit/strkit.Slugify"), "Slugify");
1414        assert_eq!(go_name("testing.(*B).runN"), "runN");
1415        assert_eq!(
1416            go_name("example.com/x/pkg.Outer.func2"),
1417            "(anonymous) in Outer"
1418        );
1419        let raw = "Samples:\nsamples/count cpu/nanoseconds\n          2   20000000: 1 2 \n          1   10000000: 3 2 \n\
1420                   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\
1421                   \x20            example.com/x/pkg.Slugify /repo/pkg/a.go:21:0 s=18\n\
1422                   \x20    2: 0x2 M=1 example.com/x/pkg.slugAll /repo/pkg/a_test.go:24:0 s=21\n\
1423                   \x20    3: 0x3 M=1 example.com/x/pkg.Slugify /repo/pkg/a.go:25:0 s=18\nMappings\n";
1424        let samples = parse_pprof_raw(Path::new("/repo"), raw);
1425        assert_eq!(samples.len(), 2);
1426        let key = |f: &str, n: &str, l: u32| Some((f.to_string(), n.to_string(), l));
1427        // Root first; the inlined Slugify sits between slugAll and strings.Map (not user code).
1428        assert_eq!(
1429            samples[0],
1430            (
1431                vec![
1432                    key("pkg/a_test.go", "slugAll", 21),
1433                    key("pkg/a.go", "Slugify", 18),
1434                    None
1435                ],
1436                20.0
1437            )
1438        );
1439        let mut functions = HashMap::new();
1440        merge_samples(&samples, &mut functions);
1441        let slug = &functions[&("pkg/a.go".to_string(), "Slugify".to_string(), 18)];
1442        assert_eq!((slug.total_ms, slug.self_ms), (30.0, 10.0));
1443        assert_eq!(slug.callers.values().map(|c| c.0).sum::<f64>(), 30.0);
1444    }
1445
1446    #[test]
1447    fn java_declarations() {
1448        let src = "class Strings {\n    public static String slugify(String text, int max) {\n        \
1449                   String s = slugify(text, 0);\n        return s;\n    }\n}\n";
1450        assert_eq!(java_declaration(src, "slugify", 4), Some(2));
1451        assert_eq!(java_declaration(src, "slugify", 1), None);
1452    }
1453
1454    #[test]
1455    fn loop_variables_in_go_java_ruby() {
1456        let (items, indexes) = loop_variables(
1457            "for _, t := range texts {\n\tSlugify(t, 30)\n}\nfor i := range xs {}\n\
1458             for (String w : words) {}\nfor (int j = 0; j < n; j++) {}\ntexts.map { |x| f(x) }\nxs.each do |y, k|\n",
1459        );
1460        assert_eq!(items, ["t", "w", "x", "y"]);
1461        assert_eq!(
1462            indexes,
1463            ["_", "i", "j"]
1464                .into_iter()
1465                .filter(|v| *v != "_")
1466                .collect::<Vec<_>>()
1467        );
1468    }
1469}