Skip to content

Fix context-sensitive template crash for anonymous class args in assignments#7177

Merged
timtebeek merged 1 commit intomainfrom
tim/fix-visit-parent-cursor
Mar 27, 2026
Merged

Fix context-sensitive template crash for anonymous class args in assignments#7177
timtebeek merged 1 commit intomainfrom
tim/fix-visit-parent-cursor

Conversation

@timtebeek
Copy link
Copy Markdown
Member

Summary

  • Fixes IndexOutOfBoundsException in JavaTemplateParser.parseExpression() when a context-sensitive template replaces a method invocation inside an assignment, where the containing anonymous class is an argument to another method call (e.g., Preconditions.check())
  • The stub generator produced invalid Java (__M__.any(new Foo(){...};) — semicolon inside method argument) causing the parser to drop /*__TEMPLATE__*/ comment markers during error recovery
  • Conditionally omit the semicolon after anonymous class body when the parent is a MethodCall, consistent with the existing pattern used elsewhere in the same method
  • Also detect __TEMPLATE__ comment in JLeftPadded.before padding for assignment-context templates where the comment lands in the padding space rather than on a tree node prefix

Test plan

  • Added replaceContextSensitiveMethodInvocationInsideAssignment test reproducing the exact crash scenario
  • All existing JavaTemplateTest* tests pass
  • Full rewrite-java-test and rewrite-java test suites pass

…gnments

When a context-sensitive JavaTemplate targeted an expression inside an
anonymous class that was itself an argument to a method call (e.g.,
Preconditions.check()), the generated stub contained invalid Java: a
semicolon inside a method argument like `__M__.any(new Foo(){...};)`.
The parser's error recovery dropped the template comment markers,
causing listTemplatedTrees to return an empty list and crash with
IndexOutOfBoundsException.

Two fixes in BlockStatementTemplateGenerator:
- Don't append ';' after anonymous class body when parent is a MethodCall
- Detect __TEMPLATE__ comment in JLeftPadded.before padding for
  assignment-context templates
@timtebeek
Copy link
Copy Markdown
Member Author

Discussed on Slack with @greg-at-moderne : https://moderneinc.slack.com/archives/C02MMFD9DKJ/p1774613169108859?thread_ts=1774588052.282249&cid=C02MMFD9DKJ

Consensus was looks fine and likely fixes the issue we had seen in today's run.

@timtebeek timtebeek merged commit 26d259d into main Mar 27, 2026
1 check passed
@timtebeek timtebeek deleted the tim/fix-visit-parent-cursor branch March 27, 2026 19:12
@github-project-automation github-project-automation bot moved this from In Progress to Done in OpenRewrite Mar 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant