Repository navigation
Resolve names and reachability with rewrite's Scope API - #1269
Merged
knutwannheden merged 28 commits intoNov 19, 2026
Merged
Conversation
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.
…nalysis-onto-rewrite-scope-api
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.
…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
deleted the
move-rewrite-static-analysis-onto-rewrite-scope-api
branch
November 19, 2026 14:44
This was referenced Nov 19, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
RunnablecallinghashCode()into() -> hashCode(), which calls the enclosing object's method.ignoredbeside a localignoredfrom an earlier switch case.foo_nralone because a setter parameter was already calledfooNr(RenamePrivateFieldsToCamelCasemisses cases when method parameters with target name exist #186).This moves those recipes onto the
Scopetrait andScopeServicefrom openrewrite/rewrite#10032, which resolve a name as the compiler does. Instead of collecting names, a recipe asks:Output that no longer breaks
hashCode(), recurses, calls a default method orsuper, reads the field it initializes, or redeclares a pattern variableignoredbeside a case localignoredignored1int x = 2; int x = 3;int x = 2; x = 3;break;after asynchronizedblock that returnsbreakThis covers the cases of #979 and items B8 and part of C5 in #1116.
What name matching stopped the recipes from doing
tryorif-elsethat returns or throws on every path.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 askScopeonly 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
Scope, so they stay as they are. RemoveInstanceOfPatternMatch could not be judged on guava, which has noinstanceofpatterns.ScopeService.completesNormallydoes not yet count acontinueas a way out of ado-while.RemoveUnreachableCodeVisitor.completesNormallycovers that until it does.Each change comes with a test that failed before it. The lazy
Scopechecks, thedo-whileguard and UnwrapElseAfterReturn's return-or-throw rule were also mutation-checked.RenamePrivateFieldsToCamelCasemisses cases when method parameters with target name exist #186