-
Notifications
You must be signed in to change notification settings - Fork 2.2k
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
Add Cognitive Complexity Rule
#5838
Open
lorwe
wants to merge
3
commits into
realm:main
Choose a base branch
from
lorwe:cognitive-complexity
base: main
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
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
This file contains 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 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
266 changes: 266 additions & 0 deletions
266
Source/SwiftLintBuiltInRules/Rules/Metrics/CognitiveComplexityRule.swift
This file contains 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,266 @@ | ||
import Foundation | ||
import SwiftSyntax | ||
|
||
@SwiftSyntaxRule | ||
struct CognitiveComplexityRule: Rule { | ||
var configuration = CognitiveComplexityConfiguration() | ||
|
||
static let description = RuleDescription( | ||
identifier: "cognitive_complexity", | ||
name: "Cognitive Complexity", | ||
description: "Cognitive complexity of function bodies should be limited.", | ||
kind: .metrics, | ||
nonTriggeringExamples: [ | ||
Example(""" | ||
func f1(count: Int, buffer: [Int]) -> Int { | ||
if count == 0 | ||
|| buffer.count = 0 { | ||
return 0 | ||
} | ||
var sum = 0 | ||
for index in 0..<buffer.count { | ||
if buffer[index] > 0 | ||
&& buffer[index] <= 10 { | ||
if buffer.count > 10 { | ||
if buffer[index] % 2 == 0 { | ||
sum += buffer[index] | ||
} else if sum > 0 { | ||
sum -= buffer[index] | ||
} | ||
} | ||
} | ||
} | ||
if sum < 0 { | ||
return -sum | ||
} | ||
return sum | ||
} | ||
"""), | ||
Example(""" | ||
func f2(count: Int, buffer: [Int]) -> Int { | ||
var sum = 0 | ||
for index in 0..<buffer.count { | ||
if buffer[index] > 0 && buffer[index] <= 10 { | ||
if buffer.count > 10 { | ||
switch buffer[index] % 2 { | ||
case 0: | ||
if sum > 0 { | ||
sum += buffer[index] | ||
} | ||
default: | ||
if sum > 0 { | ||
sum -= buffer[index] | ||
} | ||
} | ||
} | ||
} | ||
} | ||
return sum | ||
} | ||
"""), | ||
], | ||
triggeringExamples: [ | ||
Example(""" | ||
func f3(count: Int, buffer: [Int]) -> Int { | ||
guard count > 0, | ||
buffer.count > 0 { | ||
return 0 | ||
} | ||
var sum = 0 | ||
for index in 0..<buffer.count { | ||
if buffer[index] > 0 | ||
&& buffer[index] <= 10 { | ||
if buffer.count > 10 { | ||
if buffer[index] % 2 == 0 { | ||
sum += buffer[index] | ||
} else if sum > 0 { | ||
sum -= buffer[index] | ||
} else if sum < 0 { | ||
sum += buffer[index] | ||
} | ||
} | ||
} | ||
} | ||
if sum < 0 { | ||
return -sum | ||
} | ||
return sum | ||
} | ||
"""), | ||
] | ||
) | ||
} | ||
|
||
private extension CognitiveComplexityRule { | ||
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> { | ||
override func visitPost(_ node: FunctionDeclSyntax) { | ||
guard let body = node.body else { | ||
return | ||
} | ||
|
||
// for legacy reasons, we try to put the violation in the static or class keyword | ||
let violationToken = node.modifiers.staticOrClassModifier ?? node.funcKeyword | ||
validate(body: body, violationToken: violationToken) | ||
} | ||
|
||
override func visitPost(_ node: InitializerDeclSyntax) { | ||
guard let body = node.body else { | ||
return | ||
} | ||
|
||
validate(body: body, violationToken: node.initKeyword) | ||
} | ||
|
||
private func validate(body: CodeBlockSyntax, violationToken: TokenSyntax) { | ||
let complexity = ComplexityVisitor( | ||
ignoresLogicalOperatorSequences: configuration.ignoresLogicalOperatorSequences | ||
).walk(tree: body, handler: \.complexity) | ||
|
||
for parameter in configuration.params where complexity > parameter.value { | ||
let reason = "Function should have cognitive complexity \(configuration.length.warning) or less; " + | ||
"currently complexity is \(complexity)" | ||
|
||
let violation = ReasonedRuleViolation( | ||
position: violationToken.positionAfterSkippingLeadingTrivia, | ||
reason: reason, | ||
severity: parameter.severity | ||
) | ||
violations.append(violation) | ||
return | ||
} | ||
} | ||
} | ||
|
||
private class ComplexityVisitor: SyntaxVisitor { | ||
private let ignoresLogicalOperatorSequences: Bool | ||
private(set) var complexity = 0 | ||
private var nesting = 0 | ||
|
||
init(ignoresLogicalOperatorSequences: Bool) { | ||
self.ignoresLogicalOperatorSequences = ignoresLogicalOperatorSequences | ||
super.init(viewMode: .sourceAccurate) | ||
} | ||
|
||
override func visit(_: ForStmtSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: ForStmtSyntax) { | ||
nesting -= 1 | ||
complexity += nesting + 1 | ||
} | ||
|
||
override func visit(_: IfExprSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It feels like there's quite a lot of repetition in the methods - it would be nice to abstract that way a bit if possible |
||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_ node: IfExprSyntax) { | ||
nesting -= 1 | ||
let nesting = node.parent?.as(IfExprSyntax.self)?.elseBody?.is(IfExprSyntax.self) == true ? 0 : nesting | ||
if ignoresLogicalOperatorSequences { | ||
complexity += nesting + 1 | ||
} else { | ||
complexity += nesting + node.conditions.sequenceCount | ||
} | ||
} | ||
|
||
override func visit(_: GuardStmtSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_ node: GuardStmtSyntax) { | ||
nesting -= 1 | ||
if ignoresLogicalOperatorSequences { | ||
complexity += nesting + 1 | ||
} else { | ||
complexity += nesting + node.conditions.sequenceCount | ||
} | ||
} | ||
|
||
override func visit(_: RepeatStmtSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: RepeatStmtSyntax) { | ||
nesting -= 1 | ||
complexity += nesting + 1 | ||
} | ||
|
||
override func visit(_: WhileStmtSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: WhileStmtSyntax) { | ||
nesting -= 1 | ||
complexity += nesting + 1 | ||
} | ||
|
||
override func visit(_: CatchClauseSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: CatchClauseSyntax) { | ||
nesting -= 1 | ||
complexity += nesting + 1 | ||
} | ||
|
||
override func visitPost(_: SwitchExprSyntax) { | ||
complexity += 1 | ||
} | ||
|
||
override func visitPost(_: TernaryExprSyntax) { | ||
complexity += 1 | ||
} | ||
|
||
override func visitPost(_ node: BreakStmtSyntax) { | ||
if node.label != nil { | ||
complexity += 1 | ||
} | ||
} | ||
|
||
override func visitPost(_ node: ContinueStmtSyntax) { | ||
if node.label != nil { | ||
complexity += 1 | ||
} | ||
} | ||
|
||
override func visit(_: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: FunctionDeclSyntax) { | ||
nesting -= 1 | ||
} | ||
|
||
override func visit(_: ClosureExprSyntax) -> SyntaxVisitorContinueKind { | ||
nesting += 1 | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: ClosureExprSyntax) { | ||
nesting -= 1 | ||
} | ||
} | ||
} | ||
|
||
private extension DeclModifierListSyntax { | ||
var staticOrClassModifier: TokenSyntax? { | ||
first { element in | ||
let kind = element.name.tokenKind | ||
return kind == .keyword(.static) || kind == .keyword(.class) | ||
}?.name | ||
} | ||
} | ||
|
||
private extension ConditionElementListSyntax { | ||
var sequenceCount: Int { | ||
description.components(separatedBy: .newlines).count | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
Source/SwiftLintBuiltInRules/Rules/RuleConfigurations/CognitiveComplexityConfiguration.swift
This file contains 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,16 @@ | ||
import SourceKittenFramework | ||
import SwiftLintCore | ||
|
||
@AutoConfigParser | ||
struct CognitiveComplexityConfiguration: RuleConfiguration { | ||
typealias Parent = CognitiveComplexityRule | ||
|
||
@ConfigurationElement(inline: true) | ||
private(set) var length = SeverityLevelsConfiguration<Parent>(warning: 15, error: 20) | ||
@ConfigurationElement(key: "ignores_logical_operator_sequences") | ||
private(set) var ignoresLogicalOperatorSequences = false | ||
|
||
var params: [RuleParameter<Int>] { | ||
length.params | ||
} | ||
} |
This file contains 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
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.
If you look at previous rule addition changelog entries, they tend to be a bit wordier, and to specify the rule by its identifier. e.g.