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