Skip to content

Add cognitive-complexity rule (Sonar-style) #262

Description

@cursor

Summary

Add a cognitive-complexity rule (SonarSource-style) as a distinct metric from the existing cyclomatic complex-control-flow, since cognitive complexity better matches human-perceived difficulty by penalizing nesting and breaks in linear flow.

Motivation

complex-control-flow counts branches and nesting depth (cyclomatic-flavored). Cognitive complexity weights deeply nested structures more heavily and ignores some constructs (e.g. a flat switch) that inflate cyclomatic counts without hurting readability. Offering both gives teams a readability-focused signal alongside the structural one.

Proposed behavior

  • cognitive-complexity: compute the SonarSource cognitive complexity score per function (increment for control-flow structures, additional increment per level of nesting, increments for boolean operator sequences, etc.).
  • Default threshold cognitiveComplexity.max (e.g. 15); confidence scales with how far over threshold.
  • Clearly documented as complementary to, not a replacement for, complex-control-flow.

Implementation surface

  • New src/detectors/cognitiveComplexity.ts using src/utils/ast.ts; share traversal helpers with complexControlFlow.ts where possible.
  • Register in src/detectors/index.ts; include in core pack.
  • Optionally extend to Python/Kotlin later (they already have complexity detectors).
  • Docs in docs/rules.md explaining the scoring model and the difference from cyclomatic.

Acceptance criteria

  • Cognitive complexity scored per the documented model with nesting penalties.
  • Threshold configurable; confidence scales with overage.
  • Docs clearly distinguish it from complex-control-flow.
  • npm run test:all passes.

Difficulty: medium.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions