Add Inline temp variable code action
Summary
Implements the “Inline variable” refactor: replace a temporary let binding with its value at all usages in the same block and remove the declaration.
Example
Before:
func example() {
let basePrice = item.price
let total = basePrice * quantity
}
After:
func example() {
let total = item.price * quantity
}
Implementation
New: Sources/SwiftLanguageService/CodeActions/InlineTempVariable.swift SyntaxCodeActionProvider that: Finds a single let name = expr when the cursor is on the declaration or variable name. Collects all references to that name in the same CodeBlockSyntax (via a small SyntaxVisitor). Replaces each reference with the initializer; wraps in parentheses when needed for precedence
(e.g. 1 + 2 inlined into basePrice * 3 → (1 + 2) * 3).
Removes the declaration (whole CodeBlockItem). Registration: Added InlineTempVariable.self to allSyntaxCodeActions in SyntaxCodeActions.swift.
Tests:
Tests/SourceKitLSPTests/InlineTempVariableTests.swift — simple inline, precedence/parentheses, multiple usages, and no action when there are no usages.
Notes
Purely syntactic (no index/semantic info). Only offers the action when there is at least one reference in the same block. Parentheses use a composite-expression heuristic; full precedence via SwiftOperators can be a follow-up.
fixes: https://github.com/swiftlang/sourcekit-lsp/issues/2507
@rintaro can I keep working on this? Are we still adding this as a code action?
Yes, we think this code action provides functionality that is somewhat common, tedious and somewhat hard to get right, which qualifies it.
Hi @amanmaurya92,
https://github.com/swiftlang/sourcekit-lsp/pull/2754 picked this refactoring up after inactivity in this PR and is close to being merged. I would thus go with that PR’s implementation instead of this one. Sorry for the conflict here. I would encourage you to look for other issues labeled good first issue that don’t currently have an active PR associated with them if you want to contribute.
Thanks!
Ohh, Thanks @ahoppen for the closure.