-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Add opt-in unneeded_throws_rethrows
rule
#6069
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
Open
tonyskansf
wants to merge
19
commits into
realm:main
Choose a base branch
from
tonyskansf:opt-in-unneeded-throws-rule
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
19 commits
Select commit
Hold shift + click to select a range
0a9ef40
Add opt-in unneeded_throws_rethrows rule
tonyskansf 73c3a9e
Resolve testSwiftLintAutoCorrects integration test fail
tonyskansf e366373
Resolve false positives
tonyskansf 3d77f3a
Resolve testSwiftLintAutoCorrects integration test fail
tonyskansf 04bf492
Resolve unhandled cases
tonyskansf 556be93
Handle premature closing scope
tonyskansf 144d859
Handle more do-catch edge cases
tonyskansf bb93bfe
Correct typo
tonyskansf 9e45610
Run swift run swiftlint-dev rules register
tonyskansf 5898e7a
Address batch of comments
tonyskansf 25c4905
Recursively check type annotation instead of iterating over children
tonyskansf ff94069
Correct typed throws correction, add examples
tonyskansf 3416302
Fix corrections with trailing trivia
tonyskansf 2977a29
Add newline
tonyskansf c5cd3db
Refactor validate method
tonyskansf 84b7081
Only check single-element tuples for unneeded throws
tonyskansf 1f54117
Add test case for single-element tuple type
tonyskansf d3b4bf0
Remove trailing whitespace
tonyskansf 032538b
Fix false positive for throwing closures in variable declarations
tonyskansf 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
220 changes: 220 additions & 0 deletions
220
Source/SwiftLintBuiltInRules/Rules/Lint/UnneededThrowsRule.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,220 @@ | ||
import SwiftLintCore | ||
import SwiftSyntax | ||
|
||
@SwiftSyntaxRule(correctable: true, optIn: true) | ||
struct UnneededThrowsRule: Rule { | ||
var configuration = SeverityConfiguration<Self>(.warning) | ||
|
||
static let description = RuleDescription( | ||
identifier: "unneeded_throws_rethrows", | ||
name: "Unneeded (re)throws keyword", | ||
description: "Non-throwing functions/properties/closures should not be marked as `throws` or `rethrows`.", | ||
kind: .lint, | ||
nonTriggeringExamples: UnneededThrowsRuleExamples.nonTriggeringExamples, | ||
triggeringExamples: UnneededThrowsRuleExamples.triggeringExamples, | ||
corrections: UnneededThrowsRuleExamples.corrections | ||
) | ||
} | ||
|
||
private extension UnneededThrowsRule { | ||
struct Scope { | ||
var throwsClause: ThrowsClauseSyntax? | ||
} | ||
|
||
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> { | ||
private var scopes = Stack<Scope>() | ||
|
||
override var skippableDeclarations: [any DeclSyntaxProtocol.Type] { | ||
[ | ||
ProtocolDeclSyntax.self, | ||
TypeAliasDeclSyntax.self, | ||
EnumCaseDeclSyntax.self, | ||
] | ||
} | ||
|
||
override func visit(_: FunctionParameterClauseSyntax) -> SyntaxVisitorContinueKind { | ||
.skipChildren | ||
} | ||
|
||
override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { | ||
scopes.openScope(with: node.signature.effectSpecifiers?.throwsClause) | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: InitializerDeclSyntax) { | ||
if let closedScope = scopes.closeScope() { | ||
validate( | ||
scope: closedScope, | ||
construct: "initializer" | ||
) | ||
} | ||
} | ||
|
||
override func visit(_ node: AccessorDeclSyntax) -> SyntaxVisitorContinueKind { | ||
scopes.openScope(with: node.effectSpecifiers?.throwsClause) | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: AccessorDeclSyntax) { | ||
if let closedScope = scopes.closeScope() { | ||
validate( | ||
scope: closedScope, | ||
construct: "accessor" | ||
) | ||
} | ||
} | ||
|
||
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { | ||
scopes.openScope(with: node.signature.effectSpecifiers?.throwsClause) | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_: FunctionDeclSyntax) { | ||
if let closedScope = scopes.closeScope() { | ||
validate( | ||
scope: closedScope, | ||
construct: "body of this function" | ||
) | ||
} | ||
} | ||
|
||
override func visit(_ node: PatternBindingSyntax) -> SyntaxVisitorContinueKind { | ||
if node.containsInitializerClause, let functionTypeSyntax = node.functionTypeSyntax { | ||
scopes.openScope(with: functionTypeSyntax.effectSpecifiers?.throwsClause) | ||
} | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_ node: PatternBindingSyntax) { | ||
if node.containsInitializerClause, node.functionTypeSyntax != nil { | ||
if let closedScope = scopes.closeScope() { | ||
validate( | ||
scope: closedScope, | ||
construct: "closure type" | ||
) | ||
} | ||
} | ||
} | ||
|
||
override func visit(_ node: FunctionCallExprSyntax) -> SyntaxVisitorContinueKind { | ||
if node.containsTaskDeclaration { | ||
scopes.openScope() | ||
} | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_ node: FunctionCallExprSyntax) { | ||
if node.containsTaskDeclaration { | ||
tonyskansf marked this conversation as resolved.
Show resolved
Hide resolved
|
||
scopes.closeScope() | ||
} | ||
} | ||
|
||
override func visit(_: DoStmtSyntax) -> SyntaxVisitorContinueKind { | ||
scopes.openScope() | ||
return .visitChildren | ||
} | ||
|
||
override func visitPost(_ node: CodeBlockSyntax) { | ||
if node.parent?.is(DoStmtSyntax.self) == true { | ||
scopes.closeScope() | ||
} | ||
} | ||
|
||
override func visitPost(_ node: DoStmtSyntax) { | ||
if node.catchClauses.contains(where: { $0.catchItems.isEmpty }) { | ||
// All errors will be caught. | ||
return | ||
} | ||
scopes.markCurrentScopeAsThrowing() | ||
} | ||
|
||
override func visitPost(_ node: ForStmtSyntax) { | ||
if node.tryKeyword != nil { | ||
scopes.markCurrentScopeAsThrowing() | ||
} | ||
} | ||
|
||
override func visitPost(_ node: TryExprSyntax) { | ||
if node.questionOrExclamationMark == nil { | ||
scopes.markCurrentScopeAsThrowing() | ||
} | ||
} | ||
|
||
override func visitPost(_: ThrowStmtSyntax) { | ||
scopes.markCurrentScopeAsThrowing() | ||
} | ||
|
||
private func validate(scope: Scope, construct: String) { | ||
guard let throwsClause = scope.throwsClause else { return } | ||
violations.append( | ||
ReasonedRuleViolation( | ||
position: throwsClause.positionAfterSkippingLeadingTrivia, | ||
reason: "Superfluous 'throws'; \(construct) does not throw any error", | ||
correction: ReasonedRuleViolation.ViolationCorrection( | ||
// Move start position back by 1 to include the space before the throwsClause | ||
start: throwsClause.positionAfterSkippingLeadingTrivia.advanced(by: -1), | ||
end: throwsClause.endPositionBeforeTrailingTrivia, | ||
replacement: "" | ||
) | ||
) | ||
) | ||
} | ||
} | ||
} | ||
|
||
private extension Stack where Element == UnneededThrowsRule.Scope { | ||
mutating func markCurrentScopeAsThrowing() { | ||
modifyLast { currentScope in | ||
currentScope.throwsClause = nil | ||
} | ||
} | ||
|
||
mutating func openScope(with throwsClause: ThrowsClauseSyntax? = nil) { | ||
push(UnneededThrowsRule.Scope(throwsClause: throwsClause)) | ||
} | ||
|
||
@discardableResult | ||
mutating func closeScope() -> Element? { | ||
pop() | ||
} | ||
} | ||
|
||
private extension FunctionCallExprSyntax { | ||
var containsTaskDeclaration: Bool { | ||
children(viewMode: .sourceAccurate).contains { child in | ||
child.as(DeclReferenceExprSyntax.self)?.baseName.tokenKind == .identifier("Task") | ||
} | ||
} | ||
} | ||
|
||
private extension PatternBindingSyntax { | ||
var containsInitializerClause: Bool { | ||
initializer != nil | ||
} | ||
|
||
var functionTypeSyntax: FunctionTypeSyntax? { | ||
typeAnnotation?.type.baseFunctionTypeSyntax | ||
} | ||
} | ||
|
||
private extension TypeSyntax { | ||
var baseFunctionTypeSyntax: FunctionTypeSyntax? { | ||
switch Syntax(self).as(SyntaxEnum.self) { | ||
case .functionType(let function): | ||
function | ||
case .optionalType(let optional): | ||
optional.wrappedType.baseFunctionTypeSyntax | ||
case .attributedType(let attributed): | ||
attributed.baseType.baseFunctionTypeSyntax | ||
case .tupleType(let tuple): | ||
// It's hard to check for the necessity of throws keyword in multi-element tuples | ||
if tuple.elements.count == 1 { | ||
tuple.elements.first?.type.baseFunctionTypeSyntax | ||
} else { | ||
nil | ||
} | ||
default: | ||
nil | ||
} | ||
} | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.