Skip to main content

cccc_core/
report.rs

1//! Result types and language-agnostic aggregation (summary statistics and
2//! cross-file rankings). Output *rendering* lives in the CLI, not here.
3
4use serde::Serialize;
5
6/// Complexity metrics for a single function-like unit (function, method, arrow, accessor).
7///
8/// Each unit is measured independently: nesting resets to 0 at the function
9/// boundary and nested functions are reported as `children` rather than being
10/// folded into the parent's own score. See [`crate::engine`] for the exact rules.
11#[derive(Debug, Clone, Serialize)]
12pub struct FunctionReport {
13    pub name: String,
14    /// "function" | "method" | "arrow" | "getter" | "setter" | "constructor"
15    pub kind: String,
16    /// 1-based line where the function starts.
17    pub line: u32,
18    pub cognitive: u32,
19    pub cyclomatic: u32,
20    #[serde(skip_serializing_if = "Vec::is_empty")]
21    pub children: Vec<FunctionReport>,
22}
23
24/// Aggregated metrics for a single source file.
25#[derive(Debug, Clone, Serialize)]
26pub struct FileReport {
27    pub path: String,
28    /// File total = module-level code + every function (all nesting depths).
29    pub cognitive: u32,
30    pub cyclomatic: u32,
31    pub functions: Vec<FunctionReport>,
32    #[serde(skip_serializing_if = "Vec::is_empty")]
33    pub parse_errors: Vec<String>,
34}
35
36/// Distribution of one metric over the population of all functions.
37///
38/// Complexity is right-skewed, so the percentiles (not a mean/stddev) carry the
39/// signal: `median` is the typical function, `p90`/`p95`/`max` describe the tail
40/// where refactoring candidates live.
41#[derive(Debug, Clone, Serialize)]
42pub struct MetricSummary {
43    pub sum: u32,
44    pub max: u32,
45    pub median: u32,
46    pub p90: u32,
47    pub p95: u32,
48}
49
50/// Project-wide rollup across every function in every file.
51#[derive(Debug, Clone, Serialize)]
52pub struct Summary {
53    pub file_count: usize,
54    pub function_count: usize,
55    /// Total parse errors across all files. Parsers are fault-tolerant where
56    /// possible, so a non-zero count means some code was measured from a
57    /// partial parse (or, for non-recovering parsers, skipped entirely).
58    pub parse_error_count: usize,
59    /// Number of files that had at least one parse error.
60    pub parse_error_file_count: usize,
61    /// Paths of the files that had parse errors, in report order. Lets a
62    /// consumer locate the affected files without scanning every entry in
63    /// `files` (which the `--top-*` output doesn't even include).
64    #[serde(skip_serializing_if = "Vec::is_empty")]
65    pub parse_error_files: Vec<String>,
66    pub cognitive: MetricSummary,
67    pub cyclomatic: MetricSummary,
68}
69
70/// Top-level output: per-file reports plus a whole-project summary.
71#[derive(Debug, Clone, Serialize)]
72pub struct Report {
73    pub files: Vec<FileReport>,
74    pub summary: Summary,
75}
76
77/// The complexity metric a ranking is ordered by.
78#[derive(Debug, Clone, Copy)]
79pub enum Metric {
80    Cognitive,
81    Cyclomatic,
82}
83
84impl Metric {
85    fn as_str(self) -> &'static str {
86        match self {
87            Metric::Cognitive => "cognitive",
88            Metric::Cyclomatic => "cyclomatic",
89        }
90    }
91}
92
93/// One function in a flat cross-file ranking. Carries `path`/`line` so each row
94/// is locatable on its own (the per-file nesting is flattened away).
95#[derive(Debug, Clone, Serialize)]
96pub struct TopEntry {
97    pub path: String,
98    pub name: String,
99    pub kind: String,
100    pub line: u32,
101    pub cognitive: u32,
102    pub cyclomatic: u32,
103}
104
105/// Top-level output for `--top-*`: a flat ranking plus the whole-project summary.
106#[derive(Debug, Clone, Serialize)]
107pub struct TopReport {
108    /// The metric the ranking is sorted by ("cognitive" | "cyclomatic").
109    pub metric: String,
110    pub top: Vec<TopEntry>,
111    pub summary: Summary,
112}
113
114/// Visit every function in a report tree (parents before children, all depths).
115pub fn for_each_function(fns: &[FunctionReport], f: &mut impl FnMut(&FunctionReport)) {
116    for func in fns {
117        f(func);
118        for_each_function(&func.children, f);
119    }
120}
121
122/// Build a flat ranking of the `n` most complex functions across all files,
123/// ordered by `metric` descending. Ties break by path then line for stable,
124/// reproducible output. Counts every function at every nesting depth.
125pub fn compute_top(reports: &[FileReport], metric: Metric, n: usize) -> Vec<TopEntry> {
126    let mut entries = Vec::new();
127    for r in reports {
128        for_each_function(&r.functions, &mut |f| {
129            entries.push(TopEntry {
130                path: r.path.clone(),
131                name: f.name.clone(),
132                kind: f.kind.clone(),
133                line: f.line,
134                cognitive: f.cognitive,
135                cyclomatic: f.cyclomatic,
136            });
137        });
138    }
139    entries.sort_by(|a, b| {
140        let (av, bv) = match metric {
141            Metric::Cognitive => (a.cognitive, b.cognitive),
142            Metric::Cyclomatic => (a.cyclomatic, b.cyclomatic),
143        };
144        bv.cmp(&av)
145            .then_with(|| a.path.cmp(&b.path))
146            .then(a.line.cmp(&b.line))
147    });
148    entries.truncate(n);
149    entries
150}
151
152/// Assemble a `TopReport` from the per-file reports and a precomputed summary.
153pub fn build_top_report(
154    reports: &[FileReport],
155    summary: Summary,
156    metric: Metric,
157    n: usize,
158) -> TopReport {
159    TopReport {
160        metric: metric.as_str().to_string(),
161        top: compute_top(reports, metric, n),
162        summary,
163    }
164}
165
166/// Nearest-rank percentile on an ascending-sorted slice. `p` is in `[0, 100]`.
167/// Returns 0 for an empty slice.
168fn percentile(sorted: &[u32], p: f64) -> u32 {
169    if sorted.is_empty() {
170        return 0;
171    }
172    let n = sorted.len();
173    let rank = ((p / 100.0) * n as f64).ceil() as usize;
174    let idx = rank.saturating_sub(1).min(n - 1);
175    sorted[idx]
176}
177
178fn metric_summary(mut values: Vec<u32>) -> MetricSummary {
179    values.sort_unstable();
180    MetricSummary {
181        sum: values.iter().sum(),
182        max: values.last().copied().unwrap_or(0),
183        median: percentile(&values, 50.0),
184        p90: percentile(&values, 90.0),
185        p95: percentile(&values, 95.0),
186    }
187}
188
189/// Build the whole-project summary. The population is every function at every
190/// nesting depth across all files (module-level totals are excluded). Call this
191/// before any display-only filtering so the distribution reflects all code.
192pub fn compute_summary(reports: &[FileReport]) -> Summary {
193    let mut cog = Vec::new();
194    let mut cyc = Vec::new();
195    let mut parse_error_count = 0;
196    let mut parse_error_files = Vec::new();
197    for r in reports {
198        for_each_function(&r.functions, &mut |f| {
199            cog.push(f.cognitive);
200            cyc.push(f.cyclomatic);
201        });
202        if !r.parse_errors.is_empty() {
203            parse_error_count += r.parse_errors.len();
204            parse_error_files.push(r.path.clone());
205        }
206    }
207    Summary {
208        file_count: reports.len(),
209        function_count: cog.len(),
210        parse_error_count,
211        parse_error_file_count: parse_error_files.len(),
212        parse_error_files,
213        cognitive: metric_summary(cog),
214        cyclomatic: metric_summary(cyc),
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn percentile_nearest_rank() {
224        let v: Vec<u32> = (1..=10).collect();
225        assert_eq!(percentile(&v, 50.0), 5);
226        assert_eq!(percentile(&v, 90.0), 9);
227        assert_eq!(percentile(&v, 95.0), 10);
228        assert_eq!(percentile(&v, 100.0), 10);
229    }
230
231    #[test]
232    fn percentile_empty_is_zero() {
233        assert_eq!(percentile(&[], 50.0), 0);
234    }
235
236    #[test]
237    fn summary_aggregates_parse_errors() {
238        let file = |path: &str, errors: Vec<String>| FileReport {
239            path: path.to_string(),
240            cognitive: 0,
241            cyclomatic: 0,
242            functions: Vec::new(),
243            parse_errors: errors,
244        };
245        let reports = vec![
246            file("clean", Vec::new()),
247            file("one", vec!["syntax error at line 1".to_string()]),
248            file(
249                "two",
250                vec![
251                    "syntax error at line 3".to_string(),
252                    "syntax error at line 9".to_string(),
253                ],
254            ),
255        ];
256        let s = compute_summary(&reports);
257        assert_eq!(s.parse_error_count, 3);
258        assert_eq!(s.parse_error_file_count, 2);
259        assert_eq!(s.parse_error_files, vec!["one", "two"]);
260    }
261
262    #[test]
263    fn summary_without_parse_errors_is_zero() {
264        let s = compute_summary(&[]);
265        assert_eq!(s.parse_error_count, 0);
266        assert_eq!(s.parse_error_file_count, 0);
267        assert!(s.parse_error_files.is_empty());
268    }
269}