Skip to content

Add Inline temp variable code action#2547

Closed
william-laverty wants to merge 1 commit intoswiftlang:mainfrom
william-laverty:inline-temp-variable-code-action
Closed

Add Inline temp variable code action#2547
william-laverty wants to merge 1 commit intoswiftlang:mainfrom
william-laverty:inline-temp-variable-code-action

Conversation

@william-laverty
Copy link
Copy Markdown

Description

Add a syntactic code action that inlines a temporary variable by replacing all references to it with its initializer expression, then removing the declaration.

Changes

  • New InlineTempVariable code action in Sources/SwiftLanguageService/CodeActions/
  • Registered in allSyntaxCodeActions
  • Tests for basic inlining, parenthesization of binary expressions, and non-offering for unused variables

Behavior

The action is offered when the cursor is on a let/var declaration that:

  • Has a single binding with an initializer
  • Has no type annotation
  • Is referenced in subsequent statements
  • Is not used as an inout argument or reassigned

Smart parenthesization wraps the inlined expression when it's a binary operation, ternary, try/await, or cast expression to preserve precedence.

Before:

let basePrice = item.price
let total = basePrice * quantity

After:

let total = item.price * quantity

Resolves #2507

Add a syntactic code action that inlines a temporary variable by
replacing all references to it with its initializer expression, then
removing the declaration.

The action is offered when the cursor is on a let/var declaration with
a single binding that has an initializer, no type annotation, and the
variable is referenced in subsequent statements.

Smart parenthesization is applied when the initializer is a binary
expression, ternary, try/await, or cast to avoid changing precedence.

The action is not offered when the variable is unused, used as an
inout argument, or is reassigned.

Resolves #2507
@ahoppen
Copy link
Copy Markdown
Member

ahoppen commented Mar 8, 2026

@william-laverty I appreciate your enthusiasm but you now have 7 open PRs. I would encourage you to leave it at that for now so that you have the time and energy to address review feedback on those.

@ahoppen
Copy link
Copy Markdown
Member

ahoppen commented Mar 8, 2026

Here, again, we already have a PR that implements this. #2529

@ahoppen ahoppen closed this Mar 8, 2026
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 Inline temp variable code action

2 participants