Skip to content

Commit

Permalink
Prevent SuggestedFixes#renameMethod from modifying return type decl…
Browse files Browse the repository at this point in the history
…aration

By ensuring the return type `IDENTIFIER` token is not matched.

Fixes #4043

COPYBARA_INTEGRATE_REVIEW=#4043 from PicnicSupermarket:gdejong/bug-method-name cbfbc54
PiperOrigin-RevId: 555523619
  • Loading branch information
oxkitsune authored and Error Prone Team committed Aug 10, 2023
1 parent 44b6552 commit b58dd1e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -745,11 +745,12 @@ public Void visitMemberSelect(MemberSelectTree tree, Void unused) {

/** Be warned, only changes method name at the declaration. */
public static SuggestedFix renameMethod(MethodTree tree, String replacement, VisitorState state) {
// Search tokens from beginning of method tree to beginning of method body.
int basePos = getStartPosition(tree);
// Search tokens from end of return type tree to beginning of method body.
int basePos = state.getEndPosition(tree.getReturnType());
int endPos =
tree.getBody() != null ? getStartPosition(tree.getBody()) : state.getEndPosition(tree);
List<ErrorProneToken> methodTokens = state.getOffsetTokens(basePos, endPos);

for (ErrorProneToken token : methodTokens) {
if (token.kind() == TokenKind.IDENTIFIER && token.name().equals(tree.getName())) {
return SuggestedFix.replace(token.pos(), token.endPos(), replacement);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,4 +463,32 @@ public void methodReference() {
"}")
.doTest();
}

@Test
public void methodNameWithMatchingReturnType() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" private Object Object() {",
" return null;",
" }",
"",
" void call() {",
" Object();",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" private Object object() {",
" return null;",
" }",
"",
" void call() {",
" object();",
" }",
"}")
.doTest();
}
}

0 comments on commit b58dd1e

Please sign in to comment.