1use 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 pub ms: f64,
27 #[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 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 pub repo_pct: f64,
59 pub hot: Vec<Hot>,
60 #[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
73fn 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
99fn 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
128fn 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#[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
195fn 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; }
202 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
228fn 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
240fn in_repo(file: &str) -> bool {
242 !file.starts_with('/')
243}
244
245fn 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
273struct Frame {
275 key: Option<Key>,
276 self_ms: f64,
277 children: Vec<u64>,
278}
279
280fn 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 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 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 next.push(k.clone());
373 }
374 for c in children {
375 stack.push((*c, next.clone()));
376 }
377 }
378 duration_ms
379}
380
381const 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
433fn 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
467fn 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
496fn 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
511fn 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 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 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 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
600fn 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
642fn 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 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
670fn 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 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; 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 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
794const 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
846fn 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
872fn 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 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
943fn 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 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 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 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, ¶ms);
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 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 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 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 ¶ms
1302 )
1303 .as_deref(),
1304 Some("text")
1305 );
1306 assert_eq!(
1307 batch_param(&root, &caller("search.py", "best"), "score", ¶ms).as_deref(),
1308 Some("text")
1309 );
1310 assert_eq!(
1312 batch_param(&root, &caller("search.ts", "matched"), "missing", ¶ms),
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 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}