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