Skip to content

Commit

Permalink
Rewrite empty_collection_literal with SwiftSyntax (realm#4220)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpsim authored Sep 19, 2022
1 parent 992cc9a commit 8d500d1
Showing 1 changed file with 32 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import SourceKittenFramework
import SwiftSyntax

public struct EmptyCollectionLiteralRule: ConfigurationProviderRule, OptInRule {
public struct EmptyCollectionLiteralRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)

public init() {}
Expand Down Expand Up @@ -28,13 +28,36 @@ public struct EmptyCollectionLiteralRule: ConfigurationProviderRule, OptInRule {
]
)

public func validate(file: SwiftLintFile) -> [StyleViolation] {
let pattern = "\\b\\s*(==|!=)\\s*\\[\\s*:?\\s*\\]"
let excludingKinds = SyntaxKind.commentAndStringKinds
return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds).map {
StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
public func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor? {
Visitor()
}
}

private extension EmptyCollectionLiteralRule {
final class Visitor: SyntaxVisitor, ViolationsSyntaxVisitor {
private(set) var violationPositions: [AbsolutePosition] = []

override func visitPost(_ node: TokenSyntax) {
guard
node.tokenKind.isEqualityComparison,
let violationPosition = node.previousToken?.endPositionBeforeTrailingTrivia,
let expectedLeftSquareBracketToken = node.nextToken,
expectedLeftSquareBracketToken.tokenKind == .leftSquareBracket,
let expectedColonToken = expectedLeftSquareBracketToken.nextToken,
expectedColonToken.tokenKind == .colon || expectedColonToken.tokenKind == .rightSquareBracket
else {
return
}

violationPositions.append(violationPosition)
}
}
}

private extension TokenKind {
var isEqualityComparison: Bool {
self == .spacedBinaryOperator("==") ||
self == .spacedBinaryOperator("!=") ||
self == .unspacedBinaryOperator("==")
}
}

0 comments on commit 8d500d1

Please sign in to comment.