Exclude `self.x = x` from being reported in the `redundant_self_in_closure` rule (#4996)

This commit is contained in:
Danny Mösch 2023-05-11 23:26:39 +02:00 committed by GitHub
parent 8827fca693
commit 3cf9585b2e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 2 deletions

View File

@ -10,7 +10,10 @@
#### Enhancements
* None.
* Exclude simple assignments of the form `self.x = x` from being reported by
the `redundant_self_in_closure` rule.
[SimplyDanny](https://github.com/SimplyDanny)
[#4988](https://github.com/realm/SwiftLint/issues/4988)
#### Bug Fixes

View File

@ -37,6 +37,15 @@ struct RedundantSelfInClosureRule: SwiftSyntaxRule, CorrectableRule, Configurati
f { [weak self] in if let self { x = 1 } }
}
}
"""),
Example("""
struct S {
var x = 0
func f(_ work: @escaping () -> Void) { work() }
func g(x: Int) {
f { self.x = x }
}
}
""")
],
triggeringExamples: [
@ -287,8 +296,20 @@ private class ExplicitSelfVisitor: ViolationsSyntaxVisitor {
super.init(viewMode: .sourceAccurate)
}
override func visit(_ node: SequenceExprSyntax) -> SyntaxVisitorContinueKind {
let elements = node.elements
if elements.count == 3,
let assignee = elements.first?.as(MemberAccessExprSyntax.self), assignee.isBaseSelf,
elements.dropFirst(1).first?.is(AssignmentExprSyntax.self) == true,
elements.dropFirst(2).first?.as(IdentifierExprSyntax.self)?.identifier.text == assignee.name.text {
// We have something like `self.x = x` which is quite common and should thus be skipped.
return .skipChildren
}
return .visitChildren
}
override func visitPost(_ node: MemberAccessExprSyntax) {
if node.base?.as(IdentifierExprSyntax.self)?.isSelf == true, isSelfRedundant {
if node.isBaseSelf, isSelfRedundant {
corrections.append(
(start: node.positionAfterSkippingLeadingTrivia, end: node.dot.endPositionBeforeTrailingTrivia)
)
@ -313,3 +334,9 @@ private class ExplicitSelfVisitor: ViolationsSyntaxVisitor {
return false
}
}
private extension MemberAccessExprSyntax {
var isBaseSelf: Bool {
base?.as(IdentifierExprSyntax.self)?.isSelf == true
}
}