Add Collapse Nested If refactoring#2475
Add Collapse Nested If refactoring#2475Viditgupta-official wants to merge 1 commit intoswiftlang:mainfrom
Conversation
|
swiftlang/swift-syntax#3260 already started implementing this in the swift-syntax repository and was opened earlier. Sorry for the race here but we’ll continue wit that PR for now. |
|
Thanks for clarifying. I’ll admit I was a bit surprised since the issue had been allocated to me earlier, but I understand wanting to avoid parallel implementations. I’ll take a look at the swift-syntax PR and see if there’s a way I can still contribute or help move things forward there. Appreciate the context. |
|
Yeah, sorry. Sometimes it’s hard to balance people expressing interest in fixing an issue but then never opening a PR with the PRs that are already open. We’re trying to be as fair as possible but sometimes races like these just happen. Just want to say for your contribution anyway, even if it wasn’t merged. |
Description
This PR adds a new syntactic refactoring code action “Collapse Nested If Statements” to SwiftLanguageService.
The refactoring detects cases where an if statement contains exactly one statement in its body and that statement is another if (with no else on either), and collapses them into a single if with combined conditions.
Example
Before:
if a {
if b {
doSomething()
}
}
After:
if a && b {
doSomething()
}
Implementation notes
Implemented as a SyntaxRefactoringCodeActionProvider
The refactoring:
Requires both outer and inner if to have no else
Requires the outer if body to contain exactly one statement
Reuses the inner if body and combines condition lists
The action is registered alongside other syntactic refactorings in SyntaxCodeActions.swift
Known limitation / feedback request
At the moment, the code action reliably appears when the cursor is on the if keyword itself, but does not always appear when the cursor is inside the condition, on identifiers, operators, or whitespace within the same if expression.
The current implementation walks upward from innermostNodeContainingRange, but there may be a more idiomatic or preferred approach in SourceKit-LSP to make refactorings robust to cursor position within the full if expression.
I’d appreciate feedback on:
Whether this cursor-position behavior is acceptable for an initial implementation
Or if there is a recommended pattern to broaden applicability across the entire if expression range
Status
Builds successfully
Refactoring behavior works as expected when triggered
Happy to iterate based on maintainer feedback
Fixes
Addresses one part of #2424 (CollapseNestedIfStmt).