Skip to content

Resolve names and reachability with rewrite's Scope API - #1269

Merged
knutwannheden merged 28 commits into
mainfrom
move-rewrite-static-analysis-onto-rewrite-scope-api
Nov 19, 2026
Merged

knutwannheden merged 28 commits into
mainfrom
move-rewrite-static-analysis-onto-rewrite-scope-api

Conversation

@knutwannheden

@knutwannheden knutwannheden commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Several recipes decided by simple name which variable an identifier meant. When two variables shared a name, the result did not compile or meant something else, and where a recipe erred the safe way, it skipped work:

This moves those recipes onto the Scope trait and ScopeService from openrewrite/rewrite#10032, which resolve a name as the compiler does. Instead of collecting names, a recipe asks:

Scope.at(cursor).freeName("ignored", n -> false)            // a name nothing in reach uses
Scope.bindingOf(cursor, variable).map(Binding::references)   // the identifiers that refer to this variable
service(ScopeService.class).completesNormally(statement)     // JLS 14.22 reachability

Output that no longer breaks

Recipe Before After
UseLambdaForFunctionalInterface converted a class whose body calls hashCode(), recurses, calls a default method or super, reads the field it initializes, or redeclares a pattern variable keeps it
UnwrapElseAfterReturn, RemoveUnneededBlock, NoDoubleBraceInitialization moved declarations next to others of the same name, or in front of a read they then captured keeps the block
RenameExceptionInEmptyCatch ignored beside a case local ignored ignored1
MinimumSwitchCases int x = 2; int x = 3; int x = 2; x = 3;
FallThrough break; after a synchronized block that returns no break
SimplifyConstantIfBranchExecution statements left after an unwrapped branch that cannot complete removed
InstanceOfPatternMatch a pattern variable named like a later local, or a deleted local still read names clear of both

This covers the cases of #979 and items B8 and part of C5 in #1116.

What name matching stopped the recipes from doing

  • RemoveUnusedLocalVariables and InlineVariable tell a local from another of its name in a sibling block.
  • FinalizeLocalVariables and FinalizeMethodArguments no longer count a write to a nested class's field of the same name.
  • The two camel-case renamers rename when the new name is used only out of reach.
  • UnwrapElseAfterReturn unwraps after a try or if-else that returns or throws on every path.
  • InstanceOfPatternMatch replaces casts after a negated check that returns.

Over guava (1,505 files, parsed with types) the output changed at 45 sites, and each was read: 31 in InstanceOfPatternMatch, 7 in FinalizeLocalVariables, 3 each in UseLambdaForFunctionalInterface and UnwrapElseAfterReturn, 1 in RenameLocalVariablesToCamelCase.

Cost

Binding.references() resolves every name in a scope, which made FinalizeMethodArguments and RemoveUnusedLocalVariables over half again as slow. They now ask Scope only where name matching cannot tell variables apart, with identical output.

The 18 recipes this touches take 20.3 s on guava against 19.9 s before, as the median of 8 warm runs. Only RenameExceptionInEmptyCatch moved beyond run-to-run noise, and got 44% faster.

Not changed here

  • UseTryWithResources and UseMapEntrySetIteration gave the same guava output with Scope, so they stay as they are. RemoveInstanceOfPatternMatch could not be judged on guava, which has no instanceof patterns.
  • ScopeService.completesNormally does not yet count a continue as a way out of a do-while. RemoveUnreachableCodeVisitor.completesNormally covers that until it does.

Each change comes with a test that failed before it. The lazy Scope checks, the do-while guard and UnwrapElseAfterReturn's return-or-throw rule were also mutation-checked.

Moving an else body into the enclosing block widens the scope of what it
declares. A later declaration of the same name then made the block fail
to compile, and a later read of a field of that name silently read the
local. The else is kept where a later statement declares or reads one of
those names, as Scope resolves them.
A block was kept only where it declared a variable at its top level, so a
pattern variable or a local class declared in it was flattened into the
enclosing block next to a later declaration of the same name.
Scope.collidesAcross now decides, and UnwrapElseAfterReturn uses it for
the same question.
The recipe kept its own map of names per scope, built from every
identifier it had visited. A local declared in an earlier colon-style
case was in a sibling scope there, so `ignored` was chosen again and
redeclared it. The name now comes from Scope.freeName.
…ollide

The initializer block's statements were spliced into the method body
after the declaration, so a local they declare met a later local of the
same name. The initializer is kept where Scope.collidesAcross finds such
a name among the later statements.
…ariable

The shadowing check collected the enclosing method's parameters and the
variables declared in blocks on the path, which leaves out a pattern
variable, so an anonymous class redeclaring one became a lambda that does
not compile. The check now looks each name the class body declares up
through Scope.
A local declared in the first case and assigned in the default case was
redeclared at every top-level assignment there, so `x = 2; x = 3;` became
two declarations of `x`.
References were matched by attributed variable, which is the same for two
locals of one name and type in one method. An unused local was kept where
a local of its name in another block is read. The references are now
narrowed to those Scope resolves to the declaration.
A local of the same name and type in a nested block counted as a use of
the inlined variable, so its declaration was left behind, and one in a
finally block counted as a read of a variable declared inside the try,
so nothing was inlined. Both checks now go by the declaration Scope
resolves the variable to.
…ely final

VariableReferences.isEffectivelyFinal matched writes by name, so an
assignment to a same-named field of a nested class counted against a
local. The writes are now narrowed to those Scope resolves to the
declaration, and FinalizeLocalVariables finalizes such a local.
Recipes that leave a returning block behind rely on it being flattened,
so that the unreachable statements after it are removed. The collision
check is skipped for such a block, as the declaration check already is.
…d elsewhere

A field was left alone when any variable in the file had the new name, or
the old one, which a setter parameter usually does (#186). The rename now
goes ahead where Scope.Binding.canRenameTo finds that no name would come
to read something else.
…e elsewhere

A local was left alone when any variable of its method had the new name,
even one in another block. The rename now goes ahead where
Scope.Binding.canRenameTo finds no name would come to read something
else, and nothing of the new name is visible at the declaration.
The recipe worked out for itself where a pattern variable would be in
scope, and gave up on a negated check. It now asks
ScopeService.isMatchedAt for each cast, which also replaces a cast in the
else branch of a negated check.
A check such as `if (!(o instanceof String)) return;` holds for the rest
of its block. Where ScopeService.isMatchedAt says so, the block is
rewritten as a whole, so casts in the statements after the check use the
pattern variable too.
… other names

An anonymous class was converted although its method called or read, by
bare name, something the class itself provides: an Object method, its own
method, a default method or a constant of the interface. In a lambda that
name is out of scope or belongs to the enclosing class. A body using
`super`, and a field initializer whose class reads that field, are kept
too.
The recipe decided for itself whether a case's last statement leaves the
switch. It took a `synchronized` block that returns to complete, and added
a `break;` after it that does not compile as unreachable. It also read
only the then branch of an if-else, and took every colon-style switch to
leave, so it missed a case that falls through when the else branch or the
inner switch completes. ScopeService.completesNormally answers all three.
Binding.references() resolves every name in the variable's scope, which
made FinalizeMethodArguments and RemoveUnusedLocalVariables over half
again as slow on guava. isEffectivelyFinal asks it only when the name is
written in the scope. RemoveUnusedLocalVariables asks it only when the
region declares another variable of the name, the one case SemanticallyEqual
cannot tell apart, since it compares owner, name and type. Over guava the
output is unchanged, and each recipe is within 6% of its time before Scope.
…nnot complete

Unwrapping `if (true)` makes the statements after it unreachable when the
branch cannot complete normally. Only a literal return, throw, break or
continue counted, so after a branch ending in an if-else or a synchronized
block that returns, the statements stayed and the result did not compile.
ScopeService.completesNormally answers for any statement.

Three tests looped on `while (true)` without a break, so the statement
after the loop was already unreachable in their input. They loop on a
parameter instead.
…rn or throw

A then part counted as leaving only when it was, or ended with, a return
or throw. A try whose body and catch both return, or an if-else that
returns from both branches, kept its else. ScopeService.completesNormally
recognises those. A then part that a break or continue can leave still
keeps its else, as the recipe covers return and throw. Over guava this
unwraps three more else blocks.
ScopeService.completesNormally takes a do-while that only a continue
leaves to never finish, though JLS 14.22 lets it complete. So
SimplifyConstantIfBranchExecution deleted the reachable statement after
such a loop, UnwrapElseAfterReturn moved an else body out behind it, and
FallThrough added no break after it. Until the scope service counts the
continue, a statement holding a continue inside a do-while is taken to
complete. The three recipes also take the scope service their visitor
keeps for the source file.
… its check

A pattern variable that stays in scope to the end of the block, after a
check that leaves, could take the name of a local declared later in that
block. It now avoids every name the block declares or reads. A check
outside an if, such as a while condition, deleted the local initialized
from the cast but gave the pattern variable another name, leaving the
local's reads dangling. The pattern variable now takes the local's name
whatever holds the check.
…a variable in scope

The initializer's statements move into the method body, where a local
they declare meets a parameter or local of the same name that the
anonymous class was allowed to shadow.
…zer that reads its field

A lambda anywhere in a field's initializer may not name the field, unless
another class body lies between them. Only parentheses and casts were
looked through, so a class passed as an argument in the initializer was
converted, and the result did not compile.
InlineVariable and RemoveUnusedLocalVariables each kept a copy of the
same helper for the writes VariableReferences.findLhsReferences finds.
@knutwannheden knutwannheden self-assigned this Nov 19, 2026
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Nov 19, 2026
…letes

ScopeService.completesNormally counts a continue that leaves a do-while
since openrewrite/rewrite#10060, so the workaround for it goes. A test
pins InstanceOfPatternMatch too, which the same gap made use a pattern
variable after an if whose do-while could finish.
@knutwannheden
knutwannheden merged commit c48d35a into main Nov 19, 2026
1 check passed
@knutwannheden
knutwannheden deleted the move-rewrite-static-analysis-onto-rewrite-scope-api branch November 19, 2026 14:44
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

RenamePrivateFieldsToCamelCase misses cases when method parameters with target name exist

1 participant