Skip to content

Add swap binary operands code action#2694

Open
somiljain2006 wants to merge 2 commits into
swiftlang:mainfrom
somiljain2006:code-action
Open

Add swap binary operands code action#2694
somiljain2006 wants to merge 2 commits into
swiftlang:mainfrom
somiljain2006:code-action

Conversation

@somiljain2006

Copy link
Copy Markdown
Contributor

Fixes #2520

Implement swap binary operands refactoring. Add a syntax-based code action that swaps the left and right operands of a binary expression when the cursor is positioned on the operator. Comparison operators are inverted as needed (for example, < becomes >), while commutative operators are preserved. Add tests covering nested expressions, operator selection, unsupported operators, and trivia preservation.

@somiljain2006

Copy link
Copy Markdown
Contributor Author

@ahoppen @rintaro Can you review this pr?

Comment thread Sources/SwiftSyntaxCodeActions/SwapBinaryOperands.swift Outdated
Comment thread Sources/SwiftSyntaxCodeActions/SwapBinaryOperands.swift Outdated
Comment thread Sources/SwiftSyntaxCodeActions/SwapBinaryOperands.swift Outdated
Comment thread Sources/SwiftSyntaxCodeActions/SwapBinaryOperands.swift Outdated
Comment thread Sources/SwiftSyntaxCodeActions/SwapBinaryOperands.swift Outdated

// Replace only the selected infix expression while leaving the
// surrounding folded expression tree unchanged.
let finalExpr = SwapRewriter(targetId: infixExpr.id, replacement: newInfix).visit(foldedExpr)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this needed? Can’t you just replace infixExpr instead of exprToFold below?

@somiljain2006 somiljain2006 Jun 19, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

infixExpr is part of the detached tree returned by foldAll(), so it cannot be used directly to determine the edit range in the source file. Therefore, rewrite the folded tree and replace the original exprToFold range with the updated expression.

Comment thread Tests/SourceKitLSPTests/CodeActionTests.swift
@somiljain2006 somiljain2006 requested a review from ahoppen June 19, 2026 20:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Flip operands of binary expression code action

2 participants