Skip to main content

rust_anything/
profile.rs

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