-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Migrate VerticalWhitespaceClosingBracesRule to SwiftSyntax #6118
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
Open
jpsim
wants to merge
1
commit into
main
Choose a base branch
from
migrate-verticalwhitespaceclosingbracesrule-to-swiftsyntax
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,7 +1,8 @@ | ||||||
| import Foundation | ||||||
| import SourceKittenFramework | ||||||
| import SwiftLintCore | ||||||
| import SwiftSyntax | ||||||
|
|
||||||
| struct VerticalWhitespaceClosingBracesRule: CorrectableRule, OptInRule { | ||||||
| @SwiftSyntaxRule(correctable: true, optIn: true) | ||||||
| struct VerticalWhitespaceClosingBracesRule: Rule { | ||||||
| var configuration = VerticalWhitespaceClosingBracesConfiguration() | ||||||
|
|
||||||
| static let description = RuleDescription( | ||||||
|
|
@@ -14,52 +15,304 @@ struct VerticalWhitespaceClosingBracesRule: CorrectableRule, OptInRule { | |||||
| triggeringExamples: Array(VerticalWhitespaceClosingBracesRuleExamples.violatingToValidExamples.keys.sorted()), | ||||||
| corrections: VerticalWhitespaceClosingBracesRuleExamples.violatingToValidExamples.removingViolationMarkers() | ||||||
| ) | ||||||
| } | ||||||
|
|
||||||
| private struct TriviaAnalysis { | ||||||
| var consecutiveNewlines = 0 | ||||||
| var violationStartPosition: AbsolutePosition? | ||||||
| var violationEndPosition: AbsolutePosition? | ||||||
| } | ||||||
|
|
||||||
| private let pattern = "((?:\\n[ \\t]*)+)(\\n[ \\t]*[)}\\]])" | ||||||
| private let trivialLinePattern = "((?:\\n[ \\t]*)+)(\\n[ \\t)}\\]]*$)" | ||||||
| private struct CorrectionState { | ||||||
| var result = [TriviaPiece]() | ||||||
| var consecutiveNewlines = 0 | ||||||
| var pendingWhitespace = [TriviaPiece]() | ||||||
| var correctionCount = 0 | ||||||
| var hasViolation = false | ||||||
| } | ||||||
|
|
||||||
| func validate(file: SwiftLintFile) -> [StyleViolation] { | ||||||
| let pattern = configuration.onlyEnforceBeforeTrivialLines ? self.trivialLinePattern : self.pattern | ||||||
| private struct NewlineProcessingContext { | ||||||
| let currentPosition: AbsolutePosition | ||||||
| let consecutiveNewlines: Int | ||||||
| var violationStartPosition: AbsolutePosition? | ||||||
| var violationEndPosition: AbsolutePosition? | ||||||
| } | ||||||
|
|
||||||
| let patternRegex: NSRegularExpression = regex(pattern) | ||||||
| private func isTokenLineTrivialHelper( | ||||||
| for token: TokenSyntax, | ||||||
| file: SwiftLintFile, | ||||||
| locationConverter: SourceLocationConverter | ||||||
| ) -> Bool { | ||||||
| let lineColumn = locationConverter.location(for: token.positionAfterSkippingLeadingTrivia) | ||||||
| let line = lineColumn.line | ||||||
|
|
||||||
| return file.violatingRanges(for: pattern).map { violationRange in | ||||||
| let substring = file.contents.substring(from: violationRange.location, length: violationRange.length) | ||||||
| let matchResult = patternRegex.firstMatch(in: substring, options: [], range: substring.fullNSRange)! | ||||||
| let violatingSubrange = matchResult.range(at: 1) | ||||||
| let characterOffset = violationRange.location + violatingSubrange.location + 1 | ||||||
| guard let lineContent = file.lines.first(where: { $0.index == line })?.content else { | ||||||
| return false | ||||||
| } | ||||||
|
|
||||||
| return StyleViolation( | ||||||
| ruleDescription: Self.description, | ||||||
| severity: configuration.severityConfiguration.severity, | ||||||
| location: Location(file: file, characterOffset: characterOffset) | ||||||
| let trimmedLine = lineContent.trimmingCharacters(in: .whitespaces) | ||||||
| let closingBraces: Set<Character> = ["]", "}", ")"] | ||||||
| return !trimmedLine.isEmpty && trimmedLine.allSatisfy { closingBraces.contains($0) } | ||||||
| } | ||||||
|
|
||||||
| private extension VerticalWhitespaceClosingBracesRule { | ||||||
| final class Visitor: ViolationsSyntaxVisitor<VerticalWhitespaceClosingBracesConfiguration> { | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| override func visitPost(_ node: TokenSyntax) { | ||||||
| guard node.isClosingBrace else { | ||||||
| return | ||||||
| } | ||||||
|
|
||||||
| let triviaAnalysis = analyzeTriviaForViolations( | ||||||
| trivia: node.leadingTrivia, | ||||||
| token: node, | ||||||
| position: node.position | ||||||
| ) | ||||||
|
|
||||||
| if let violation = triviaAnalysis { | ||||||
| violations.append( | ||||||
| ReasonedRuleViolation( | ||||||
| position: violation.position, | ||||||
| correction: .init( | ||||||
| start: violation.position, | ||||||
| end: violation.endPosition, | ||||||
| replacement: "" | ||||||
| ) | ||||||
| ) | ||||||
| ) | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| private func analyzeTriviaForViolations( | ||||||
| trivia: Trivia, | ||||||
| token: TokenSyntax, | ||||||
| position: AbsolutePosition | ||||||
| ) -> (position: AbsolutePosition, endPosition: AbsolutePosition)? { | ||||||
| let analysis = analyzeTrivia(trivia: trivia, startPosition: position) | ||||||
|
|
||||||
| guard let startPos = analysis.violationStartPosition, | ||||||
| let endPos = analysis.violationEndPosition, | ||||||
| analysis.consecutiveNewlines >= 2 else { | ||||||
| return nil | ||||||
| } | ||||||
|
|
||||||
| if configuration.onlyEnforceBeforeTrivialLines && | ||||||
| !isTokenLineTrivialHelper(for: token, file: file, locationConverter: locationConverter) { | ||||||
| return nil | ||||||
| } | ||||||
|
|
||||||
| return (position: startPos, endPosition: endPos) | ||||||
| } | ||||||
|
|
||||||
| private func analyzeTrivia( | ||||||
| trivia: Trivia, | ||||||
| startPosition: AbsolutePosition | ||||||
| ) -> TriviaAnalysis { | ||||||
| var result = TriviaAnalysis() | ||||||
| var currentPosition = startPosition | ||||||
|
|
||||||
| for piece in trivia { | ||||||
| let (newlines, positionAdvance) = processTriviaPiece( | ||||||
| piece: piece, | ||||||
| currentPosition: currentPosition, | ||||||
| consecutiveNewlines: result.consecutiveNewlines, | ||||||
| violationStartPosition: &result.violationStartPosition, | ||||||
| violationEndPosition: &result.violationEndPosition | ||||||
| ) | ||||||
| result.consecutiveNewlines = newlines | ||||||
| currentPosition = currentPosition.advanced(by: positionAdvance) | ||||||
| } | ||||||
|
|
||||||
| return result | ||||||
| } | ||||||
|
|
||||||
| private func processTriviaPiece( | ||||||
| piece: TriviaPiece, | ||||||
| currentPosition: AbsolutePosition, | ||||||
| consecutiveNewlines: Int, | ||||||
| violationStartPosition: inout AbsolutePosition?, | ||||||
| violationEndPosition: inout AbsolutePosition? | ||||||
| ) -> (newlines: Int, positionAdvance: Int) { | ||||||
| switch piece { | ||||||
| case .newlines(let count), .carriageReturns(let count): | ||||||
| var context = NewlineProcessingContext( | ||||||
| currentPosition: currentPosition, | ||||||
| consecutiveNewlines: consecutiveNewlines, | ||||||
| violationStartPosition: violationStartPosition, | ||||||
| violationEndPosition: violationEndPosition | ||||||
| ) | ||||||
| let result = processNewlines( | ||||||
| count: count, | ||||||
| bytesPerNewline: 1, | ||||||
| context: &context | ||||||
| ) | ||||||
| violationStartPosition = context.violationStartPosition | ||||||
| violationEndPosition = context.violationEndPosition | ||||||
| return result | ||||||
| case .carriageReturnLineFeeds(let count): | ||||||
| var context = NewlineProcessingContext( | ||||||
| currentPosition: currentPosition, | ||||||
| consecutiveNewlines: consecutiveNewlines, | ||||||
| violationStartPosition: violationStartPosition, | ||||||
| violationEndPosition: violationEndPosition | ||||||
| ) | ||||||
| let result = processNewlines( | ||||||
| count: count, | ||||||
| bytesPerNewline: 2, | ||||||
| context: &context | ||||||
| ) | ||||||
| violationStartPosition = context.violationStartPosition | ||||||
| violationEndPosition = context.violationEndPosition | ||||||
| return result | ||||||
| case .spaces, .tabs: | ||||||
| return (consecutiveNewlines, piece.sourceLength.utf8Length) | ||||||
| default: | ||||||
| // Any other trivia breaks the sequence | ||||||
| violationStartPosition = nil | ||||||
| violationEndPosition = nil | ||||||
| return (0, piece.sourceLength.utf8Length) | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| func correct(file: SwiftLintFile) -> Int { | ||||||
| let pattern = configuration.onlyEnforceBeforeTrivialLines ? self.trivialLinePattern : self.pattern | ||||||
| let violatingRanges = file.ruleEnabled(violatingRanges: file.violatingRanges(for: pattern), for: self) | ||||||
| guard violatingRanges.isNotEmpty else { | ||||||
| return 0 | ||||||
| private func processNewlines( | ||||||
| count: Int, | ||||||
| bytesPerNewline: Int, | ||||||
| context: inout NewlineProcessingContext | ||||||
| ) -> (newlines: Int, positionAdvance: Int) { | ||||||
| var newConsecutiveNewlines = context.consecutiveNewlines | ||||||
| var totalAdvance = 0 | ||||||
|
|
||||||
| for _ in 0..<count { | ||||||
| newConsecutiveNewlines += 1 | ||||||
| // violationStartPosition marks the beginning of the first newline | ||||||
| // that constitutes an empty line (i.e., the second in a sequence of \n\n). | ||||||
| if newConsecutiveNewlines == 2 && context.violationStartPosition == nil { | ||||||
| context.violationStartPosition = context.currentPosition.advanced(by: totalAdvance) | ||||||
| } | ||||||
| // violationEndPosition tracks the end of the last newline in any sequence of >= 2 newlines. | ||||||
| if newConsecutiveNewlines >= 2 { | ||||||
| context.violationEndPosition = context.currentPosition.advanced(by: totalAdvance + bytesPerNewline) | ||||||
| } | ||||||
| totalAdvance += bytesPerNewline | ||||||
| } | ||||||
|
|
||||||
| return (newConsecutiveNewlines, totalAdvance) | ||||||
| } | ||||||
| let patternRegex = regex(pattern) | ||||||
| var fileContents = file.contents | ||||||
| for violationRange in violatingRanges.reversed() { | ||||||
| fileContents = patternRegex.stringByReplacingMatches( | ||||||
| in: fileContents, | ||||||
| options: [], | ||||||
| range: violationRange, | ||||||
| withTemplate: "$2" | ||||||
| } | ||||||
|
|
||||||
| final class Rewriter: ViolationsSyntaxRewriter<VerticalWhitespaceClosingBracesConfiguration> { | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The rewriter is currently not used at all since the visitor does the replacement already and the rule doesn't specify |
||||||
| override func visit(_ token: TokenSyntax) -> TokenSyntax { | ||||||
| guard token.isClosingBrace else { | ||||||
| return super.visit(token) | ||||||
| } | ||||||
|
|
||||||
| let correctedTrivia = correctTrivia( | ||||||
| trivia: token.leadingTrivia, | ||||||
| token: token | ||||||
| ) | ||||||
|
|
||||||
| if correctedTrivia.hasCorrections { | ||||||
| numberOfCorrections += correctedTrivia.correctionCount | ||||||
| return super.visit(token.with(\.leadingTrivia, correctedTrivia.trivia)) | ||||||
| } | ||||||
|
|
||||||
| return super.visit(token) | ||||||
| } | ||||||
|
|
||||||
| private func correctTrivia( | ||||||
| trivia: Trivia, | ||||||
| token: TokenSyntax | ||||||
| ) -> (trivia: Trivia, hasCorrections: Bool, correctionCount: Int) { | ||||||
| // First check if we should apply corrections | ||||||
| if configuration.onlyEnforceBeforeTrivialLines && | ||||||
| !isTokenLineTrivialHelper(for: token, file: file, locationConverter: locationConverter) { | ||||||
| return (trivia: trivia, hasCorrections: false, correctionCount: 0) | ||||||
| } | ||||||
|
|
||||||
| var state = CorrectionState() | ||||||
|
|
||||||
| for piece in trivia { | ||||||
| processPieceForCorrection(piece: piece, state: &state) | ||||||
| } | ||||||
|
|
||||||
| // Add any remaining whitespace | ||||||
| state.result.append(contentsOf: state.pendingWhitespace) | ||||||
|
|
||||||
| return (trivia: Trivia(pieces: state.result), | ||||||
| hasCorrections: state.correctionCount > 0, | ||||||
| correctionCount: state.correctionCount) | ||||||
| } | ||||||
|
|
||||||
| private func processPieceForCorrection(piece: TriviaPiece, state: inout CorrectionState) { | ||||||
| switch piece { | ||||||
| case .newlines(let count), .carriageReturns(let count): | ||||||
| let newlineCreator = piece.isNewline ? TriviaPiece.newlines : TriviaPiece.carriageReturns | ||||||
| processNewlinesForCorrection( | ||||||
| count: count, | ||||||
| newlineCreator: { newlineCreator($0) }, | ||||||
| state: &state | ||||||
| ) | ||||||
| case .carriageReturnLineFeeds(let count): | ||||||
| processNewlinesForCorrection( | ||||||
| count: count, | ||||||
| newlineCreator: { TriviaPiece.carriageReturnLineFeeds($0) }, | ||||||
| state: &state | ||||||
| ) | ||||||
| case .spaces, .tabs: | ||||||
| // Only keep whitespace if we haven't seen a violation yet | ||||||
| if !state.hasViolation { | ||||||
| state.pendingWhitespace.append(piece) | ||||||
| } | ||||||
| default: | ||||||
| // Other trivia breaks the sequence | ||||||
| state.consecutiveNewlines = 0 | ||||||
| state.hasViolation = false | ||||||
| state.result.append(contentsOf: state.pendingWhitespace) | ||||||
| state.result.append(piece) | ||||||
| state.pendingWhitespace.removeAll() | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| private func processNewlinesForCorrection( | ||||||
| count: Int, | ||||||
| newlineCreator: (Int) -> TriviaPiece, | ||||||
| state: inout CorrectionState | ||||||
| ) { | ||||||
| for _ in 0..<count { | ||||||
| state.consecutiveNewlines += 1 | ||||||
| if state.consecutiveNewlines == 1 { | ||||||
| // First newline - always keep it with any preceding whitespace | ||||||
| state.result.append(contentsOf: state.pendingWhitespace) | ||||||
| state.result.append(newlineCreator(1)) | ||||||
| state.pendingWhitespace.removeAll() | ||||||
| } else { | ||||||
| // Additional newlines - these form empty lines and should be removed | ||||||
| state.hasViolation = true | ||||||
| state.correctionCount += 1 | ||||||
| state.pendingWhitespace.removeAll() | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
| file.write(fileContents) | ||||||
| return violatingRanges.count | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| private extension SwiftLintFile { | ||||||
| func violatingRanges(for pattern: String) -> [NSRange] { | ||||||
| match(pattern: pattern, excludingSyntaxKinds: SyntaxKind.commentAndStringKinds) | ||||||
| private extension TokenSyntax { | ||||||
| var isClosingBrace: Bool { | ||||||
| switch tokenKind { | ||||||
| case .rightBrace, .rightParen, .rightSquare: | ||||||
| return true | ||||||
| default: | ||||||
| return false | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| private extension TriviaPiece { | ||||||
| var isNewline: Bool { | ||||||
| switch self { | ||||||
| case .newlines, .carriageReturns, .carriageReturnLineFeeds: | ||||||
| return true | ||||||
| default: | ||||||
| return false | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What does the "helper" suffix stand for?