big_code_analysis/count.rs
1// Metric counts (token, function, branch, argument, etc.) are stored as
2// `usize` and crossed with `f64` averages, ratios, and Halstead scores
3// across the cyclomatic / MI / Halstead computations. The `usize as f64`
4// and `f64 as usize` casts are intentional and snapshot-anchored — every
5// site is bounded by the count it came from. Allowing the lints at the
6// module level keeps the metric arithmetic legible.
7#![allow(
8 clippy::cast_precision_loss,
9 clippy::cast_possible_truncation,
10 clippy::cast_sign_loss
11)]
12// Per-language metric and AST modules deliberately consume the macro-
13// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
14// inside match expressions — explicit imports would list dozens of
15// variants per arm and obscure the per-language token sets that are the
16// point of these files. Allowed at the module level rather than per
17// function so the per-language impl blocks stay readable.
18#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
19
20extern crate num_format;
21
22use num_format::{Locale, ToFormattedString};
23use std::fmt;
24use std::sync::{Arc, Mutex};
25
26use crate::traits::*;
27
28// Hidden from rustdoc because the signature exposes `ParserTrait`,
29// which is `#[doc(hidden)]` per issue #256. The CLI's `Count` callback
30// remains the documented surface for this functionality.
31#[doc(hidden)]
32/// Counts the types of nodes specified in the input slice
33/// and the number of nodes in a code.
34pub fn count<T: ParserTrait>(parser: &T, filters: &[String]) -> (usize, usize) {
35 let filters = parser.get_filters(filters);
36 let node = parser.get_root();
37 let mut cursor = node.cursor();
38 let mut stack = Vec::new();
39 let mut good = 0;
40 let mut total = 0;
41
42 stack.push(node);
43
44 while let Some(node) = stack.pop() {
45 total += 1;
46 if filters.any(&node) {
47 good += 1;
48 }
49 cursor.reset(&node);
50 if cursor.goto_first_child() {
51 loop {
52 stack.push(cursor.node());
53 if !cursor.goto_next_sibling() {
54 break;
55 }
56 }
57 }
58 }
59 (good, total)
60}
61
62/// Configuration options for counting different
63/// types of nodes in a code.
64#[derive(Debug)]
65pub struct CountCfg {
66 /// Types of nodes to count
67 pub filters: Arc<[String]>,
68 /// Number of nodes of a certain type counted by each thread
69 pub stats: Arc<Mutex<Count>>,
70}
71
72/// Count of different types of nodes in a code.
73#[derive(Debug, Default)]
74pub struct Count {
75 /// The number of specific types of nodes searched in a code
76 pub good: usize,
77 /// The total number of nodes in a code
78 pub total: usize,
79}
80
81impl Callback for Count {
82 type Res = std::io::Result<()>;
83 type Cfg = CountCfg;
84
85 fn call<T: ParserTrait>(cfg: Self::Cfg, parser: &T) -> Self::Res {
86 let (good, total) = count(parser, &cfg.filters);
87 let mut results = cfg.stats.lock().unwrap();
88 results.good += good;
89 results.total += total;
90 Ok(())
91 }
92}
93
94impl fmt::Display for Count {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 writeln!(
97 f,
98 "Total nodes: {}",
99 self.total.to_formatted_string(&Locale::en)
100 )?;
101 writeln!(
102 f,
103 "Found nodes: {}",
104 self.good.to_formatted_string(&Locale::en)
105 )?;
106 write!(
107 f,
108 "Percentage: {:.2}%",
109 (self.good as f64) / (self.total as f64) * 100.
110 )
111 }
112}