Skip to content

Commit

Permalink
Check at the violation position if a correction can be applied
Browse files Browse the repository at this point in the history
  • Loading branch information
SimplyDanny committed Jul 20, 2024
1 parent 238415b commit 27a82fa
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -546,5 +546,20 @@ struct OpeningBraceRuleExamples {
return
}
"""),
Example("""
if
"test".isEmpty
// swiftlint:disable:next opening_brace
{
// code here
}
"""): Example("""
if
"test".isEmpty
// swiftlint:disable:next opening_brace
{
// code here
}
"""),
]
}
21 changes: 14 additions & 7 deletions Source/SwiftLintCore/Protocols/SwiftSyntaxCorrectableRule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
if violations.isEmpty {
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
}
if correctionRanges.isEmpty {
return []
}

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

0 comments on commit 27a82fa

Please sign in to comment.