-
Notifications
You must be signed in to change notification settings - Fork 104
SONARPY-186 Rule: Cognitive Complexity of functions should not be too high #74
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a6448e5
SONARPY-186 Rule: Cognitive Complexity of functions should not be too…
vilchik-elena a09be65
Remove FunctionComplexity rule from default profile
vilchik-elena 25eda06
Update licenses
vilchik-elena 788727a
SONARPY-186 Fix wrong behaviour
vilchik-elena ba73094
Add unit test for 'except' with multiple exceptions
vilchik-elena 68cace8
Add unit test with not complex function
vilchik-elena File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
1,258 changes: 1,258 additions & 0 deletions
1,258
its/ruling/src/test/resources/expected/python-S3776.json
Large diffs are not rendered by default.
Oops, something went wrong.
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
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
184 changes: 184 additions & 0 deletions
184
python-checks/src/main/java/org/sonar/python/checks/CognitiveComplexityFunctionCheck.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| /* | ||
| * SonarQube Python Plugin | ||
| * Copyright (C) 2011-2017 SonarSource SA | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the GNU Lesser General Public | ||
| * License as published by the Free Software Foundation; either | ||
| * version 3 of the License, or (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
| * Lesser General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Lesser General Public License | ||
| * along with this program; if not, write to the Free Software Foundation, | ||
| * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
| */ | ||
| package org.sonar.python.checks; | ||
|
|
||
| import com.sonar.sslr.api.AstNode; | ||
| import java.util.HashSet; | ||
| import java.util.Set; | ||
| import org.sonar.check.Priority; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.check.RuleProperty; | ||
| import org.sonar.python.PythonCheck; | ||
| import org.sonar.python.api.PythonGrammar; | ||
| import org.sonar.python.api.PythonKeyword; | ||
| import org.sonar.python.api.PythonPunctuator; | ||
| import org.sonar.squidbridge.annotations.ActivatedByDefault; | ||
| import org.sonar.squidbridge.annotations.SqaleLinearWithOffsetRemediation; | ||
|
|
||
| @Rule( | ||
| key = CognitiveComplexityFunctionCheck.CHECK_KEY, | ||
| name = "Cognitive Complexity of functions should not be too high", | ||
| priority = Priority.CRITICAL, | ||
| tags = Tags.BRAIN_OVERLOAD | ||
| ) | ||
| @ActivatedByDefault | ||
| @SqaleLinearWithOffsetRemediation( | ||
| coeff = "1min", | ||
| offset = "5min", | ||
| effortToFixDescription = "per complexity point above the threshold") | ||
| public class CognitiveComplexityFunctionCheck extends PythonCheck { | ||
|
|
||
| private static final String MESSAGE = "Refactor this method to reduce its Cognitive Complexity from %s to the %s allowed."; | ||
| public static final String CHECK_KEY = "S3776"; | ||
| private static final int DEFAULT_THRESHOLD = 15; | ||
|
|
||
| private AstNode currentFunction = null; | ||
| private int complexity; | ||
| private int nestingLevel; | ||
| private Set<IssueLocation> secondaryLocations = new HashSet<>(); | ||
|
|
||
| @RuleProperty( | ||
| key = "threshold", | ||
| description = "The maximum authorized complexity.", | ||
| defaultValue = "" + DEFAULT_THRESHOLD) | ||
| private int threshold = DEFAULT_THRESHOLD; | ||
|
|
||
| public void setThreshold(int threshold) { | ||
| this.threshold = threshold; | ||
| } | ||
|
|
||
| @Override | ||
| public void init() { | ||
| subscribeTo( | ||
| PythonGrammar.IF_STMT, | ||
| PythonKeyword.ELIF, | ||
| PythonKeyword.ELSE, | ||
|
|
||
| PythonGrammar.WHILE_STMT, | ||
| PythonGrammar.FOR_STMT, | ||
| PythonGrammar.EXCEPT_CLAUSE, | ||
|
|
||
| PythonGrammar.AND_TEST, | ||
| PythonGrammar.OR_TEST, | ||
|
|
||
| PythonGrammar.TEST, | ||
|
|
||
| PythonGrammar.FUNCDEF, | ||
| PythonGrammar.SUITE); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(AstNode astNode) { | ||
| if (astNode.is(PythonGrammar.FUNCDEF) && currentFunction == null) { | ||
| currentFunction = astNode; | ||
| complexity = 0; | ||
| nestingLevel = 0; | ||
| secondaryLocations.clear(); | ||
| } | ||
|
|
||
| if (currentFunction != null) { | ||
| if (astNode.is(PythonGrammar.SUITE) && incrementsNestingLevel(astNode)) { | ||
| nestingLevel++; | ||
| } | ||
|
|
||
| checkComplexity(astNode); | ||
| } | ||
| } | ||
|
|
||
| private void checkComplexity(AstNode astNode) { | ||
| if (astNode.is(PythonGrammar.IF_STMT, PythonGrammar.WHILE_STMT, PythonGrammar.FOR_STMT, PythonGrammar.EXCEPT_CLAUSE)) { | ||
| incrementWithNesting(astNode.getFirstChild()); | ||
| } | ||
|
|
||
| if (astNode.is(PythonKeyword.ELIF) || (astNode.is(PythonKeyword.ELSE) && astNode.getNextSibling().is(PythonPunctuator.COLON))) { | ||
| incrementWithoutNesting(astNode); | ||
| } | ||
|
|
||
| if (astNode.is(PythonGrammar.AND_TEST, PythonGrammar.OR_TEST)) { | ||
| incrementWithoutNesting(astNode.getFirstChild(PythonKeyword.AND, PythonKeyword.OR)); | ||
| } | ||
|
|
||
| // conditional expression | ||
| if (astNode.is(PythonGrammar.TEST) && astNode.hasDirectChildren(PythonKeyword.IF)) { | ||
| incrementWithNesting(astNode.getFirstChild(PythonKeyword.IF)); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void leaveNode(AstNode astNode) { | ||
| if (currentFunction == null) { | ||
| return; | ||
| } | ||
|
|
||
| if (currentFunction.equals(astNode)) { | ||
| if (complexity > threshold){ | ||
| raiseIssue(); | ||
| } | ||
| currentFunction = null; | ||
| } | ||
|
|
||
| if (astNode.is(PythonGrammar.SUITE) && incrementsNestingLevel(astNode)) { | ||
| nestingLevel--; | ||
| } | ||
| } | ||
|
|
||
| private void raiseIssue() { | ||
| String message = String.format(MESSAGE, complexity, threshold); | ||
| PreciseIssue issue = addIssue(currentFunction.getFirstChild(PythonGrammar.FUNCNAME), message) | ||
| .withCost(complexity - threshold); | ||
| secondaryLocations.forEach(issue::secondary); | ||
| } | ||
|
|
||
| private boolean incrementsNestingLevel(AstNode astNode) { | ||
| AstNode previousSibling = astNode.getPreviousSibling().getPreviousSibling(); | ||
| if (previousSibling.is(PythonKeyword.TRY, PythonKeyword.FINALLY)) { | ||
| return false; | ||
| } | ||
|
|
||
| AstNode parent = astNode.getParent(); | ||
|
|
||
| return !parent.is(PythonGrammar.WITH_STMT, PythonGrammar.CLASSDEF) | ||
| && (!parent.is(PythonGrammar.FUNCDEF) || !parent.equals(currentFunction)); | ||
| } | ||
|
|
||
| private void incrementWithNesting(AstNode secondaryLocationNode) { | ||
| int currentNodeComplexity = nestingLevel + 1; | ||
| incrementComplexity(secondaryLocationNode, currentNodeComplexity); | ||
| } | ||
|
|
||
| private void incrementWithoutNesting(AstNode secondaryLocationNode) { | ||
| incrementComplexity(secondaryLocationNode, 1); | ||
| } | ||
|
|
||
| private void incrementComplexity(AstNode secondaryLocationNode, int currentNodeComplexity) { | ||
| secondaryLocations.add(new IssueLocation(secondaryLocationNode, secondaryMessage(currentNodeComplexity))); | ||
| complexity += currentNodeComplexity; | ||
| } | ||
|
|
||
| private static String secondaryMessage(int complexity) { | ||
| if (complexity == 1) { | ||
| return "+1"; | ||
|
|
||
| } else{ | ||
| return String.format("+%s (incl %s for nesting)", complexity, complexity - 1); | ||
| } | ||
| } | ||
|
|
||
| } | ||
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
7 changes: 7 additions & 0 deletions
7
python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3776.html
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| <p>Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be | ||
| difficult to maintain.</p> | ||
| <h2>See</h2> | ||
| <ul> | ||
| <li> <a href="http://redirect.sonarsource.com/doc/cognitive-complexity.html">Cognitive Complexity</a> </li> | ||
| </ul> | ||
|
|
39 changes: 39 additions & 0 deletions
39
...on-checks/src/test/java/org/sonar/python/checks/CognitiveComplexityFunctionCheckTest.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| /* | ||
| * SonarQube Python Plugin | ||
| * Copyright (C) 2011-2017 SonarSource SA | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the GNU Lesser General Public | ||
| * License as published by the Free Software Foundation; either | ||
| * version 3 of the License, or (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
| * Lesser General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Lesser General Public License | ||
| * along with this program; if not, write to the Free Software Foundation, | ||
| * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
| */ | ||
| package org.sonar.python.checks; | ||
|
|
||
| import org.junit.Test; | ||
| import org.sonar.python.checks.utils.PythonCheckVerifier; | ||
|
|
||
| public class CognitiveComplexityFunctionCheckTest { | ||
|
|
||
| private final CognitiveComplexityFunctionCheck check = new CognitiveComplexityFunctionCheck(); | ||
|
|
||
| @Test | ||
| public void test() { | ||
| check.setThreshold(0); | ||
| PythonCheckVerifier.verify("src/test/resources/checks/cognitiveComplexityFunction.py", check); | ||
| } | ||
|
|
||
| @Test | ||
| public void default_threshold() throws Exception { | ||
| PythonCheckVerifier.verify("src/test/resources/checks/cognitiveComplexityFunctionDefault.py", check); | ||
| } | ||
| } |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vilchik-elena Can we test this secondary message? It is currently not done in the test file
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ivandalbosco No, it's not implemented in python, I've tested line numbers only