mirror of
https://github.com/realm/SwiftLint.git
synced 2026-06-06 20:18:40 +00:00
5a30991fa4
This cuts down on the boilerplate involved in writing SwiftSyntax-based rules. May not be significant right now since most rules are still built with SourceKit, but as we migrate more rules moving forward, this should make it easier for rule authors to write rules that behave performantly and correctly.
40 lines
1.4 KiB
Swift
40 lines
1.4 KiB
Swift
import SwiftSyntax
|
|
|
|
/// A SwiftLint CorrectableRule that performs its corrections using a SwiftSyntax `SyntaxRewriter`.
|
|
public protocol SwiftSyntaxCorrectableRule: SwiftSyntaxRule, CorrectableRule {
|
|
/// Produce a `ViolationsSyntaxRewriter` for the given file.
|
|
///
|
|
/// - parameter file: The file for which to produce the rewriter.
|
|
///
|
|
/// - returns: A `ViolationsSyntaxRewriter` for the given file.
|
|
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter?
|
|
}
|
|
|
|
public extension SwiftSyntaxCorrectableRule {
|
|
func correct(file: SwiftLintFile) -> [Correction] {
|
|
guard let rewriter = makeRewriter(file: file),
|
|
let syntaxTree = file.syntaxTree,
|
|
case let newTree = rewriter.visit(syntaxTree),
|
|
rewriter.correctionPositions.isNotEmpty else {
|
|
return []
|
|
}
|
|
|
|
file.write(newTree.description)
|
|
return rewriter
|
|
.correctionPositions
|
|
.sorted()
|
|
.map { position in
|
|
Correction(
|
|
ruleDescription: Self.description,
|
|
location: Location(file: file, position: position)
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A SwiftSyntax `SyntaxRewriter` that produces absolute positions where corrections were applied.
|
|
public protocol ViolationsSyntaxRewriter: SyntaxRewriter {
|
|
/// Positions in a source file where corrections were applied.
|
|
var correctionPositions: [AbsolutePosition] { get }
|
|
}
|