Skip to main content

rust_anything/
profile.rs

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