Skip to content
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

Check at the violation position if a correction can be applied #5682

Merged
merged 1 commit into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -566,5 +566,20 @@ struct OpeningBraceRuleExamples {
}
}
"""),
Example("""
if
"test".isEmpty
// swiftlint:disable:next opening_brace
{
// code here
}
"""): Example("""
if
"test".isEmpty
// swiftlint:disable:next opening_brace
{
// code here
}
"""),
]
}
23 changes: 15 additions & 8 deletions Source/SwiftLintCore/Protocols/SwiftSyntaxCorrectableRule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public extension SwiftSyntaxCorrectableRule {
if let rewriter = makeRewriter(file: file) {
let newTree = rewriter.visit(syntaxTree)
let positions = rewriter.correctionPositions
if positions.isEmpty {
guard positions.isNotEmpty else {
return []
}
let corrections = positions
Expand All @@ -40,25 +40,32 @@ public extension SwiftSyntaxCorrectableRule {
}

// There is no rewriter. Falling back to the correction ranges collected by the visitor (if any).
let violationCorrections = makeVisitor(file: file)
let violations = makeVisitor(file: file)
.walk(tree: syntaxTree, handler: \.violations)
.compactMap(\.correction)
if violationCorrections.isEmpty {
guard violations.isNotEmpty else {
return []
}

let locationConverter = file.locationConverter
let disabledRegions = file.regions()
.filter { $0.areRulesDisabled(ruleIDs: Self.description.allIdentifiers) }
.compactMap { $0.toSourceRange(locationConverter: locationConverter) }

typealias CorrectionRange = (range: NSRange, correction: String)
let correctionRanges = violationCorrections
let correctionRanges = violations
.filter { !$0.position.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) }
.compactMap(\.correction)
.compactMap { correction in
file.stringView.NSRange(start: correction.start, end: correction.end).map { range in
CorrectionRange(range: range, correction: correction.replacement)
}
}
.filter { (correctionRange: CorrectionRange) in
file.ruleEnabled(violatingRange: correctionRange.range, for: self) != nil
}
.sorted { (lhs: CorrectionRange, rhs: CorrectionRange) -> Bool in
lhs.range.location > rhs.range.location
}
guard correctionRanges.isNotEmpty else {
return []
}

var corrections = [Correction]()
var contents = file.contents
Expand Down