-
Notifications
You must be signed in to change notification settings - Fork 278
#432 cognitive complexity #440
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Ollec
wants to merge
9
commits into
terryyin:master
Choose a base branch
from
Ollec:#432_Cognitive_Complexity
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
… for multiple languages with tests for each - Implemented cognitive complexity tests for Python, R, Ruby, Rust, Scala, Solidity, Structured Text, Swift, TTCN-3, TypeScript, Vue.js, Zig and more. - Each language includes tests for simple functions, single if statements, nested loops, binary logical operators, and other control structures. - Updated error messages in option parsing to include cognitive complexity as a valid sorting factor.
- Implemented a new extension for calculating Cognitive Complexity in functions, following the specification by SonarSource. - Updated output formats to include Cognitive Complexity in headers and outputs for different formats (CSV, HTML). - Adjusted error messages for sorting factors to reflect the new order of fields, ensuring clarity in available options.
…uages, and made it no longer default - Removed cognitive complexity tests from Python, R, Ruby, Rust, Scala, Solidity, Structured Text, Swift, TTCN-3, TypeScript, Vue.js, and Zig test files. - Updated test cases to ensure they accurately reflect the cognitive complexity calculations for various control structures. - Adjusted the expected cognitive complexity values based on the latest implementation details. - Modified the test options to reflect changes in the default and extension fields for cognitive complexity.
Contributor
Author
|
@terryyin are there any changes you would like to me to make, or scrap the whole PR? |
Owner
|
@Ollec sorry, I keep postponing this because too many things are changed. I will review as soon as I can. |
Contributor
Author
|
@terryyin No worries, I understand. It ended up being a lot more of an undertaking than I had been planning. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This took a lot more than I was expecting. I really like the extension model that Lizard has.
When testing on actual projects, I encountered issues with both Python and PL/SQL, so I am confident we will find other kinks in other languages.
Add Cognitive Complexity (CogC) Metric Support
Overview
This PR implements Cognitive Complexity as a built-in complexity metric alongside Cyclomatic Complexity (CCN) in Lizard. Cognitive Complexity is a metric designed to measure how difficult code is to understand, addressing several limitations of Cyclomatic Complexity by focusing on human intuition about code readability rather than pure mathematical path counting.
Implementation follows the Cognitive Complexity specification v1.2 by SonarSource (April 2017).
What is Cognitive Complexity?
Unlike Cyclomatic Complexity which counts all decision points equally, Cognitive Complexity:
&&or||count as +1, not per operator?.,??) don't add complexityResult: Cognitive Complexity scores better correlate with perceived code difficulty and maintainability.
Implementation Architecture
Extension-Based Design
Cognitive Complexity is implemented as a Lizard extension (
lizard_ext/lizardcogc.py) that:FileInfoBuilderandFunctionInfoto add CogC tracking methodscurrent_nesting_level) for C-like languagescogc_nesting_level) for all languages, especially Python/RubyKey Features Implemented
Four Types of Increments (per specification):
if,for,while,foreach,repeat) - Add +1 + nesting levelelse,elif,elseif) - Add +1 without nesting penalty, but increase nesting for childrengoto, labeled jumps) - Add +1 regardless of nesting#if,#ifdef,#elif) - Treated as structural incrementsSpecial Handling:
cogc_excluded_nestingcounter)ifstatements?.,??)docounted, not trailingwhilecogc_last_operatornormalizationLanguage-Specific Adaptations:
has_top_level_increment)WHENclausespending_structural_nestingflag withadd_bare_nesting()hookLanguage Support
26 languages with Cognitive Complexity support:⚠️ Partial (2/4 parser-limited tests pass)⚠️ Partial (tests skipped)
All Languages however
Erlang
Structured Text
Total:
190 language-specific CogC tests30+ core/spec tests+
= ~220 tests
Files Changed
New Files
lizard_ext/lizardcogc.py- Core CogC extension implementationcognitive_complexity_theory.rst- Comprehensive documentationtest/test_extensions/test_cognitive_complexity.py- Core functionality teststest/test_extensions/test_cognitive_complexity_cli.py- CLI integration testsModified Files
lizard.py- CLI argument for-G/--CogCthreshold (default: 15)lizard_ext/htmloutput.py- Added CogC column to HTML outputREADME.rst- Updated supported languages list, added CogC usage examplesCHANGELOG.md- Documented new featureclike.py,erlang.py,plsql.py,python.py,st.py,typescript.py,zig.pyCLI Usage
Command-Line Options
Output Formats
CogC can appears in all output formats:
<cognitive_complexity>elementcognitive_complexityfieldExample Output
Implementation Details
Token Processing Pipeline
State Variables Tracked
In
FileInfoBuilder:cogc_nesting_level- Control-flow nesting depthcogc_last_operator- Last binary operator (normalized)cogc_nesting_stack- Boolean stack for structural nestingcogc_excluded_nesting- Try block nesting to excludepending_lambda_nesting- Lambda entry flaglambda_depth- Nested lambda trackingpending_structural_nesting- Brace-less language flagIn
FunctionInfo:cognitive_complexity- Running CogC totalinitial_nesting_level- Bracket nesting at function startinitial_cogc_nesting_level- Control-flow nesting at start (preprocessor directives)Nesting Calculation Formula
Documentation
Added Documentation Files
cognitive_complexity_theory.rst- covering:Updated
README.rst:Updated
CHANGELOG.md:Testing Strategy
Test Categories
Core functionality tests (
test_cognitive_complexity.py)CLI integration tests (
test_cognitive_complexity_cli.py)Language-specific tests (26 test files)
Test Coverage Standards
All tests follow strict assertions:
assertEqual(expected, actual.cognitive_complexity)assertGreaterEqual,assertLess, etc.// +1,// +2 (nesting=1)Breaking Changes
None. This is a purely additive feature:
-G/--CogC(doesn't conflict with existing options)Performance Impact
Minimal. The extension:
Future Work
Not implemented (per specification, but low priority):
;in if/case)Specification Attribution
Source Specification
This implementation is based on the Cognitive Complexity specification version 1.2 by G. Ann Campbell, SonarSource SA (April 19, 2017).
Specification Details:
Attribution Locations
Proper attribution to SonarSource and the specification is provided in:
lizard_ext/lizardcogc.py- Core implementation filecognitive_complexity_theory.rst- DocumentationREADME.rst- User-facing documentationTest Examples Inspired by Specification
Test cases inspired by the specification have been transformed to avoid copyright concerns while maintaining specification compliance validation:
Related Issues
Closes #432