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