big-code-analysis 2.0.0

Tool to compute and export code metrics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Per-language metric and AST modules deliberately consume the macro-
// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
// inside match expressions — explicit imports would list dozens of
// variants per arm and obscure the per-language token sets that are the
// point of these files. Allowed at the module level rather than per
// function so the per-language impl blocks stay readable.
#![allow(clippy::enum_glob_use, clippy::ref_option, clippy::wildcard_imports)]

use termcolor::{Color, StandardStream, WriteColor};

use crate::node::Node;
use crate::output::ColorMode;
use crate::tools::{color, intense_color};

/// Dumps the `AST` of a code.
///
/// Returns a [`Result`] value, when an error occurs.
///
/// # Errors
///
/// Propagates any [`std::io::Error`] produced by the color-aware
/// writer that backs `stdout` (broken pipe, write failure, …).
///
/// # Examples
///
/// ```
/// use big_code_analysis::{dump_node, Ast, LANG, Source};
///
/// let source = b"int a = 42;";
/// let ast = Ast::parse(Source::new(LANG::Cpp, source))
///     .expect("cpp feature enabled");
/// let root = ast.root_node();
///
/// // Dump the AST from the first line of code in a file to the last one
/// dump_node(ast.source(), &root, -1, None, None).unwrap();
/// ```
///
/// # Panics
///
/// Panics if `code` is not the exact source `node` was parsed from.
/// `node`'s byte range is used to slice `code`, so a `node` taken from a
/// different (or smaller) tree indexes out of bounds. Always pair a node
/// with the source it came from — e.g. `ast.source()` and a node obtained
/// from the *same* [`crate::Ast`] (`ast.root_node()` or a descendant).
pub fn dump_node(
    code: &[u8],
    node: &Node,
    depth: i32,
    line_start: Option<usize>,
    line_end: Option<usize>,
) -> std::io::Result<()> {
    dump_node_with_color(code, node, depth, line_start, line_end, ColorMode::Always)
}

/// Like [`dump_node`], but the caller selects the [`ColorMode`].
///
/// `bca` resolves a `--color` flag, the `NO_COLOR` convention, and
/// stdout tty detection into a mode and passes it here so piped output
/// is escape-free by default. The bare [`dump_node`] keeps the
/// historical always-colored behavior for backward compatibility.
///
/// # Errors
///
/// Propagates any [`std::io::Error`] produced by the color-aware
/// writer that backs `stdout` (broken pipe, write failure, …).
///
/// # Panics
///
/// Panics if `code` is not the exact source `node` was parsed from.
/// `node`'s byte range is used to slice `code`, so a `node` taken from a
/// different (or smaller) tree indexes out of bounds. Always pair a node
/// with the source it came from — e.g. `ast.source()` and a node obtained
/// from the *same* [`crate::Ast`] (`ast.root_node()` or a descendant).
pub fn dump_node_with_color(
    code: &[u8],
    node: &Node,
    depth: i32,
    line_start: Option<usize>,
    line_end: Option<usize>,
    color_mode: ColorMode,
) -> std::io::Result<()> {
    let stdout = StandardStream::stdout(color_mode.to_color_choice());
    let mut stdout = stdout.lock();
    let mut state = DumpState {
        code,
        line_start: &line_start,
        line_end: &line_end,
        stdout: &mut stdout,
    };
    let ret = dump_tree_helper(&mut state, node, "", true, depth);

    color(&mut stdout, Color::White)?;

    ret
}

/// Recursion-invariant rendering state threaded through the AST walk:
/// the source bytes, the optional line-range filter, and the colored
/// writer. Bundling these keeps every walk function under the
/// argument-count limit (the pre-split helper carried eight arguments)
/// and lets tests substitute a `termcolor::NoColor` sink over a
/// `Vec<u8>` for byte-exact output assertions.
struct DumpState<'a> {
    code: &'a [u8],
    line_start: &'a Option<usize>,
    line_end: &'a Option<usize>,
    stdout: &'a mut dyn WriteColor,
}

/// One pending node in the iterative AST walk: the node, the box-drawing
/// prefix accumulated from its ancestors, whether it is the last child of
/// its parent (which selects its connector glyph), and the remaining
/// depth budget.
struct Frame<'a> {
    node: Node<'a>,
    prefix: String,
    last: bool,
    depth: i32,
}

/// Render the subtree rooted at `node` with an explicit work stack rather
/// than recursion. A pathologically deep AST (thousands of nested
/// expressions, which the iterative *builder* in tree-sitter accepts
/// without bound) would otherwise overflow the thread stack at dump time
/// — an uncatchable abort, forbidden by the no-panic rule. The traversal
/// order, per-node glyphs, and depth semantics are byte-identical to the
/// prior recursive form (#700).
fn dump_tree_helper(
    state: &mut DumpState,
    node: &Node,
    prefix: &str,
    last: bool,
    depth: i32,
) -> std::io::Result<()> {
    let mut stack: Vec<Frame> = vec![Frame {
        node: *node,
        prefix: prefix.to_owned(),
        last,
        depth,
    }];

    while let Some(Frame {
        node,
        prefix,
        last,
        depth,
    }) = stack.pop()
    {
        if depth == 0 {
            continue;
        }

        let (pref_child, pref) = branch_glyphs(&node, last);

        if line_in_range(node.start_row() + 1, state.line_start, state.line_end) {
            write_node_line(state.stdout, state.code, &node, &prefix, pref)?;
        }

        let count = node.child_count();
        if count == 0 {
            continue;
        }

        // Children share one extended prefix. Push them in reverse so
        // `pop()` visits them in source order, matching the recursive
        // form's pre-order traversal. `Children` is not a
        // `DoubleEndedIterator`, so collect first, then walk the indices
        // backwards.
        let child_prefix = format!("{prefix}{pref_child}");
        let child_depth = depth - 1;
        let children: Vec<Node> = node.children().collect();
        for (i, child) in children.into_iter().enumerate().rev() {
            stack.push(Frame {
                node: child,
                prefix: child_prefix.clone(),
                last: i + 1 == count,
                depth: child_depth,
            });
        }
    }

    Ok(())
}

/// Box-drawing prefixes for `node` as `(pref_child, pref)`. The root
/// (no parent) renders flush-left regardless of `last`; this check must
/// stay first because `dump_node` passes `last = true` for the root.
fn branch_glyphs(node: &Node, last: bool) -> (&'static str, &'static str) {
    if node.parent().is_none() {
        ("", "")
    } else if last {
        ("   ", "╰─ ")
    } else {
        ("", "├─ ")
    }
}

/// Whether 1-based `row` falls within the optional `[line_start,
/// line_end]` filter. Either bound being `None` leaves that side
/// unconstrained, so `(None, None)` always shows the node.
fn line_in_range(row: usize, line_start: &Option<usize>, line_end: &Option<usize>) -> bool {
    line_start.is_none_or(|start| row >= start) && line_end.is_none_or(|end| row <= end)
}

/// Set `c` then write `args` in that color. Collapsing the recurring
/// set-color-then-write pair into one fallible call keeps each writer
/// helper's exit count under the threshold.
fn paint(stdout: &mut dyn WriteColor, c: Color, args: std::fmt::Arguments) -> std::io::Result<()> {
    color(stdout, c)?;
    stdout.write_fmt(args)
}

/// Emit the full colored description line for one node: header, position
/// range, optional same-row snippet, then the trailing newline (always,
/// even for multi-row nodes whose snippet is skipped).
fn write_node_line(
    stdout: &mut dyn WriteColor,
    code: &[u8],
    node: &Node,
    prefix: &str,
    pref: &str,
) -> std::io::Result<()> {
    write_node_header(stdout, node, prefix, pref)?;
    write_node_location(stdout, node)?;
    write_node_snippet(stdout, code, node)?;
    writeln!(stdout)
}

/// Prefix glyphs followed by the `{kind:kind_id}` tag.
fn write_node_header(
    stdout: &mut dyn WriteColor,
    node: &Node,
    prefix: &str,
    pref: &str,
) -> std::io::Result<()> {
    paint(stdout, Color::Blue, format_args!("{prefix}{pref}"))?;
    intense_color(stdout, Color::Yellow)?;
    write!(stdout, "{{{}:{}}} ", node.kind(), node.kind_id())
}

/// The `from (row, col) to (row, col)` 1-based position range.
fn write_node_location(stdout: &mut dyn WriteColor, node: &Node) -> std::io::Result<()> {
    paint(stdout, Color::White, format_args!("from "))?;
    let (row, column) = node.start_position();
    paint(
        stdout,
        Color::Green,
        format_args!("({}, {}) ", row + 1, column + 1),
    )?;
    paint(stdout, Color::White, format_args!("to "))?;
    let (row, column) = node.end_position();
    paint(
        stdout,
        Color::Green,
        format_args!("({}, {}) ", row + 1, column + 1),
    )
}

/// Source snippet for single-row nodes only. Multi-row nodes return
/// without writing (the caller still emits the trailing newline).
/// Non-UTF-8 spans fall back to raw bytes — regression guard
/// `dump_node_non_utf8_source_does_not_panic`.
fn write_node_snippet(
    stdout: &mut dyn WriteColor,
    code: &[u8],
    node: &Node,
) -> std::io::Result<()> {
    if node.start_row() != node.end_row() {
        return Ok(());
    }

    paint(stdout, Color::White, format_args!(": "))?;
    intense_color(stdout, Color::Red)?;
    let snippet = &code[node.start_byte()..node.end_byte()];
    match str::from_utf8(snippet) {
        Ok(text) => write!(stdout, "{text} "),
        Err(_) => stdout.write_all(snippet),
    }
}

#[cfg(test)]
#[allow(
    clippy::float_cmp,
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::similar_names,
    clippy::doc_markdown,
    clippy::needless_raw_string_hashes,
    clippy::too_many_lines
)]
mod tests {
    use std::path::PathBuf;

    use termcolor::NoColor;

    use crate::{CppParser, ParserTrait};

    use super::*;

    #[test]
    fn dump_node_non_utf8_source_does_not_panic() {
        // Regression: `stdout.write_all(code).unwrap()` panicked when the raw-bytes
        // fallback branch was taken for non-UTF-8 source content.
        let code = b"char c = '\xff';";
        let path = PathBuf::from("test.c");
        let parser = CppParser::new(code.to_vec(), &path, None);
        let root = parser.root();
        assert!(dump_node(code, &root, -1, None, None).is_ok());
    }

    #[test]
    fn line_in_range_unbounded_always_shows() {
        // Both bounds `None` is the "dump everything" default.
        assert!(line_in_range(5, &None, &None));
        assert!(line_in_range(1, &None, &None));
    }

    #[test]
    fn line_in_range_respects_inclusive_bounds() {
        // Lower bound only.
        assert!(line_in_range(5, &Some(3), &None));
        assert!(!line_in_range(2, &Some(3), &None));
        // Upper bound only.
        assert!(line_in_range(5, &None, &Some(6)));
        assert!(!line_in_range(7, &None, &Some(6)));
        // Both bounds AND-composed.
        assert!(line_in_range(5, &Some(3), &Some(6)));
        assert!(!line_in_range(5, &Some(6), &Some(9))); // below start
        assert!(!line_in_range(5, &Some(1), &Some(4))); // above end
        // Bounds are inclusive on both ends.
        assert!(line_in_range(3, &Some(3), &Some(3)));
    }

    #[test]
    fn branch_glyphs_root_is_flush_left_regardless_of_last() {
        let code = b"int a = 42;\n";
        let parser = CppParser::new(code.to_vec(), &PathBuf::from("t.c"), None);
        let root = parser.root();
        // The root has no parent: empty prefixes whatever `last` says.
        assert_eq!(branch_glyphs(&root, true), ("", ""));
        assert_eq!(branch_glyphs(&root, false), ("", ""));

        let child = root
            .children()
            .next()
            .expect("translation_unit has a child");
        assert_eq!(branch_glyphs(&child, true), ("   ", "╰─ "));
        assert_eq!(branch_glyphs(&child, false), ("", "├─ "));
    }

    #[test]
    fn dump_output_matches_expected_tree() {
        // Byte-exact guard that the split preserves the rendered tree.
        // `NoColor` discards color directives, so the captured bytes are
        // the plain text a user sees (the colored CLI output stripped of
        // ANSI). Expected values were captured from the pre-split code.
        let code = b"int a = 42;\n";
        let parser = CppParser::new(code.to_vec(), &PathBuf::from("t.c"), None);
        let root = parser.root();

        let no_start: Option<usize> = None;
        let no_end: Option<usize> = None;
        let mut sink = NoColor::new(Vec::new());
        {
            let mut state = DumpState {
                code,
                line_start: &no_start,
                line_end: &no_end,
                stdout: &mut sink,
            };
            dump_tree_helper(&mut state, &root, "", true, -1).expect("dump to in-memory sink");
        }
        let rendered = String::from_utf8(sink.into_inner()).expect("dump output is utf-8");

        let expected = concat!(
            "{translation_unit:219} from (1, 1) to (2, 1) \n",
            "╰─ {declaration:255} from (1, 1) to (1, 12) : int a = 42; \n",
            "   ├─ {primitive_type:96} from (1, 1) to (1, 4) : int \n",
            "   ├─ {init_declarator:294} from (1, 5) to (1, 11) : a = 42 \n",
            "   │  ├─ {identifier:1} from (1, 5) to (1, 6) : a \n",
            "   │  ├─ {=:74} from (1, 7) to (1, 8) : = \n",
            "   │  ╰─ {number_literal:158} from (1, 9) to (1, 11) : 42 \n",
            "   ╰─ {;:42} from (1, 11) to (1, 12) : ; \n",
        );
        assert_eq!(rendered, expected);
    }

    #[test]
    fn dump_output_line_range_filters_rows() {
        // A tight `[2, 2]` range hides every node whose start row is 1,
        // exercising `line_in_range` end to end through the walk.
        let code = b"int a = 1;\nint b = 2;\n";
        let parser = CppParser::new(code.to_vec(), &PathBuf::from("t.c"), None);
        let root = parser.root();

        let start: Option<usize> = Some(2);
        let end: Option<usize> = Some(2);
        let mut sink = NoColor::new(Vec::new());
        {
            let mut state = DumpState {
                code,
                line_start: &start,
                line_end: &end,
                stdout: &mut sink,
            };
            dump_tree_helper(&mut state, &root, "", true, -1).expect("dump to in-memory sink");
        }
        let rendered = String::from_utf8(sink.into_inner()).expect("dump output is utf-8");

        // Row-1 nodes (`int a = 1;` and the root, which starts on row 1)
        // are filtered out; only row-2 nodes survive.
        assert!(
            !rendered.contains("(1, "),
            "row-1 nodes should be hidden:\n{rendered}"
        );
        assert!(
            rendered.contains("int b = 2;"),
            "row-2 declaration should show:\n{rendered}"
        );
    }

    #[test]
    fn deeply_nested_ast_dumps_without_stack_overflow() {
        // The dump walk is iterative (#700): a pathologically deep AST —
        // here ~4000 nested parentheses, which tree-sitter builds with an
        // iterative parser — must dump without overflowing the thread
        // stack. The pre-fix recursive `dump_tree_helper` aborted the
        // process here; an abort is uncatchable, so reaching the
        // assertion at all is the regression guard. Run on a small-stack
        // thread so a latent re-introduction of recursion fails loudly
        // rather than relying on the (large) test-runner stack.
        const DEPTH: usize = 4_000;
        let mut src = Vec::with_capacity(DEPTH * 2 + 8);
        src.extend_from_slice(b"int a = ");
        src.extend(std::iter::repeat_n(b'(', DEPTH));
        src.push(b'1');
        src.extend(std::iter::repeat_n(b')', DEPTH));
        src.extend_from_slice(b";\n");

        let handle = std::thread::Builder::new()
            .stack_size(512 * 1024)
            .spawn(move || {
                let parser = CppParser::new(src.clone(), &PathBuf::from("deep.c"), None);
                let root = parser.root();
                let no_start: Option<usize> = None;
                let no_end: Option<usize> = None;
                let mut sink = NoColor::new(Vec::new());
                let mut state = DumpState {
                    code: &src,
                    line_start: &no_start,
                    line_end: &no_end,
                    stdout: &mut sink,
                };
                dump_tree_helper(&mut state, &root, "", true, -1).is_ok()
            })
            .expect("spawn dump thread");
        assert!(
            handle
                .join()
                .expect("dump thread must not overflow the stack"),
            "deep AST must dump successfully"
        );
    }

    #[test]
    fn dump_output_depth_limits_recursion() {
        // `bca find` dumps with depth=1 (src/find.rs) to show only the
        // matched node, not its subtree. depth=1 renders the node and stops
        // before its children; depth=0 renders nothing. This is the only
        // positive-depth path in production, and it is what the `depth - 1`
        // decrement in `dump_tree_helper`'s iterative walk guards — pin it
        // explicitly.
        let code = b"int a = 42;\n";
        let parser = CppParser::new(code.to_vec(), &PathBuf::from("t.c"), None);
        let root = parser.root();
        let no_start: Option<usize> = None;
        let no_end: Option<usize> = None;

        // depth = 1: the root renders, but recursion stops before children.
        let mut sink = NoColor::new(Vec::new());
        {
            let mut state = DumpState {
                code,
                line_start: &no_start,
                line_end: &no_end,
                stdout: &mut sink,
            };
            dump_tree_helper(&mut state, &root, "", true, 1).expect("dump to in-memory sink");
        }
        let rendered = String::from_utf8(sink.into_inner()).expect("dump output is utf-8");
        assert!(
            rendered.contains("{translation_unit:"),
            "depth=1 should render the root:\n{rendered}"
        );
        assert!(
            !rendered.contains("{declaration:"),
            "depth=1 must not recurse into children:\n{rendered}"
        );
        assert_eq!(
            rendered.lines().count(),
            1,
            "depth=1 renders exactly one node:\n{rendered}"
        );

        // depth = 0: nothing renders at all.
        let mut sink_zero = NoColor::new(Vec::new());
        {
            let mut state = DumpState {
                code,
                line_start: &no_start,
                line_end: &no_end,
                stdout: &mut sink_zero,
            };
            dump_tree_helper(&mut state, &root, "", true, 0).expect("dump to in-memory sink");
        }
        assert!(sink_zero.into_inner().is_empty(), "depth=0 renders nothing");
    }
}