Skip to content

Commit

Permalink
Rewrite trailing_closure rule with SwiftSyntax (realm#5414)
Browse files Browse the repository at this point in the history
  • Loading branch information
KS1019 authored Jan 15, 2024
1 parent 2f15f66 commit 6af9419
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 102 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@
* `multiline_literal_brackets`
* `nimble_operator`
* `opening_brace`
* `trailing_closure`
* `void_return`

[SimplyDanny](https://github.com/SimplyDanny)
[kishikawakatsumi](https://github.com/kishikawakatsumi)
[Marcelo Fabri](https://github.com/marcelofabri)
[swiftty](https://github.com/swiftty)
[KS1019](https://github.com/KS1019)

* Print invalid keys when configuration parsing fails.
[SimplyDanny](https://github.com/SimplyDanny)
Expand Down
157 changes: 55 additions & 102 deletions Source/SwiftLintBuiltInRules/Rules/Style/TrailingClosureRule.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Foundation
import SourceKittenFramework
import SwiftLintCore
import SwiftSyntax

@SwiftSyntaxRule
struct TrailingClosureRule: OptInRule {
var configuration = TrailingClosureConfiguration()

Expand All @@ -18,127 +19,79 @@ struct TrailingClosureRule: OptInRule {
Example("offsets.sorted { $0.offset < $1.offset }"),
Example("foo.something({ return 1 }())"),
Example("foo.something({ return $0 }(1))"),
Example("foo.something(0, { return 1 }())")
Example("foo.something(0, { return 1 }())"),
Example("for x in list.filter({ $0.isValid }) {}"),
Example("if list.allSatisfy({ $0.isValid }) {}"),
Example("foo(param1: 1, param2: { _ in true }, param3: 0)"),
Example("foo(param1: 1, param2: { _ in true }) { $0 + 1 }"),
Example("foo(param1: { _ in false }, param2: { _ in true })"),
Example("foo(param1: { _ in false }, param2: { _ in true }, param3: { _ in false })"),
Example("""
if f({ true }), g({ true }) {
print("Hello")
}
"""),
Example("""
for i in h({ [1,2,3] }) {
print(i)
}
""")
],
triggeringExamples: [
Example("↓foo.map({ $0 + 1 })"),
Example("↓foo.reduce(0, combine: { $0 + 1 })"),
Example("↓offsets.sorted(by: { $0.offset < $1.offset })"),
Example("↓foo.something(0, { $0 + 1 })")
Example("↓foo.something(0, { $0 + 1 })"),
Example("↓foo.something(param1: { _ in true }, param2: 0, param3: { _ in false })"),
Example("""
for n in list {
↓n.forEach({ print($0) })
}
""", excludeFromDocumentation: true)
]
)
}

func validate(file: SwiftLintFile) -> [StyleViolation] {
let dict = file.structureDictionary
return violationOffsets(for: dict, file: file).map {
StyleViolation(ruleDescription: Self.description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file, byteOffset: $0))
}
}

private func violationOffsets(for dictionary: SourceKittenDictionary, file: SwiftLintFile) -> [ByteCount] {
var results = [ByteCount]()

if dictionary.expressionKind == .call,
shouldBeTrailingClosure(dictionary: dictionary, file: file),
let offset = dictionary.offset {
results = [offset]
}
private extension TrailingClosureRule {
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> {
override func visitPost(_ node: FunctionCallExprSyntax) {
guard node.trailingClosure == nil else { return }

if let kind = dictionary.statementKind, kind != .brace {
// trailing closures are not allowed in `if`, `guard`, etc
results += dictionary.substructure.flatMap { subDict -> [ByteCount] in
guard subDict.statementKind == .brace else {
return []
if configuration.onlySingleMutedParameter {
if node.containsOnlySingleMutedParameter {
violations.append(node.positionAfterSkippingLeadingTrivia)
}

return violationOffsets(for: subDict, file: file)
}
} else {
results += dictionary.substructure.flatMap { subDict in
violationOffsets(for: subDict, file: file)
} else if node.shouldTrigger {
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}

return results
}

private func shouldBeTrailingClosure(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool {
func shouldTrigger() -> Bool {
return !isAlreadyTrailingClosure(dictionary: dictionary, file: file) &&
!isAnonymousClosureCall(dictionary: dictionary, file: file)
}

let arguments = dictionary.enclosedArguments

// check if last parameter should be trailing closure
if !configuration.onlySingleMutedParameter, arguments.isNotEmpty,
case let closureArguments = filterClosureArguments(arguments, file: file),
closureArguments.count == 1,
closureArguments.last?.offset == arguments.last?.offset {
return shouldTrigger()
override func visit(_ node: ConditionElementListSyntax) -> SyntaxVisitorContinueKind {
.skipChildren
}

let argumentsCountIsExpected: Bool = {
if SwiftVersion.current >= .fiveDotSix, arguments.count == 1,
arguments[0].expressionKind == .argument {
return true
}

return arguments.isEmpty
}()
// check if there's only one unnamed parameter that is a closure
if argumentsCountIsExpected,
let offset = dictionary.offset,
let totalLength = dictionary.length,
let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
case let start = nameOffset + nameLength,
case let length = totalLength + offset - start,
case let byteRange = ByteRange(location: start, length: length),
let range = file.stringView.byteRangeToNSRange(byteRange),
let match = regex("\\s*\\(\\s*\\{").firstMatch(in: file.contents, options: [], range: range)?.range,
match.location == range.location {
return shouldTrigger()
override func visit(_ node: ForStmtSyntax) -> SyntaxVisitorContinueKind {
walk(node.body)
return .skipChildren
}

return false
}
}

private func filterClosureArguments(_ arguments: [SourceKittenDictionary],
file: SwiftLintFile) -> [SourceKittenDictionary] {
return arguments.filter { argument in
guard let bodyByteRange = argument.bodyByteRange,
let range = file.stringView.byteRangeToNSRange(bodyByteRange),
let match = regex("\\s*\\{").firstMatch(in: file.contents, options: [], range: range)?.range,
match.location == range.location
else {
return false
}

return true
}
private extension FunctionCallExprSyntax {
var containsOnlySingleMutedParameter: Bool {
arguments.onlyElement?.isMutedClosure == true
}

private func isAlreadyTrailingClosure(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool {
guard let byteRange = dictionary.byteRange,
let text = file.stringView.substringWithByteRange(byteRange)
else {
return false
}

return !text.hasSuffix(")")
var shouldTrigger: Bool {
arguments.last?.expression.is(ClosureExprSyntax.self) == true
// If at least last two arguments were ClosureExprSyntax, a violation should not be triggered.
&& (arguments.count <= 1
|| !arguments.dropFirst(arguments.count - 2).allSatisfy({ $0.expression.is(ClosureExprSyntax.self) }))
}
}

private func isAnonymousClosureCall(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool {
guard let byteRange = dictionary.byteRange,
let range = file.stringView.byteRangeToNSRange(byteRange)
else {
return false
}

let pattern = regex("\\)\\s*\\)\\z")
return pattern.numberOfMatches(in: file.contents, range: range) > 0
private extension LabeledExprSyntax {
var isMutedClosure: Bool {
label == nil && expression.is(ClosureExprSyntax.self)
}
}

0 comments on commit 6af9419

Please sign in to comment.