Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ForEachIterable error when calling iterator method without 'this' #2260

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -172,14 +172,15 @@ private Description match(
if (elementType.hasTag(TypeTag.WILDCARD)) {
elementType = getUpperBound(elementType, state.getTypes());
}
Tree iterableExprNode = getReceiver(tree.getInitializer());
String iterableExpr =
iterableExprNode != null ? state.getSourceForNode(iterableExprNode) : "this";
fix.replace(
startPosition,
getStartPosition(body),
String.format(
"for (%s %s : %s) ",
SuggestedFixes.prettyType(state, fix, elementType),
replacement,
state.getSourceForNode(getReceiver(tree.getInitializer()))));
SuggestedFixes.prettyType(state, fix, elementType), replacement, iterableExpr));
return describeMatch(tree, fix.build());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,42 @@ public void wildcardExtends() {
.doTest();
}

@Test
public void iteratorMemberMethod() {
BugCheckerRefactoringTestHelper.newInstance(new ForEachIterable(), getClass())
.addInputLines(
"in/Test.java",
"import java.util.Iterator;",
"import java.lang.Iterable;",
"class Test<V> implements Iterable<V> {",
" @Override",
" public Iterator<V> iterator() {",
" return null;",
" }",
" void test() {",
" Iterator<V> iter = iterator();",
" while (iter.hasNext()) {",
" iter.next();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.Iterator;",
"import java.lang.Iterable;",
"class Test<V> implements Iterable<V> {",
" @Override",
" public Iterator<V> iterator() {",
" return null;",
" }",
" void test() {",
" for (V element : this) {",
" }",
" }",
"}")
.doTest();
}

@Test
public void negative() {
CompilationTestHelper.newInstance(ForEachIterable.class, getClass())
Expand Down