Skip to main content

cccc_core/
engine.rs

1//! The scoring engine: walks the normalized [`crate::ir`] and computes Cognitive
2//! Complexity (SonarSource / G. Ann Campbell) and Cyclomatic Complexity (McCabe).
3//!
4//! ## Measurement model
5//!
6//! Every [`Node::Function`] is measured **independently**: its nesting level
7//! starts at 0 at its own boundary, and a structural increment is attributed
8//! only to the nearest enclosing function. Nested functions therefore do *not*
9//! inflate the enclosing function's own score; they are reported as `children`.
10//! A file's total is module-level code plus every function at every depth (each
11//! structural increment counted exactly once).
12//!
13//! ## Cyclomatic Complexity (McCabe)
14//!
15//! Base 1 per function; +1 for each branch (`if`/`else if`), ternary, loop,
16//! non-default `case`, `catch`, explicit null guard, and each logical
17//! operator (one per extra operand in a [`Node::Logical`]).
18//!
19//! ## Cognitive Complexity (SonarSource)
20//!
21//! - +1 and +nesting bonus for: branch, ternary, switch, loop, catch.
22//! - +1 flat (no bonus) for: `else` / `else if`, labelled jumps, each logical
23//!   sequence, and recursion (a call to the nearest enclosing function's name).
24//! - Nesting increases inside branch/ternary/switch/loop/catch bodies and nested
25//!   function bodies.
26
27use crate::ir::Node;
28use crate::report::{FileReport, FunctionReport};
29
30/// An in-progress accumulator for one function-like unit (or the module root).
31///
32/// `kind` is an opaque, adapter-chosen label; the engine only ever compares it
33/// against the sentinel `"module"` (the implicit root frame) when deciding
34/// whether a call counts as recursion.
35struct Frame {
36    name: String,
37    kind: String,
38    line: u32,
39    cognitive: u32,
40    cyclomatic: u32,
41    nesting: u32,
42    children: Vec<FunctionReport>,
43}
44
45struct Engine {
46    /// `stack[0]` is always the module frame; deeper entries are functions.
47    stack: Vec<Frame>,
48}
49
50impl Engine {
51    fn new() -> Self {
52        let module = Frame {
53            name: "<module>".to_string(),
54            kind: "module".to_string(),
55            line: 1,
56            cognitive: 0,
57            cyclomatic: 0,
58            nesting: 0,
59            children: Vec::new(),
60        };
61        Self {
62            stack: vec![module],
63        }
64    }
65
66    fn top(&mut self) -> &mut Frame {
67        self.stack.last_mut().expect("stack never empty")
68    }
69
70    fn top_nesting(&self) -> u32 {
71        self.stack.last().expect("stack never empty").nesting
72    }
73
74    fn add_cognitive(&mut self, amount: u32) {
75        self.top().cognitive += amount;
76    }
77
78    fn add_cyclomatic(&mut self) {
79        self.top().cyclomatic += 1;
80    }
81
82    fn enter_nesting(&mut self) {
83        self.top().nesting += 1;
84    }
85
86    fn leave_nesting(&mut self) {
87        self.top().nesting -= 1;
88    }
89
90    /// Walk a slice of sibling nodes at the current nesting/frame.
91    fn walk(&mut self, nodes: &[Node]) {
92        for node in nodes {
93            self.visit(node);
94        }
95    }
96
97    /// The structural increment shared by loops, switch, and catch: +1 plus the
98    /// nesting bonus to cognitive, optionally a cyclomatic point, then the body
99    /// with nesting raised by one. (`switch` passes `add_cyclomatic = false` —
100    /// the switch itself is not a McCabe decision point; its cases are.)
101    fn nested(&mut self, add_cyclomatic: bool, body: &[Node]) {
102        let n = self.top_nesting();
103        self.add_cognitive(1 + n);
104        if add_cyclomatic {
105            self.add_cyclomatic();
106        }
107        self.enter_nesting();
108        self.walk(body);
109        self.leave_nesting();
110    }
111
112    fn visit(&mut self, node: &Node) {
113        match node {
114            Node::Function {
115                name,
116                kind,
117                line,
118                body,
119            } => self.visit_function(name, kind, *line, body),
120            Node::Branch {
121                test,
122                then,
123                alternate,
124            } => self.visit_branch(test, then, alternate),
125            Node::Conditional {
126                test,
127                then,
128                alternate,
129            } => {
130                let n = self.top_nesting();
131                self.add_cognitive(1 + n);
132                self.add_cyclomatic();
133                self.walk(test);
134                self.enter_nesting();
135                self.walk(then);
136                self.walk(alternate);
137                self.leave_nesting();
138            }
139            Node::Loop { body } => self.nested(true, body),
140            Node::Catch { body } => self.nested(true, body),
141            Node::Switch { cases } => {
142                let n = self.top_nesting();
143                self.add_cognitive(1 + n);
144                self.enter_nesting();
145                for case in cases {
146                    if !case.is_default {
147                        self.add_cyclomatic(); // a non-default `case` is a decision point
148                    }
149                    self.walk(&case.body);
150                }
151                self.leave_nesting();
152            }
153            Node::Jump { labeled } => {
154                if *labeled {
155                    self.add_cognitive(1);
156                }
157            }
158            Node::Logical { operands, .. } => self.visit_logical(operands),
159            Node::NullGuard { body } => {
160                self.add_cyclomatic();
161                self.walk(body);
162            }
163            Node::Call { callee } => self.visit_call(callee.as_deref()),
164            Node::Group(children) => self.walk(children),
165        }
166    }
167
168    fn visit_function(&mut self, name: &str, kind: &str, line: u32, body: &[Node]) {
169        self.stack.push(Frame {
170            name: name.to_string(),
171            kind: kind.to_string(),
172            line,
173            cognitive: 0,
174            cyclomatic: 1, // McCabe base
175            nesting: 0,
176            children: Vec::new(),
177        });
178        self.walk(body);
179        let frame = self.stack.pop().expect("function frame");
180        let report = FunctionReport {
181            name: frame.name,
182            kind: frame.kind,
183            line: frame.line,
184            cognitive: frame.cognitive,
185            cyclomatic: frame.cyclomatic,
186            children: frame.children,
187        };
188        self.top().children.push(report);
189    }
190
191    /// `if` consequent gets a nesting bonus; the alternate (`else` / `else if`)
192    /// is scored flat — one cognitive point, no bonus.
193    fn visit_branch(&mut self, test: &[Node], then: &[Node], alternate: &Option<Box<Node>>) {
194        let n = self.top_nesting();
195        self.add_cognitive(1 + n);
196        self.add_cyclomatic();
197        self.walk(test);
198        self.enter_nesting();
199        self.walk(then);
200        self.leave_nesting();
201        self.visit_alternate(alternate);
202    }
203
204    fn visit_alternate(&mut self, alternate: &Option<Box<Node>>) {
205        let Some(node) = alternate else { return };
206        match node.as_ref() {
207            // `else if`: its own decision (cyclomatic +1), flat cognitive +1.
208            Node::Branch {
209                test,
210                then,
211                alternate,
212            } => {
213                self.add_cognitive(1);
214                self.add_cyclomatic();
215                self.walk(test);
216                self.enter_nesting();
217                self.walk(then);
218                self.leave_nesting();
219                self.visit_alternate(alternate);
220            }
221            // plain `else`: flat cognitive +1, body nested.
222            other => {
223                self.add_cognitive(1);
224                self.enter_nesting();
225                self.visit(other);
226                self.leave_nesting();
227            }
228        }
229    }
230
231    /// One cognitive point for the sequence; one cyclomatic point per operator
232    /// (i.e. per extra operand). Operands are walked for nested constructs.
233    fn visit_logical(&mut self, operands: &[Node]) {
234        self.add_cognitive(1);
235        for _ in 1..operands.len() {
236            self.add_cyclomatic();
237        }
238        self.walk(operands);
239    }
240
241    fn visit_call(&mut self, callee: Option<&str>) {
242        if let Some(name) = callee
243            && let Some(top) = self.stack.last()
244            && top.kind != "module"
245            && top.name == name
246        {
247            self.add_cognitive(1); // recursion
248        }
249    }
250}
251
252/// Sum every function (all depths) into the running totals.
253fn sum_tree(fns: &[FunctionReport], cog: &mut u32, cyc: &mut u32) {
254    for f in fns {
255        *cog += f.cognitive;
256        *cyc += f.cyclomatic;
257        sum_tree(&f.children, cog, cyc);
258    }
259}
260
261/// Score a module's worth of IR (`nodes` is module-level code) into a
262/// [`FileReport`] labelled `path`. `parse_errors` is carried through verbatim
263/// for the adapter's convenience.
264pub fn analyze(path: &str, nodes: &[Node], parse_errors: Vec<String>) -> FileReport {
265    let mut engine = Engine::new();
266    engine.walk(nodes);
267    let module = engine.stack.pop().expect("module frame");
268
269    let functions = module.children;
270    let mut cognitive = module.cognitive;
271    let mut cyclomatic = module.cyclomatic;
272    sum_tree(&functions, &mut cognitive, &mut cyclomatic);
273
274    FileReport {
275        path: path.to_string(),
276        cognitive,
277        cyclomatic,
278        functions,
279        parse_errors,
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use crate::ir::{LogicalOp, Node, SwitchCase};
287
288    fn func(name: &str, kind: &str, body: Vec<Node>) -> Node {
289        Node::Function {
290            name: name.into(),
291            kind: kind.into(),
292            line: 1,
293            body,
294        }
295    }
296    fn find<'a>(fns: &'a [FunctionReport], name: &str) -> Option<&'a FunctionReport> {
297        for f in fns {
298            if f.name == name {
299                return Some(f);
300            }
301            if let Some(found) = find(&f.children, name) {
302                return Some(found);
303            }
304        }
305        None
306    }
307    fn cog(report: &FileReport, name: &str) -> u32 {
308        find(&report.functions, name).expect("function").cognitive
309    }
310    fn cyc(report: &FileReport, name: &str) -> u32 {
311        find(&report.functions, name).expect("function").cyclomatic
312    }
313
314    // sumOfPrimes: OUT: for { for { if { continue OUT } } } -> cognitive 7.
315    #[test]
316    fn sonar_sum_of_primes_is_7() {
317        let inner_if = Node::Branch {
318            test: vec![],
319            then: vec![Node::Jump { labeled: true }],
320            alternate: None,
321        };
322        let inner_for = Node::Loop {
323            body: vec![inner_if],
324        };
325        let outer_for = Node::Loop {
326            body: vec![inner_for],
327        };
328        let f = func("sumOfPrimes", "function", vec![outer_for]);
329        let r = analyze("t", &[f], vec![]);
330        // for(+1) + nested for(+2) + nested if(+3) + continue OUT(+1) = 7
331        assert_eq!(cog(&r, "sumOfPrimes"), 7);
332    }
333
334    #[test]
335    fn sonar_get_words_is_1() {
336        let sw = Node::Switch {
337            cases: vec![
338                SwitchCase {
339                    is_default: false,
340                    body: vec![],
341                },
342                SwitchCase {
343                    is_default: false,
344                    body: vec![],
345                },
346                SwitchCase {
347                    is_default: true,
348                    body: vec![],
349                },
350            ],
351        };
352        let r = analyze("t", &[func("getWords", "function", vec![sw])], vec![]);
353        assert_eq!(cog(&r, "getWords"), 1);
354        // base 1 + 2 non-default cases = 3
355        assert_eq!(cyc(&r, "getWords"), 3);
356    }
357
358    #[test]
359    fn nested_if_adds_nesting() {
360        let deep = Node::Branch {
361            test: vec![],
362            then: vec![Node::Branch {
363                test: vec![],
364                then: vec![Node::Branch {
365                    test: vec![],
366                    then: vec![],
367                    alternate: None,
368                }],
369                alternate: None,
370            }],
371            alternate: None,
372        };
373        let r = analyze("t", &[func("f", "function", vec![deep])], vec![]);
374        assert_eq!(cog(&r, "f"), 6); // +1 +2 +3
375    }
376
377    #[test]
378    fn else_if_else_are_flat() {
379        // if {} else if {} else {}
380        let chain = Node::Branch {
381            test: vec![],
382            then: vec![],
383            alternate: Some(Box::new(Node::Branch {
384                test: vec![],
385                then: vec![],
386                alternate: Some(Box::new(Node::Group(vec![]))),
387            })),
388        };
389        let r = analyze("t", &[func("f", "function", vec![chain])], vec![]);
390        assert_eq!(cog(&r, "f"), 3); // if +1, else-if +1, else +1
391    }
392
393    #[test]
394    fn logical_sequences() {
395        // if (a && b && c || d): if(+1) + && seq(+1) + || seq(+1) = 3
396        let inner_and = Node::Logical {
397            op: LogicalOp::And,
398            operands: vec![
399                Node::Group(vec![]),
400                Node::Group(vec![]),
401                Node::Group(vec![]),
402            ],
403        };
404        let outer_or = Node::Logical {
405            op: LogicalOp::Or,
406            operands: vec![inner_and, Node::Group(vec![])],
407        };
408        let branch = Node::Branch {
409            test: vec![outer_or],
410            then: vec![],
411            alternate: None,
412        };
413        let r = analyze("t", &[func("f", "function", vec![branch])], vec![]);
414        assert_eq!(cog(&r, "f"), 3);
415        // cyc: base1 + if1 + (&& has 3 operands => +2) + (|| has 2 => +1) = 5
416        assert_eq!(cyc(&r, "f"), 5);
417    }
418
419    #[test]
420    fn null_guard_adds_only_a_cyclomatic_path() {
421        let null_guard = Node::NullGuard {
422            body: vec![Node::Call { callee: None }],
423        };
424        let r = analyze("t", &[func("f", "function", vec![null_guard])], vec![]);
425        assert_eq!(cog(&r, "f"), 0);
426        assert_eq!(cyc(&r, "f"), 2); // base 1 + optional path 1
427    }
428
429    #[test]
430    fn recursion_adds_one() {
431        // fib: if(+1) + call fib (+1 recursion)
432        let body = vec![
433            Node::Branch {
434                test: vec![],
435                then: vec![],
436                alternate: None,
437            },
438            Node::Call {
439                callee: Some("fib".into()),
440            },
441        ];
442        let r = analyze("t", &[func("fib", "function", body)], vec![]);
443        assert_eq!(cog(&r, "fib"), 2);
444    }
445
446    #[test]
447    fn nested_function_is_independent_unit() {
448        let inner = func(
449            "inner",
450            "function",
451            vec![Node::Branch {
452                test: vec![],
453                then: vec![],
454                alternate: None,
455            }],
456        );
457        let outer = func("outer", "function", vec![inner]);
458        let r = analyze("t", &[outer], vec![]);
459        assert_eq!(cog(&r, "outer"), 0); // child excluded from parent's own score
460        assert_eq!(cog(&r, "inner"), 1);
461    }
462
463    #[test]
464    fn file_total_sums_all_functions() {
465        let a = func(
466            "a",
467            "function",
468            vec![Node::Branch {
469                test: vec![],
470                then: vec![],
471                alternate: None,
472            }],
473        );
474        let b = func(
475            "b",
476            "function",
477            vec![Node::Branch {
478                test: vec![],
479                then: vec![],
480                alternate: None,
481            }],
482        );
483        let r = analyze("t", &[a, b], vec![]);
484        assert_eq!(r.cognitive, 2);
485    }
486}