mirror of
https://github.com/realm/SwiftLint.git
synced 2026-06-06 20:18:40 +00:00
* [bazel] Remove custom SwiftSyntax BUILD file Something similar to this has been merged upstream instead now. This also renames the repo name to SwiftSyntax in preparation for it being in the BCR * [SwiftSyntax] Update to latest 509.0.0 tag https://github.com/apple/swift-syntax/releases/tag/509.0.0-swift-DEVELOPMENT-SNAPSHOT-2023-04-25-b
49 lines
1.7 KiB
Swift
49 lines
1.7 KiB
Swift
import SwiftSyntax
|
|
|
|
struct EmptyStringRule: ConfigurationProviderRule, OptInRule, SwiftSyntaxRule {
|
|
var configuration = SeverityConfiguration(.warning)
|
|
|
|
static let description = RuleDescription(
|
|
identifier: "empty_string",
|
|
name: "Empty String",
|
|
description: "Prefer checking `isEmpty` over comparing `string` to an empty string literal",
|
|
kind: .performance,
|
|
nonTriggeringExamples: [
|
|
Example("myString.isEmpty"),
|
|
Example("!myString.isEmpty"),
|
|
Example("\"\"\"\nfoo==\n\"\"\"")
|
|
],
|
|
triggeringExamples: [
|
|
Example(#"myString↓ == """#),
|
|
Example(#"myString↓ != """#),
|
|
Example(#"myString↓=="""#),
|
|
Example(##"myString↓ == #""#"##),
|
|
Example(###"myString↓ == ##""##"###)
|
|
]
|
|
)
|
|
|
|
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
|
Visitor(viewMode: .sourceAccurate)
|
|
}
|
|
}
|
|
|
|
private extension EmptyStringRule {
|
|
final class Visitor: ViolationsSyntaxVisitor {
|
|
override func visitPost(_ node: StringLiteralExprSyntax) {
|
|
guard
|
|
// Empty string literal: `""`, `#""#`, etc.
|
|
node.segments.onlyElement?.contentLength == .zero,
|
|
let previousToken = node.previousToken(viewMode: .sourceAccurate),
|
|
// On the rhs of an `==` or `!=` operator
|
|
previousToken.tokenKind.isEqualityComparison,
|
|
let secondPreviousToken = previousToken.previousToken(viewMode: .sourceAccurate)
|
|
else {
|
|
return
|
|
}
|
|
|
|
let violationPosition = secondPreviousToken.endPositionBeforeTrailingTrivia
|
|
violations.append(violationPosition)
|
|
}
|
|
}
|
|
}
|