Skip to content
Open
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
1 change: 1 addition & 0 deletions Sources/SwiftRefactor/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ add_swift_syntax_library(SwiftRefactor
ExpandEditorPlaceholder.swift
FormatRawStringLiteral.swift
IntegerLiteralUtilities.swift
InvertIfCondition.swift
MigrateToNewIfLetSyntax.swift
OpaqueParameterToGeneric.swift
RefactoringProvider.swift
Expand Down
82 changes: 82 additions & 0 deletions Sources/SwiftRefactor/InvertIfCondition.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if compiler(>=6)
public import SwiftSyntax
#else
import SwiftSyntax
#endif

/// Inverts a negated `if` condition and swaps the branches.
///
/// ## Before
///
/// ```swift
/// if !x {
/// foo()
/// } else {
/// bar()
/// }
/// ```
///
/// ## After
///
/// ```swift
/// if x {
/// bar()
/// } else {
/// foo()
/// }
/// ```
public struct InvertIfCondition: SyntaxRefactoringProvider {
public static func refactor(syntax ifExpr: IfExprSyntax, in context: Void) -> IfExprSyntax {
guard let elseBody = ifExpr.elseBody, case .codeBlock(let elseBlock) = elseBody else {
return ifExpr
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there is nothing to refactor we should throw a RefactoringNotApplicableError. This will prevent the refactoring from showing up in SourceKit-LSP when it doesn’t apply.

}

guard ifExpr.conditions.count == 1, let condition = ifExpr.conditions.first else {
return ifExpr
}

guard case .expression(let expr) = condition.condition else {
return ifExpr
}

guard let prefixOpExpr = expr.as(PrefixOperatorExprSyntax.self), prefixOpExpr.operator.text == "!" else {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also support adding the ! if you want to invert an if expression that has a normal expression? The tricky part would likely be to decide whether parentheses need to be added around the expression for precedence rules. We can also do that in a follow-up PR.

return ifExpr
}

let innerExpr = prefixOpExpr.expression.with(\.leadingTrivia, prefixOpExpr.leadingTrivia.merging(triviaOf: prefixOpExpr.operator))

let newCondition = condition.with(\.condition, .expression(innerExpr))
let newConditions = ifExpr.conditions.with(\.[ifExpr.conditions.startIndex], newCondition)
Comment on lines +60 to +61
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let newCondition = condition.with(\.condition, .expression(innerExpr))
let newConditions = ifExpr.conditions.with(\.[ifExpr.conditions.startIndex], newCondition)
let newConditions = ifExpr.conditions.with(\.[ifExpr.conditions.startIndex].condition, .expression(innerExpr))


let oldBody = ifExpr.body
let oldElseBlock = elseBlock

let newBody =
oldElseBlock
.with(\.leadingTrivia, oldBody.leadingTrivia)
.with(\.trailingTrivia, oldBody.trailingTrivia)

let newElseBody =
oldBody
.with(\.leadingTrivia, oldElseBlock.leadingTrivia)
.with(\.trailingTrivia, oldElseBlock.trailingTrivia)

return
ifExpr
.with(\.conditions, newConditions)
.with(\.body, newBody)
.with(\.elseBody, .codeBlock(newElseBody))
}
}
162 changes: 162 additions & 0 deletions Tests/SwiftRefactorTest/InvertIfConditionTest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SwiftParser
import SwiftRefactor
import SwiftSyntax
import SwiftSyntaxBuilder
import XCTest
import _SwiftSyntaxTestSupport

final class InvertIfConditionTest: XCTestCase {
func testInvertIfCondition() throws {
let tests = [
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment about writing an assert function as in your other PR here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment still applies

(
"""
if !x {
foo()
} else {
bar()
}
""",
"""
if x {
bar()
} else {
foo()
}
"""
),
(
"""
if !(x == y) {
return
} else {
continue
}
""",
"""
if (x == y) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we strip the parentheses here since they are no longer necessary?

continue
} else {
return
}
"""
),
// Trivia preservation
(
"""
if /* comment */ !x {
a
} else {
b
}
""",
"""
if /* comment */ x {
b
} else {
a
}
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you also add a test that has comments in the bodies?

),
]

for (input, expected) in tests {
try assertInvertIfCondition(input, expected: expected)
}
}

func testInvertIfConditionFails() throws {
let tests = [
// Not negated
"""
if x {
a
} else {
b
}
""",
// No else
"""
if !x {
a
}
""",
// Else if (not a CodeBlock)
"""
if !x {
a
} else if y {
b
}
""",
// Multiple conditions
"""
if !x, !y {
a
} else {
b
}
""",
// Binding
"""
if let x = y {
a
} else {
b
}
""",
]

for input in tests {
try assertInvertIfCondition(input, expected: input)
}
}

private func assertInvertIfCondition(
_ input: String,
expected: String,
file: StaticString = #filePath,
line: UInt = #line
) throws {
let inputSyntax = try XCTUnwrap(
ExprSyntax.parse(from: input).as(IfExprSyntax.self),
"Failed validity check: \(input)",
file: file,
line: line
)
let expectedSyntax = try XCTUnwrap(
ExprSyntax.parse(from: expected),
"Failed validity check: \(expected)",
file: file,
line: line
)

try assertRefactor(
inputSyntax,
context: (),
provider: InvertIfCondition.self,
expected: expectedSyntax,
file: file,
line: line
)
}
}

// Private helper to avoid redeclaration conflicts
private extension ExprSyntax {
static func parse(from source: String) -> ExprSyntax {
var parser = Parser(source)
return ExprSyntax.parse(from: &parser)
}
}