-
Notifications
You must be signed in to change notification settings - Fork 247
Add the UseExplicitNilCheckInConditions
rule.
#627
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
allevato
merged 1 commit into
swiftlang:main
from
allevato:no-discard-conditional-assignment
Sep 18, 2023
Merged
Changes from all commits
Commits
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 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
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
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
67 changes: 67 additions & 0 deletions
67
Sources/SwiftFormat/Rules/UseExplicitNilCheckInConditions.swift
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,67 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See https://swift.org/LICENSE.txt for license information | ||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import SwiftSyntax | ||
import SwiftSyntaxBuilder | ||
|
||
/// When checking an optional value for `nil`-ness, prefer writing an explicit `nil` check rather | ||
/// than binding and immediately discarding the value. | ||
/// | ||
/// For example, `if let _ = someValue { ... }` is forbidden. Use `if someValue != nil { ... }` | ||
/// instead. | ||
/// | ||
/// Lint: `let _ = expr` inside a condition list will yield a lint error. | ||
/// | ||
/// Format: `let _ = expr` inside a condition list will be replaced by `expr != nil`. | ||
@_spi(Rules) | ||
public final class UseExplicitNilCheckInConditions: SyntaxFormatRule { | ||
public override func visit(_ node: ConditionElementSyntax) -> ConditionElementSyntax { | ||
switch node.condition { | ||
case .optionalBinding(let optionalBindingCondition): | ||
guard | ||
let initializerClause = optionalBindingCondition.initializer, | ||
isDiscardedAssignmentPattern(optionalBindingCondition.pattern) | ||
else { | ||
return node | ||
} | ||
|
||
diagnose(.useExplicitNilComparison, on: optionalBindingCondition) | ||
|
||
// Since we're moving the initializer value from the RHS to the LHS of an expression/pattern, | ||
// preserve the relative position of the trailing trivia. Similarly, preserve the leading | ||
// trivia of the original node, since that token is being removed entirely. | ||
var value = initializerClause.value | ||
let trailingTrivia = value.trailingTrivia | ||
value.trailingTrivia = [] | ||
|
||
return ConditionElementSyntax( | ||
condition: .expression("\(node.leadingTrivia)\(value) != nil\(trailingTrivia)")) | ||
default: | ||
return node | ||
} | ||
} | ||
|
||
/// Returns true if the given pattern is a discarding assignment expression (for example, the `_` | ||
/// in `let _ = x`). | ||
private func isDiscardedAssignmentPattern(_ pattern: PatternSyntax) -> Bool { | ||
guard let exprPattern = pattern.as(ExpressionPatternSyntax.self) else { | ||
return false | ||
} | ||
return exprPattern.expression.is(DiscardAssignmentExprSyntax.self) | ||
} | ||
} | ||
|
||
extension Finding.Message { | ||
@_spi(Rules) | ||
public static let useExplicitNilComparison: Finding.Message = | ||
"compare this value using `!= nil` instead of binding and discarding it" | ||
} |
82 changes: 82 additions & 0 deletions
82
Tests/SwiftFormatTests/Rules/UseExplicitNilCheckInConditionsTests.swift
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,82 @@ | ||
import _SwiftFormatTestSupport | ||
|
||
@_spi(Rules) import SwiftFormat | ||
|
||
final class UseExplicitNilCheckInConditionsTests: LintOrFormatRuleTestCase { | ||
func testIfExpressions() { | ||
assertFormatting( | ||
UseExplicitNilCheckInConditions.self, | ||
input: """ | ||
if 1️⃣let _ = x {} | ||
if let x = y, 2️⃣let _ = x.m {} | ||
if let x = y {} else if 3️⃣let _ = z {} | ||
""", | ||
expected: """ | ||
if x != nil {} | ||
if let x = y, x.m != nil {} | ||
if let x = y {} else if z != nil {} | ||
""", | ||
findings: [ | ||
FindingSpec("1️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
FindingSpec("2️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
FindingSpec("3️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
] | ||
) | ||
} | ||
|
||
func testGuardStatements() { | ||
assertFormatting( | ||
UseExplicitNilCheckInConditions.self, | ||
input: """ | ||
guard 1️⃣let _ = x else {} | ||
guard let x = y, 2️⃣let _ = x.m else {} | ||
""", | ||
expected: """ | ||
guard x != nil else {} | ||
guard let x = y, x.m != nil else {} | ||
""", | ||
findings: [ | ||
FindingSpec("1️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
FindingSpec("2️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
] | ||
) | ||
} | ||
|
||
func testWhileStatements() { | ||
assertFormatting( | ||
UseExplicitNilCheckInConditions.self, | ||
input: """ | ||
while 1️⃣let _ = x {} | ||
while let x = y, 2️⃣let _ = x.m {} | ||
""", | ||
expected: """ | ||
while x != nil {} | ||
while let x = y, x.m != nil {} | ||
""", | ||
findings: [ | ||
FindingSpec("1️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
FindingSpec("2️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
] | ||
) | ||
} | ||
|
||
func testTriviaPreservation() { | ||
assertFormatting( | ||
UseExplicitNilCheckInConditions.self, | ||
input: """ | ||
if /*comment*/ 1️⃣let _ = x /*comment*/ {} | ||
if 2️⃣let _ = x // comment | ||
{} | ||
""", | ||
expected: """ | ||
if /*comment*/ x != nil /*comment*/ {} | ||
if x != nil // comment | ||
{} | ||
""", | ||
findings: [ | ||
FindingSpec("1️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
FindingSpec("2️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), | ||
] | ||
) | ||
} | ||
} |
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.
"would be replaced with empty literal..."?
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.
Ah, that's a typo from earlier, there was a race between the generate-the-docs PR and the one adding this rule so it didn't get generated the first time. I'll update that in a separate follow-up because I need to do a pass over all the rule docs anyway to make sure they're formatted nicely in the new Markdown file.