big_code_analysis/output/dump_metrics.rs
1//! Terminal per-metric dump serializer.
2//!
3//! The dump tree is driven by [`wire::CodeMetrics`] — the serialized
4//! metric shape — rather than hand-picking a per-metric subset of stats
5//! (issue #674). Projecting the compute metrics through the wire form and
6//! walking the resulting JSON object guarantees the dump's field set is
7//! *uniform by construction*: every leaf the JSON output carries appears
8//! here under the same key, and a new metric field shows up automatically
9//! with no edit to this file.
10//!
11//! Field *order* in this text view is serde_json's default sorted-key order
12//! (`Value::Object` is a `BTreeMap` because `preserve_order` is deliberately
13//! not enabled — see the root `Cargo.toml`), which is deterministic and
14//! differs from the JSON serializer's struct-field order. The uniform field
15//! *set* is what #674 requires; matching JSON's order would mean enabling
16//! `preserve_order` workspace-wide, which would perturb the frozen
17//! code-climate / SARIF fingerprint contracts (#559).
18//!
19//! The other deliberate divergence from JSON is presentation: float values
20//! render rounded to [`TEXT_FLOAT_DECIMALS`] decimals in this text view,
21//! whereas JSON keeps full precision. Non-finite floats (which serialize
22//! to JSON `null`) render as `NaN`, matching the prior dump and the
23//! human-readable `numfmt` arm.
24
25use termcolor::{Color, WriteColor};
26
27use serde_json::Value;
28
29use crate::output::color::print_to_stdout;
30use crate::output::numfmt::F64_SAFE_INT_BOUND;
31use crate::output::{ColorMode, branch_glyphs};
32use crate::spaces::{CodeMetrics, FuncSpace};
33use crate::wire;
34
35use crate::tools::{color, intense_color};
36
37/// Decimal places used when rendering a non-integer float in the text
38/// dump. JSON output keeps full precision; the terminal view trades the
39/// trailing noise for legibility (issue #674).
40const TEXT_FLOAT_DECIMALS: usize = 2;
41
42/// Dumps the metrics of a code.
43///
44/// Returns a [`Result`] value, when an error occurs.
45///
46/// # Errors
47///
48/// Propagates any [`std::io::Error`] produced by the color-aware
49/// writer that backs `stdout` (broken pipe, write failure, …).
50///
51/// # Examples
52///
53/// ```
54/// use big_code_analysis::{analyze, dump_root, LANG, MetricsOptions, Source};
55///
56/// // Compute metrics via the non-generic `analyze` entry point.
57/// let space = analyze(
58/// Source::new(LANG::Cpp, b"int a = 42;"),
59/// MetricsOptions::default(),
60/// )
61/// .expect("snippet has a top-level FuncSpace");
62///
63/// // Dump all metrics
64/// dump_root(&space).unwrap();
65/// ```
66pub fn dump_root(space: &FuncSpace) -> std::io::Result<()> {
67 dump_root_with_color(space, ColorMode::Always)
68}
69
70/// Like [`dump_root`], but the caller selects the [`ColorMode`].
71///
72/// `bca` resolves a `--color` flag, the `NO_COLOR` convention, and
73/// stdout tty detection into a mode and passes it here so piped output
74/// is escape-free by default. The bare [`dump_root`] keeps the
75/// historical always-colored behavior for backward compatibility.
76///
77/// # Errors
78///
79/// Propagates any [`std::io::Error`] produced by the color-aware
80/// writer that backs `stdout` (broken pipe, write failure, …).
81pub fn dump_root_with_color(space: &FuncSpace, color_mode: ColorMode) -> std::io::Result<()> {
82 print_to_stdout(color_mode, |stdout| {
83 dump_space(space, stdout)?;
84 color(stdout, Color::White)
85 })
86}
87
88/// One pending space in the walk: the space, the length its indentation
89/// prefix has in the shared buffer, and whether it is its parent's last
90/// child.
91///
92/// The prefix is a *length* rather than an owned copy (#1054): prefixes
93/// only grow as the walk descends, so the first `prefix_len` bytes stay
94/// this space's prefix until it is popped. Owning one prefix per stack
95/// entry cost O(depth²) resident bytes on a deep closure nest.
96type SpaceFrame<'a> = (&'a FuncSpace, usize, bool);
97
98/// Dump the `FuncSpace` metric tree with an explicit work stack rather
99/// than recursion, so a pathologically deep space nesting (closures
100/// within closures) cannot overflow the thread stack at dump time — an
101/// uncatchable abort, forbidden by the no-panic rule (#700). Traversal
102/// order and per-node glyphs are byte-identical to the prior recursive
103/// form.
104fn dump_space(space: &FuncSpace, stdout: &mut dyn WriteColor) -> std::io::Result<()> {
105 let mut prefix = String::new();
106 let mut stack: Vec<SpaceFrame> = vec![(space, 0, true)];
107
108 while let Some((space, prefix_len, last)) = stack.pop() {
109 // Truncating on every visit — rather than on the way back up —
110 // is what lets a frame carry a bare length: whatever a sibling's
111 // subtree appended is dropped here. Recorded lengths always sit
112 // on a char boundary because only whole glyph runs are appended.
113 prefix.truncate(prefix_len);
114 let (pref_child, pref) = branch_glyphs(last);
115
116 color(stdout, Color::Blue)?;
117 write!(stdout, "{prefix}{pref}")?;
118
119 intense_color(stdout, Color::Yellow)?;
120 write!(stdout, "{}: ", space.kind)?;
121
122 intense_color(stdout, Color::Cyan)?;
123 write!(stdout, "{}", space.name.as_ref().map_or("", |name| name))?;
124
125 intense_color(stdout, Color::Red)?;
126 writeln!(stdout, " (@{})", space.start_line)?;
127
128 prefix.push_str(pref_child);
129 let child_prefix_len = prefix.len();
130 dump_metrics(&space.metrics, &mut prefix, space.spaces.is_empty(), stdout)?;
131
132 // Push children in reverse so `pop()` visits them in source
133 // order; the final child carries `last = true` for the closing
134 // `` `- `` glyph, matching the recursive `split_last` form.
135 let count = space.spaces.len();
136 for (i, child) in space.spaces.iter().enumerate().rev() {
137 stack.push((child, child_prefix_len, i + 1 == count));
138 }
139 }
140
141 Ok(())
142}
143
144/// Render a space's `metrics` subtree. `prefix` is the shared
145/// indentation buffer; it is extended in place for the metric groups and
146/// left extended — every caller either truncates back or is the space
147/// walk, which re-truncates on its next visit.
148fn dump_metrics(
149 metrics: &CodeMetrics,
150 prefix: &mut String,
151 last: bool,
152 stdout: &mut dyn WriteColor,
153) -> std::io::Result<()> {
154 let (pref_child, pref) = branch_glyphs(last);
155
156 color(stdout, Color::Blue)?;
157 write!(stdout, "{prefix}{pref}")?;
158
159 intense_color(stdout, Color::Yellow)?;
160 writeln!(stdout, "metrics")?;
161
162 // Project the compute metrics through the wire shape and walk the
163 // serialized object so the dump's field set is the JSON field set
164 // exactly (issue #674). Disabled class-only metrics (`wmc`/`npm`/`npa`
165 // on a non-class language) are already elided by the `From` impl, so
166 // they never appear in the object and need no per-metric guard here.
167 let wire_metrics = wire::CodeMetrics::from(metrics);
168 let Value::Object(groups) = serde_json::to_value(&wire_metrics).unwrap_or(Value::Null) else {
169 return Ok(());
170 };
171
172 prefix.push_str(pref_child);
173 let group_prefix_len = prefix.len();
174 let last_index = groups.len().saturating_sub(1);
175 for (index, (name, value)) in groups.iter().enumerate() {
176 prefix.truncate(group_prefix_len);
177 dump_group(name, value, prefix, index == last_index, stdout)?;
178 }
179 Ok(())
180}
181
182/// Render one metric group (`cognitive`, `loc`, …) as a green-labelled
183/// subtree, then walk its leaves. A nested object leaf (e.g.
184/// `cyclomatic.modified`) recurses as its own subtree, so the rendered
185/// shape always mirrors the JSON nesting.
186///
187/// Extends the shared `prefix` in place for the group's leaves and leaves
188/// it extended; callers truncate back before the next sibling.
189fn dump_group(
190 name: &str,
191 value: &Value,
192 prefix: &mut String,
193 last: bool,
194 stdout: &mut dyn WriteColor,
195) -> std::io::Result<()> {
196 let (pref_child, pref) = branch_glyphs(last);
197
198 color(stdout, Color::Blue)?;
199 write!(stdout, "{prefix}{pref}")?;
200
201 intense_color(stdout, Color::Green)?;
202 writeln!(stdout, "{name}")?;
203
204 prefix.push_str(pref_child);
205 dump_object(value, prefix, stdout)
206}
207
208/// Walk the leaves of a metric object, emitting one `name: value` line
209/// per scalar and recursing into any nested object (rendered as a green
210/// subtree, matching the JSON nesting). A non-object value is ignored
211/// (the wire metric groups are always objects).
212///
213/// Truncating the shared `prefix` back to this object's level before each
214/// field is what keeps a nested group from indenting its siblings.
215fn dump_object(
216 value: &Value,
217 prefix: &mut String,
218 stdout: &mut dyn WriteColor,
219) -> std::io::Result<()> {
220 let Value::Object(fields) = value else {
221 return Ok(());
222 };
223 let field_prefix_len = prefix.len();
224 let last_index = fields.len().saturating_sub(1);
225 for (index, (name, leaf)) in fields.iter().enumerate() {
226 let last = index == last_index;
227 prefix.truncate(field_prefix_len);
228 if leaf.is_object() {
229 dump_group(name, leaf, prefix, last, stdout)?;
230 } else {
231 dump_value(name, leaf, prefix, last, stdout)?;
232 }
233 }
234 Ok(())
235}
236
237/// Emit a single `name: value` leaf. Floats render rounded to
238/// [`TEXT_FLOAT_DECIMALS`] decimals (text view only — JSON keeps full
239/// precision); integers print verbatim; a JSON `null` (a non-finite
240/// metric) renders as `NaN`, matching the prior dump.
241fn dump_value(
242 name: &str,
243 value: &Value,
244 prefix: &str,
245 last: bool,
246 stdout: &mut dyn WriteColor,
247) -> std::io::Result<()> {
248 let pref = if last { "`- " } else { "|- " };
249
250 color(stdout, Color::Blue)?;
251 write!(stdout, "{prefix}{pref}")?;
252
253 intense_color(stdout, Color::Magenta)?;
254 write!(stdout, "{name}: ")?;
255
256 color(stdout, Color::White)?;
257 writeln!(stdout, "{}", format_leaf(value))
258}
259
260/// Format a scalar wire leaf for the text view. Integral numbers print
261/// without a decimal point; non-integral floats round to
262/// [`TEXT_FLOAT_DECIMALS`] places; `null` (a non-finite metric) becomes
263/// `NaN`.
264fn format_leaf(value: &Value) -> String {
265 match value {
266 Value::Null => "NaN".to_owned(),
267 Value::Number(n) => format_number(n),
268 // The wire metric leaves are only numbers or null; render anything
269 // else verbatim rather than panicking on an unexpected shape.
270 other => other.to_string(),
271 }
272}
273
274/// Render a JSON number: an integer prints without a decimal point; a
275/// float rounds to [`TEXT_FLOAT_DECIMALS`] places, after which a trailing
276/// `.00` is dropped so a whole-valued average reads like a count.
277fn format_number(n: &serde_json::Number) -> String {
278 if let Some(int) = n.as_u64() {
279 return int.to_string();
280 }
281 if let Some(int) = n.as_i64() {
282 return int.to_string();
283 }
284 let Some(float) = n.as_f64() else {
285 return n.to_string();
286 };
287 // A safe-integer-valued float (e.g. an exact `2.0` average) prints as
288 // an integer. This *diverges* from the JSON serializer, which keeps
289 // the `.0` (serde_json renders `2.0` as `"2.0"`, not `"2"`); the dump
290 // drops it deliberately for terminal legibility, the same presentation
291 // tradeoff the module header documents for rounded floats (#674).
292 if float.fract() == 0.0 && float.abs() < F64_SAFE_INT_BOUND {
293 #[allow(clippy::cast_possible_truncation)]
294 return (float as i64).to_string();
295 }
296 format!("{float:.TEXT_FLOAT_DECIMALS$}")
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302 use crate::metric_set::Metric;
303 use crate::{LANG, MetricsOptions, Source, analyze};
304
305 fn render(space: &FuncSpace) -> String {
306 let mut buf = termcolor::NoColor::new(Vec::new());
307 dump_space(space, &mut buf).expect("dump to in-memory buffer");
308 String::from_utf8(buf.into_inner()).expect("utf-8 dump")
309 }
310
311 #[test]
312 fn fields_after_a_nested_metric_object_resume_the_group_rail() {
313 // `cyclomatic.modified` is the one metric group that nests
314 // another object, and `sum` / `value` follow it. Rendering the
315 // nested group extends the shared indentation buffer (#1054), so
316 // those two trailing fields only land back on the `cyclomatic`
317 // rail if `dump_object` truncates before each field, and the
318 // group *after* cyclomatic only lands back on the metrics rail
319 // if the group loop truncates too. Nothing else in the suite
320 // exercises a nested group's siblings.
321 //
322 // The whole block is compared as a line sequence rather than
323 // with per-rail `contains` checks: `sum` and `value` are fields
324 // of several groups, and a deeper rail ends with the shallower
325 // one, so a substring search accepts both the wrong group and
326 // the exact mis-indentation this test exists to catch.
327 let space = analyze(
328 Source::new(LANG::Cpp, b"int a = 42;"),
329 MetricsOptions::default(),
330 )
331 .expect("snippet has a top-level FuncSpace");
332 let out = render(&space);
333
334 // Values are dropped: this pins indentation, not metric numbers.
335 let rails: Vec<&str> = out
336 .lines()
337 .skip_while(|line| *line != " |- cyclomatic")
338 .take_while(|line| !line.starts_with(" |- halstead"))
339 .map(|line| line.split_once(": ").map_or(line, |(rail, _)| rail))
340 .collect();
341 assert_eq!(
342 rails,
343 vec![
344 " |- cyclomatic",
345 " | |- average",
346 " | |- max",
347 " | |- min",
348 " | |- modified",
349 " | | |- average",
350 " | | |- max",
351 " | | |- min",
352 " | | |- sum",
353 " | | `- value",
354 " | |- sum",
355 " | `- value",
356 ],
357 "cyclomatic's rails must survive the nested `modified` \
358 object:\n{out}"
359 );
360 assert!(
361 out.lines().any(|line| line == " |- halstead"),
362 "the group after cyclomatic must be back on the metrics \
363 rail:\n{out}"
364 );
365 }
366
367 #[test]
368 fn sibling_space_after_a_nested_one_resumes_its_own_rail() {
369 // The walk keeps one shared indentation buffer that is extended
370 // on descent and truncated on the next visit (#1054), and the
371 // metric groups under each space extend it further still. `after`
372 // is a top-level sibling that follows `outer`'s deeper subtree
373 // and its whole metrics block, so a truncation bug leaves it
374 // indented under `inner`'s rail. Built by hand — `FuncSpace` has
375 // an iterative `Drop` (#1056), so struct-update syntax cannot
376 // move fields out of it.
377 //
378 // The expected rails are what the pre-#1054 binary emits for the
379 // equivalent parsed tree (`function outer(){function inner(){}}
380 // function after(){}`).
381 use crate::spaces::SpaceKind;
382 let func = |name: &str, line: usize, spaces: Vec<FuncSpace>| FuncSpace {
383 name: Some(name.to_string()),
384 start_line: line,
385 end_line: line,
386 kind: SpaceKind::Function,
387 spaces,
388 metrics: CodeMetrics::default(),
389 suppressed: crate::SuppressionScope::default(),
390 };
391 let space = FuncSpace {
392 name: Some("u".to_string()),
393 start_line: 1,
394 end_line: 4,
395 kind: SpaceKind::Unit,
396 spaces: vec![
397 func("outer", 1, vec![func("inner", 2, vec![])]),
398 func("after", 4, vec![]),
399 ],
400 metrics: CodeMetrics::default(),
401 suppressed: crate::SuppressionScope::default(),
402 };
403
404 let out = render(&space);
405 let rails: Vec<&str> = out
406 .lines()
407 .filter(|line| line.contains("(@") || line.ends_with("- metrics"))
408 .collect();
409 assert_eq!(
410 rails,
411 vec![
412 "`- unit: u (@1)",
413 " |- metrics",
414 " |- function: outer (@1)",
415 " | |- metrics",
416 " | `- function: inner (@2)",
417 " | `- metrics",
418 " `- function: after (@4)",
419 " `- metrics",
420 ],
421 "space and metric-block rails must survive the shared prefix \
422 buffer's truncate/extend cycle:\n{out}"
423 );
424 }
425
426 #[test]
427 fn selection_mask_omits_unselected_metric_groups() {
428 // `with_only(&[Loc])` must restrict the dump to the loc group:
429 // the wire-driven projection (#674) elides unselected metrics, so
430 // they never appear in the walked JSON object. A pre-#674 dump
431 // printed all groups with default/zero stats, contradicting the
432 // serialized "present => selected" contract (#700).
433 let space = analyze(
434 Source::new(LANG::Cpp, b"int a = 42;"),
435 MetricsOptions::default().with_only(&[Metric::Loc]),
436 )
437 .expect("snippet has a top-level FuncSpace");
438 let out = render(&space);
439 assert!(out.contains("loc\n"), "loc group must be present:\n{out}");
440 for omitted in ["cognitive", "cyclomatic", "halstead", "nom", "abc"] {
441 assert!(
442 !out.contains(&format!("{omitted}\n")),
443 "unselected `{omitted}` group must be omitted:\n{out}"
444 );
445 }
446 }
447
448 #[test]
449 fn last_emitted_metric_group_uses_closing_connector() {
450 // The genuinely-last emitted metric group must carry the closing
451 // `` `- `` glyph rather than a dangling `|-` (#700, already made
452 // dynamic by the wire projection in #674). For a non-class C
453 // dump, the wmc/npm/npa class-only groups are elided, so the last
454 // group line under the root `metrics` subtree must end the
455 // subtree with `` `- ``.
456 let space = analyze(
457 Source::new(LANG::Cpp, b"int a = 42;"),
458 MetricsOptions::default(),
459 )
460 .expect("snippet has a top-level FuncSpace");
461 let out = render(&space);
462
463 // Group lines sit six columns in: three for the root space's own
464 // `` `- `` (it is the only space) and three more for the
465 // `metrics` line's. Filtering at three columns instead matched
466 // only the `metrics` line itself, so this test passed even with
467 // every group rendering `|-`.
468 let group_lines: Vec<&str> = out
469 .lines()
470 .filter(|line| line.starts_with(" |- ") || line.starts_with(" `- "))
471 .collect();
472 assert!(
473 group_lines.len() > 1,
474 "expected several metric groups under the root:\n{out}"
475 );
476 let last_group = group_lines.last().expect("at least one metric group");
477 assert!(
478 last_group.starts_with(" `- "),
479 "the last emitted metric group must use the closing connector, got: {last_group:?}\n{out}"
480 );
481 assert!(
482 group_lines[..group_lines.len() - 1]
483 .iter()
484 .all(|line| line.starts_with(" |- ")),
485 "every group but the last must use the mid-child connector:\n{out}"
486 );
487 }
488
489 #[test]
490 fn deeply_nested_spaces_dump_without_stack_overflow() {
491 // The space walk is iterative (#700): a deep chain of nested
492 // function spaces must dump without overflowing the thread stack.
493 // Run on a small-stack thread so a recursion regression fails
494 // loudly rather than relying on the test-runner stack.
495 use crate::spaces::SpaceKind;
496 const DEPTH: usize = 8_000;
497 let handle = std::thread::Builder::new()
498 .stack_size(512 * 1024)
499 .spawn(|| {
500 let leaf = || FuncSpace {
501 name: Some("f".to_string()),
502 start_line: 1,
503 end_line: 1,
504 kind: SpaceKind::Function,
505 spaces: Vec::new(),
506 metrics: CodeMetrics::default(),
507 suppressed: crate::SuppressionScope::default(),
508 };
509 let mut root = leaf();
510 let mut cursor = &mut root;
511 for _ in 0..DEPTH {
512 cursor.spaces.push(leaf());
513 cursor = cursor.spaces.last_mut().expect("just pushed");
514 }
515 // Discard the bytes rather than buffering them: a
516 // depth-8000 chain renders ~8000 metric blocks, each
517 // line carrying ~3 x depth bytes of indentation, so a
518 // `Vec` sink held ~10 GB and made the unit suite an
519 // out-of-memory hazard. Nothing here asserts on the
520 // text, and every write still runs.
521 let mut sink = termcolor::NoColor::new(std::io::sink());
522 let ok = dump_space(&root, &mut sink).is_ok();
523 // `root` drops here without flattening: `FuncSpace`'s
524 // `Drop` is iterative as of #1056, so teardown costs no
525 // stack depth and cannot mask the dump result.
526 ok
527 })
528 .expect("spawn dump thread");
529 assert!(
530 handle.join().expect("dump thread must not overflow"),
531 "deep space nesting must dump successfully"
532 );
533 }
534
535 /// Value printed after `{field}:` in the FIRST `{block}` metric block of
536 /// the dump — i.e. the root `Unit`'s, which is emitted before any child
537 /// space. `{val}` Display renders whole f64s without a decimal point, so
538 /// callers can compare against `"0"`.
539 fn root_block_field(out: &str, block: &str, field: &str) -> String {
540 let body = &out[out
541 .find(&format!("{block}\n"))
542 .expect("metric block present")..];
543 let at = body.find(&format!("{field}: ")).expect("field present") + field.len() + 2;
544 body[at..].lines().next().unwrap_or("").trim().to_owned()
545 }
546
547 /// Regression for the parent-space aggregate bug: `dump_nom` / `dump_nargs`
548 /// must print the SUBTREE-AGGREGATE counts (`functions_sum` / `fn_args_sum`,
549 /// matching the JSON serializer and `Display`), not the space's IMMEDIATE
550 /// counts — which are 0 at any parent whose functions all live in a nested
551 /// module/impl, and would not sum to the aggregate `total`.
552 #[test]
553 fn dump_nom_and_nargs_use_subtree_aggregates_at_parent_space() {
554 // The one function (with args) is nested in `mod m`, so the root Unit's
555 // immediate function/arg counts are 0 while the subtree aggregates are
556 // not — the exact shape that exposed the bug.
557 let space = analyze(
558 Source::new(
559 LANG::Rust,
560 b"mod m { fn a(x: i32, y: i32) -> i32 { x + y } }",
561 ),
562 MetricsOptions::default(),
563 )
564 .expect("snippet has a top-level FuncSpace");
565
566 let mut buf = termcolor::NoColor::new(Vec::new());
567 dump_space(&space, &mut buf).expect("dump to in-memory buffer");
568 let out = String::from_utf8(buf.into_inner()).expect("utf-8 dump");
569
570 assert_ne!(
571 root_block_field(&out, "nom", "functions"),
572 "0",
573 "root nom must print functions_sum (aggregate), not the immediate 0:\n{out}"
574 );
575 assert_ne!(
576 root_block_field(&out, "nargs", "functions"),
577 "0",
578 "root nargs must print fn_args_sum (aggregate), not the immediate 0:\n{out}"
579 );
580 }
581
582 /// Regression for #562: the two Halstead dump labels must use the
583 /// underscore key that matches the JSON/CSV key name, so a user can grep
584 /// the same token across `dump` and JSON. The space-separated forms
585 /// (`estimated program length` / `purity ratio`) were the only outliers.
586 #[test]
587 fn dump_halstead_labels_use_underscore_keys() {
588 let space = analyze(
589 Source::new(LANG::Cpp, b"int a = 42;"),
590 MetricsOptions::default(),
591 )
592 .expect("snippet has a top-level FuncSpace");
593
594 let mut buf = termcolor::NoColor::new(Vec::new());
595 dump_space(&space, &mut buf).expect("dump to in-memory buffer");
596 let out = String::from_utf8(buf.into_inner()).expect("utf-8 dump");
597
598 assert!(
599 out.contains("estimated_program_length: "),
600 "dump must use the underscore key `estimated_program_length`:\n{out}"
601 );
602 assert!(
603 out.contains("purity_ratio: "),
604 "dump must use the underscore key `purity_ratio`:\n{out}"
605 );
606 assert!(
607 !out.contains("estimated program length"),
608 "dump must not emit the space-separated `estimated program length`:\n{out}"
609 );
610 assert!(
611 !out.contains("purity ratio"),
612 "dump must not emit the space-separated `purity ratio`:\n{out}"
613 );
614 }
615}