sourcekit-lsp icon indicating copy to clipboard operation
sourcekit-lsp copied to clipboard

Add Inline temp variable code action

Open amanmaurya92 opened this issue 9 months ago • 2 comments

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

amanmaurya92 avatar Mar 02 '26 14:03 amanmaurya92

@rintaro can I keep working on this? Are we still adding this as a code action?

amanmaurya92 avatar Mar 13 '26 07:03 amanmaurya92

Yes, we think this code action provides functionality that is somewhat common, tedious and somewhat hard to get right, which qualifies it.

ahoppen avatar Mar 15 '26 12:03 ahoppen

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!

ahoppen avatar Sep 03 '26 08:09 ahoppen

Ohh, Thanks @ahoppen for the closure.

amanmaurya92 avatar Sep 03 '26 09:09 amanmaurya92