Skip to content

Commit

Permalink
Remove tracking of correction positions
Browse files Browse the repository at this point in the history
  • Loading branch information
SimplyDanny committed Jan 13, 2025
1 parent f045130 commit d1ace5c
Show file tree
Hide file tree
Showing 77 changed files with 307 additions and 502 deletions.
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

#### Breaking

* None.
* Remove tracking of correction positions. Print the number of corrections made instead.
[SimplyDanny](https://github.com/SimplyDanny)

#### Experimental

Expand All @@ -24,7 +25,7 @@
[SimplyDanny](https://github.com/SimplyDanny)

* The artifact bundle name has changed. `SwiftLintBinary-macos.artifactbundle.zip` is now called
`SwiftLintBinary.artifactbundle.zip`. It now includes an AMD64 Linux binary.
`SwiftLintBinary.artifactbundle.zip`. It now includes an AMD64 Linux binary.
[Bradley Mackey](https://github.com/bradleymackey)
[#5514](https://github.com/realm/SwiftLint/issues/5514)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,9 @@ enum LegacyFunctionRuleHelper {
let funcName = node.calledExpression.as(DeclReferenceExprSyntax.self)?.baseName.text else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)

numberOfCorrections += 1
let trimmedArguments = node.arguments.map { $0.trimmingTrailingComma() }
let rewriteStrategy = legacyFunctions[funcName]

let expr: ExprSyntax
switch rewriteStrategy {
case .equal:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ private extension DuplicateImportsRule {
if itemsToRemove.isEmpty {
return super.visit(node)
}
correctionPositions.append(contentsOf: itemsToRemove.map(\.absolutePosition))

numberOfCorrections += itemsToRemove.count
var copy = node
for indexInParent in itemsToRemove.map(\.indexInParent).reversed() {
let currentIndex = copy.index(copy.startIndex, offsetBy: indexInParent)
Expand All @@ -187,7 +186,6 @@ private extension DuplicateImportsRule {
}
copy.remove(at: currentIndex)
}

return super.visit(copy)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ private extension ExplicitInitRule {
final class Rewriter: ViolationsSyntaxRewriter<ConfigurationType> {
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
guard let calledExpression = node.calledExpression.as(MemberAccessExprSyntax.self),
let violationPosition = calledExpression.explicitInitPosition,
calledExpression.explicitInitPosition != nil,
let calledBase = calledExpression.base else {
return super.visit(node)
}
correctionPositions.append(violationPosition)
numberOfCorrections += 1
let newNode = node.with(\.calledExpression, calledBase)
return super.visit(newNode)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ private extension JoinedDefaultParameterRule {

final class Rewriter: ViolationsSyntaxRewriter<ConfigurationType> {
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
guard let violationPosition = node.violationPosition else {
guard node.violationPosition != nil else {
return super.visit(node)
}
correctionPositions.append(violationPosition)
numberOfCorrections += 1
let newNode = node.with(\.arguments, [])
return super.visit(newNode)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ private extension LegacyConstantRule {
guard let correction = LegacyConstantRuleExamples.patterns[node.baseName.text] else {
return super.visit(node)
}
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
return ("\(raw: correction)" as ExprSyntax)
.with(\.leadingTrivia, node.leadingTrivia)
.with(\.trailingTrivia, node.trailingTrivia)
Expand All @@ -47,7 +47,7 @@ private extension LegacyConstantRule {
let calledExpression = node.calledExpression.as(DeclReferenceExprSyntax.self) else {
return super.visit(node)
}
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
return ("\(raw: calledExpression.baseName.text).pi" as ExprSyntax)
.with(\.leadingTrivia, node.leadingTrivia)
.with(\.trailingTrivia, node.trailingTrivia)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,7 @@ private extension LegacyConstructorRule {
let args = constructorsToArguments[identifier] else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)

numberOfCorrections += 1
let arguments = LabeledExprListSyntax(node.arguments.enumerated().map { index, elem in
elem
.with(\.label, .identifier(args[index]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,7 @@ private extension NimbleOperatorRule {
let expectedValueExpr = expectation.expectedValueExpr(for: predicate) else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)

numberOfCorrections += 1
let elements = ExprListSyntax([
expectation.baseExpr.with(\.trailingTrivia, .space),
operatorExpr.with(\.trailingTrivia, .space),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ private extension PreferKeyPathRule {
let calleeName = node.calleeName else {
return super.visit(node)
}
correctionPositions.append(closure.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
var node = node.with(\.calledExpression, node.calledExpression.with(\.trailingTrivia, []))
if node.leftParen == nil {
node = node.with(\.leftParen, .leftParenToken())
Expand All @@ -137,7 +137,7 @@ private extension PreferKeyPathRule {
if let expr = node.onlyExprStmt,
expr.accesses(identifier: node.onlyParameter) == true,
let replacement = expr.asKeyPath {
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
let node = replacement
.with(\.leadingTrivia, node.leadingTrivia)
.with(\.trailingTrivia, node.trailingTrivia)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,9 @@ private extension PreferTypeCheckingRule {
guard let asExpr = node.asExprWithOptionalTypeChecking else {
return super.visit(node)
}

correctionPositions.append(asExpr.asKeyword.positionAfterSkippingLeadingTrivia)

numberOfCorrections += 1
let expression = asExpr.expression.trimmed
let type = asExpr.type.trimmed

return ExprSyntax(stringLiteral: "\(expression) is \(type)")
.with(\.leadingTrivia, node.leadingTrivia)
.with(\.trailingTrivia, node.trailingTrivia)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,12 @@ private extension PreferZeroOverExplicitInitRule {
guard node.hasViolation, let name = node.name else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)

numberOfCorrections += 1
let newNode = MemberAccessExprSyntax(name: "zero")
.with(\.base, "\(raw: name)")
return super.visit(
newNode
.with(\.leadingTrivia, node.leadingTrivia)
.with(\.trailingTrivia, node.trailingTrivia)
)
.with(\.leadingTrivia, node.leadingTrivia)
.with(\.trailingTrivia, node.trailingTrivia)
return super.visit(newNode)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ private extension RedundantNilCoalescingRule {
else {
return super.visit(node)
}

numberOfCorrections += 1
let newNode = ExprListSyntax(node.dropLast(2)).with(\.trailingTrivia, [])
correctionPositions.append(secondToLastExpression.operator.positionAfterSkippingLeadingTrivia)
return super.visit(newNode)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,7 @@ private extension RedundantOptionalInitializationRule {
guard violations.isNotEmpty else {
return super.visit(node)
}

correctionPositions.append(contentsOf: violations.map(\.0))

numberOfCorrections += violations.count
let violatingBindings = violations.map(\.1)
let newBindings = PatternBindingListSyntax(node.bindings.map { binding in
guard violatingBindings.contains(binding) else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,25 +88,23 @@ private extension RedundantVoidReturnRule {
override func visit(_ node: ClosureSignatureSyntax) -> ClosureSignatureSyntax {
guard configuration.includeClosures,
let output = node.returnClause,
let tokenBeforeOutput = output.previousToken(viewMode: .sourceAccurate),
output.previousToken(viewMode: .sourceAccurate) != nil,
output.containsRedundantVoidViolation
else {
return super.visit(node)
}

correctionPositions.append(tokenBeforeOutput.endPositionBeforeTrailingTrivia)
numberOfCorrections += 1
return super.visit(node.with(\.returnClause, nil).removingTrailingSpaceIfNeeded())
}

override func visit(_ node: FunctionSignatureSyntax) -> FunctionSignatureSyntax {
guard let output = node.returnClause,
let tokenBeforeOutput = output.previousToken(viewMode: .sourceAccurate),
output.previousToken(viewMode: .sourceAccurate) != nil,
output.containsRedundantVoidViolation
else {
return super.visit(node)
}

correctionPositions.append(tokenBeforeOutput.endPositionBeforeTrailingTrivia)
numberOfCorrections += 1
return super.visit(node.with(\.returnClause, nil).removingTrailingSpaceIfNeeded())
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ private extension ReturnValueFromVoidFunctionRule {
Syntax(statements).enclosingFunction()?.returnsVoid == true else {
return super.visit(statements)
}
correctionPositions.append(returnStmt.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
let newStmtList = Array(statements.dropLast()) + [
CodeBlockItemSyntax(item: .expr(expr))
.with(\.leadingTrivia, returnStmt.leadingTrivia),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ private extension ShorthandOptionalBindingRule {
guard node.isShadowingOptionalBinding else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
let newNode = node
.with(\.initializer, nil)
.with(\.pattern, node.pattern.with(\.trailingTrivia, node.trailingTrivia))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,14 @@ struct SyntacticSugarRule: CorrectableRule, SourceKitFreeRule {
violations.flatMap { [$0] + flattenViolations($0.children) }
}

func correct(file: SwiftLintFile) -> [Correction] {
func correct(file: SwiftLintFile) -> Int {
let visitor = SyntacticSugarRuleVisitor(viewMode: .sourceAccurate)
return visitor.walk(file: file) { visitor in
var context = CorrectingContext(rule: self, file: file, contents: file.contents)
context.correctViolations(visitor.violations)

file.write(context.contents)

return context.corrections
}
return [context.numberOfCorrections]
}.reduce(0, +)
}
}

Expand Down Expand Up @@ -259,7 +257,7 @@ private struct CorrectingContext<R: Rule> {
let rule: R
let file: SwiftLintFile
var contents: String
var corrections: [Correction] = []
var numberOfCorrections = 0

mutating func correctViolations(_ violations: [SyntacticSugarRuleViolation]) {
let sortedVolations = violations.sorted(by: { $0.correction.typeStart > $1.correction.typeStart })
Expand Down Expand Up @@ -309,9 +307,7 @@ private struct CorrectingContext<R: Rule> {
correctViolations(violation.children)
replaceCharacters(in: leftRange, with: "")
}

let location = Location(file: file, byteOffset: ByteCount(correction.typeStart))
corrections.append(Correction(ruleDescription: type(of: rule).description, location: location))
numberOfCorrections += 1
}

private func typeIsOpaqueOrExistential(correction: SyntacticSugarRuleViolation.Correction) -> Bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private extension ToggleBoolRule {
guard node.hasToggleBoolViolation, let firstExpr = node.first, let index = node.index(of: firstExpr) else {
return super.visit(node)
}
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
let elements = node
.with(
\.[index],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ private extension TrailingSemicolonRule {
guard node.isTrailingSemicolon else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
return .unknown("").with(\.trailingTrivia, node.trailingTrivia)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,30 +95,24 @@ private extension UnneededBreakInSwitchRule {
guard let statement = node.unneededBreak else {
return
}

violations.append(statement.item.positionAfterSkippingLeadingTrivia)
}
}

final class Rewriter: ViolationsSyntaxRewriter<ConfigurationType> {
override func visit(_ node: SwitchCaseSyntax) -> SwitchCaseSyntax {
let stmts = CodeBlockItemListSyntax(node.statements.dropLast())

guard let breakStatement = node.unneededBreak, let secondLast = stmts.last else {
return super.visit(node)
}

correctionPositions.append(breakStatement.item.positionAfterSkippingLeadingTrivia)

numberOfCorrections += 1
let trivia = breakStatement.item.leadingTrivia + breakStatement.item.trailingTrivia

let newNode = node
.with(\.statements, stmts)
.with(\.statements.trailingTrivia, secondLast.item.trailingTrivia + trivia)
.trimmed { !$0.isComment }
.formatted()
.as(SwitchCaseSyntax.self)!

return super.visit(newNode)
}
}
Expand All @@ -131,7 +125,6 @@ private extension SwitchCaseSyntax {
breakStatement.label == nil else {
return nil
}

return statements.last
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ private extension UnneededSynthesizedInitializerRule {

override func visit(_ node: InitializerDeclSyntax) -> DeclSyntax {
if unneededInitializers.contains(node) {
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
let expr: DeclSyntax = ""
return expr
.with(\.leadingTrivia, node.leadingTrivia)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,7 @@ private extension UntypedErrorInCatchRule {
guard let item = node.catchItems.onlyElement, item.isIdentifierPattern else {
return super.visit(node)
}

correctionPositions.append(node.catchKeyword.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
return super.visit(
node
.with(\.catchKeyword, node.catchKeyword.with(\.trailingTrivia, .spaces(1)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ private extension LowerACLThanParentRule {
guard node.isHigherACLThanParent else {
return super.visit(node)
}

correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1
let newNode: DeclModifierSyntax
if node.name.tokenKind == .keyword(.open) {
newNode = DeclModifierSyntax(
Expand Down
4 changes: 1 addition & 3 deletions Source/SwiftLintBuiltInRules/Rules/Lint/MarkRule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ private extension MarkRule {
override func visit(_ token: TokenSyntax) -> TokenSyntax {
var pieces = token.leadingTrivia.pieces
for result in token.violationResults() {
// caution: `correctionPositions` records the positions before the mutations.
// https://github.com/realm/SwiftLint/pull/4297
correctionPositions.append(result.position)
numberOfCorrections += 1
result.correct(&pieces)
}
return super.visit(token.with(\.leadingTrivia, Trivia(pieces: pieces)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ private extension PrivateSwiftUIStatePropertyRule {
return DeclSyntax(node)
}

correctionPositions.append(node.bindingSpecifier.positionAfterSkippingLeadingTrivia)
numberOfCorrections += 1

// If there are no modifiers present on the current syntax node,
// then we should retain the binding specifier's leading trivia
Expand Down
Loading

0 comments on commit d1ace5c

Please sign in to comment.