Expand description
Cognitive complexity (SonarQube S3776-style) via tree-sitter.
Cyclomatic complexity counts independent paths (good for “how many tests”); cognitive complexity models how hard code is to follow by adding a nesting penalty, so deeply nested control flow scores higher than flat code with the same number of branches. That nesting is the signal the Sonar study links to agent token cost: a deeply nested function cannot be navigated by name, so the agent reads all of it.
§Increment rules
- +1 plus the current nesting depth for each control-flow construct that
nests:
if, loops,switch/match,catch/except, ternary,try. Each such construct also raises the nesting level for its body. - +1 (flat) for each sequence of binary boolean operators
(
&&/||/and/or) — consecutive identical operators count once. - +1 (flat) for flow-breaking jumps that carry a label (
break/continuewith a label) and forgoto. else/else ifdo not add a nesting level (handled via thealternativefield), so else-if chains stay roughly linear.
Nested function bodies are scored independently (mirrors
crate::core::cyclomatic). The traversal uses the heap-stack walk pattern
to stay safe on pathologically deep trees (#378).
Structs§
- Function
Cognitive - Cognitive complexity of a single function-like definition.
Functions§
- cognitive_
per_ function - Compute cognitive complexity per function for
sourceof the given fileextension. ReturnsNonewhen tree-sitter is disabled, the extension is unsupported, or the file has no functions.