Skip to content
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

Prefer if and switch expressions #5832

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ disabled_rules:
- no_grouping_extension
- no_magic_numbers
- one_declaration_per_file
- prefer_if_and_switch_expressions
- prefer_nimble
- prefixed_toplevel_constant
- required_deinit
Expand Down
1 change: 1 addition & 0 deletions Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ public let builtInRules: [any Rule.Type] = [
OverrideInExtensionRule.self,
PatternMatchingKeywordsRule.self,
PeriodSpacingRule.self,
PreferIfAndSwitchExpressionsRule.self,
PreferKeyPathRule.self,
PreferNimbleRule.self,
PreferSelfInStaticReferencesRule.self,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import SwiftOperators
import SwiftSyntax

@SwiftSyntaxRule
struct PreferIfAndSwitchExpressionsRule: Rule {
var configuration = SeverityConfiguration<Self>(.warning)

static let description = RuleDescription(
identifier: "prefer_if_and_switch_expressions",
name: "Prefer if and switch expressions",
description: "Use if and switch expressions instead of statements that perform similar actions in its branches",
kind: .idiomatic,
nonTriggeringExamples: PreferIfAndSwitchExpressionsRuleExamples.nonTriggeringExamples,
triggeringExamples: PreferIfAndSwitchExpressionsRuleExamples.triggeringExamples
)
}

private extension PreferIfAndSwitchExpressionsRule {
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> {
override func visitPost(_ node: IfExprSyntax) {
guard node.parent?.is(IfExprSyntax.self) != true else { return }

if let actions = node.actionInBranches(), actionToReplace(actionsInBranches: actions) != nil {
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}

override func visitPost(_ node: SwitchExprSyntax) {
let cases = node.cases.compactMap { $0.as(SwitchCaseSyntax.self) }
let actions = cases.map { $0.statements.extractSingleAction() }
if actionToReplace(actionsInBranches: actions) != nil {
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}

/// Compares the actions and return the equivalent action that would replace them.
func actionToReplace(actionsInBranches actions: [Action?]) -> Action? {
let validActions = actions.filter { $0 != .throw }

let nonNilActions = validActions.compactMap { $0 }
guard nonNilActions.count == validActions.count, nonNilActions.count >= 2 else {
return nil
}

return if nonNilActions.dropFirst().allSatisfy({ $0 == nonNilActions.first }) {
nonNilActions.first
} else {
nil
}
}
}
}

/// Represents an action executed in one branch of an if or switch expression
/// that may cause a violation of the rule.
private enum Action: Equatable {
case assignment(identifier: String)
case `return`
case `throw`
}

private extension IfExprSyntax {
/// Retrieves the list of `Action`.
/// Returns `nil` if there is no unconditional else block.
func actionInBranches() -> [Action?]? {
guard let elseBody else { return nil }

var branchesActions = switch elseBody {
case let .ifExpr(ifExprSyntax):
ifExprSyntax.actionInBranches()
case let .codeBlock(finalElse):
[finalElse.statements.extractSingleAction()]
}

if branchesActions != nil {
let thenBlockAction = body.statements.extractSingleAction()
branchesActions?.append(thenBlockAction)
}

return branchesActions
}
}

private extension CodeBlockItemListSyntax {
/// Extracts the only action in the block.
func extractSingleAction() -> Action? {
guard let statement = onlyElement else { return nil }

if statement.item.is(ReturnStmtSyntax.self) {
return .return
}

if statement.item.is(ThrowStmtSyntax.self) {
return .throw
}

if
let sequenceExpr = statement.item.as(SequenceExprSyntax.self),
let folded = try? OperatorTable.standardOperators.foldSingle(sequenceExpr),
let operatorExpr = folded.as(InfixOperatorExprSyntax.self),
operatorExpr.operator.is(AssignmentExprSyntax.self),
let declReference = operatorExpr.leftOperand.as(DeclReferenceExprSyntax.self) {
return .assignment(identifier: declReference.baseName.text)
}

return nil
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
internal struct PreferIfAndSwitchExpressionsRuleExamples {
static let nonTriggeringExamples = [
Example("""
if cond {
// Nothing
} else {
return 2
}
return 1
"""),
Example("""
if cond {
print("Hey")
return 1
} else {
return 2
}
"""),
Example("""
return if cond {
1
} else {
2
}
"""),
Example("""
return if cond {
1
} else {
2
}
"""),
Example("""
if cond {
return 1
} else {
throw TestError.test
}
"""),
Example("""
let x = switch value {
case 1:
"One"
case 2:
"Two"
default:
fatalError()
}
"""),
Example("""
if value {
x = "One"
} else {
y = "Two"
}
"""),
Example("""
switch value {
case 1:
x = "One"
case 2:
y = "Two"
default:
z = "Three"
}
"""),
]

static let triggeringExamples = [
Example("""
func f(cond: Bool) -> Int {
↓if cond {
return 1
} else if self.otherCond {
return 2
} else {
return 3
}
}
"""),
Example("""
func f(cond: Bool) {
let r: Int
↓if cond {
r = 1
} else {
// Some comment
r = 2
}
}
"""),
Example("""
func test(x: Int) throws -> String {
↓switch x {
case 1:
return "One"
case 2:
return "Two"
default:
return "More"
}
}
"""),
Example("""
func test(x: Int) throws -> String {
↓switch x {
case 1:
return "One"
case 2:
return "Two"
default:
throw TestError.test
}
}
"""),
Example("""
init(rawValue: String) throws {
↓switch rawValue {
case "lemon": self = .lemon
case "lime": self = .lime
default: throw TestError.test
}
}
"""),
]
}
6 changes: 6 additions & 0 deletions Tests/GeneratedTests/GeneratedTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,12 @@ final class PeriodSpacingRuleGeneratedTests: SwiftLintTestCase {
}
}

final class PreferIfAndSwitchExpressionsRuleGeneratedTests: SwiftLintTestCase {
func testWithDefaultConfiguration() {
verifyRule(PreferIfAndSwitchExpressionsRule.description)
}
}

final class PreferKeyPathRuleGeneratedTests: SwiftLintTestCase {
func testWithDefaultConfiguration() {
verifyRule(PreferKeyPathRule.description)
Expand Down
2 changes: 2 additions & 0 deletions Tests/IntegrationTests/default_rule_configurations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,8 @@ pattern_matching_keywords:
severity: warning
period_spacing:
severity: warning
prefer_if_and_switch_expressions:
severity: warning
prefer_key_path:
severity: warning
restrict_to_standard_functions: true
Expand Down