Java intention: Quick fix for error "foreach not applicable to type java.util.Iterator" (IDEA-124751)

This commit is contained in:
Pavel Dolgov
2016-07-01 16:12:36 +03:00
parent 57b55ceeb6
commit d50a5c7a07
19 changed files with 302 additions and 2 deletions
@@ -274,4 +274,6 @@ public abstract class QuickFixFactory {
public IntentionAction createWrapWithOptionalFix(@Nullable PsiType type, @NotNull PsiExpression expression) {
throw new UnsupportedOperationException();
}
public abstract IntentionAction createNotIterableForEachLoopFix(PsiExpression expression);
}
@@ -753,7 +753,9 @@ public class GenericsHighlightUtil {
if (itemType == null) {
String description = JavaErrorMessages.message("foreach.not.applicable",
JavaHighlightUtil.formatType(expression.getType()));
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
final HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createNotIterableForEachLoopFix(expression));
return highlightInfo;
}
return null;
}
@@ -626,4 +626,9 @@ public class EmptyQuickFixFactory extends QuickFixFactory {
public IntentionAction createWrapWithOptionalFix(@Nullable PsiType type, @NotNull PsiExpression expression) {
return QuickFixes.EMPTY_FIX;
}
@Override
public IntentionAction createNotIterableForEachLoopFix(PsiExpression expression) {
return QuickFixes.EMPTY_FIX;
}
}
@@ -0,0 +1,126 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
/**
* @author Pavel.Dolgov
*/
public class ReplaceIteratorForEachLoopWithIteratorForLoopFix implements IntentionAction {
private final PsiForeachStatement myStatement;
public ReplaceIteratorForEachLoopWithIteratorForLoopFix(@NotNull PsiForeachStatement statement) {
myStatement = statement;
}
@Nls
@NotNull
@Override
public String getText() {
return "Replace 'for each' loop with iterator 'for' loop";
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return getText();
}
@Override
public boolean startInWriteAction() {
return true;
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return myStatement.isValid() && myStatement.getManager().isInProject(myStatement);
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;
final PsiExpression iteratedValue = myStatement.getIteratedValue();
if (iteratedValue == null) {
return;
}
final PsiType iteratedValueType = iteratedValue.getType();
if (iteratedValueType == null) {
return;
}
final PsiParameter iterationParameter = myStatement.getIterationParameter();
final String iterationParameterName = iterationParameter.getName();
if (iterationParameterName == null) {
return;
}
final PsiStatement forEachBody = myStatement.getBody();
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
final JavaCodeStyleManager javaStyleManager = JavaCodeStyleManager.getInstance(project);
final String name = javaStyleManager.suggestUniqueVariableName("it", myStatement, true);
PsiForStatement newForLoop = (PsiForStatement)elementFactory.createStatementFromText(
"for (Iterator " + name + " = initializer; " + name + ".hasNext();) { Object next = " + name + ".next(); }", myStatement);
final PsiDeclarationStatement newDeclaration = (PsiDeclarationStatement)newForLoop.getInitialization();
if (newDeclaration == null) return;
final PsiLocalVariable newIteratorVariable = (PsiLocalVariable)newDeclaration.getDeclaredElements()[0];
final PsiTypeElement newIteratorTypeElement = elementFactory.createTypeElement(iteratedValueType);
newIteratorVariable.getTypeElement().replace(newIteratorTypeElement);
newIteratorVariable.setInitializer(iteratedValue);
final PsiBlockStatement newBody = (PsiBlockStatement)newForLoop.getBody();
if (newBody == null) return;
final PsiCodeBlock newBodyBlock = newBody.getCodeBlock();
final PsiDeclarationStatement newFirstStatement = (PsiDeclarationStatement)newBodyBlock.getStatements()[0];
final PsiLocalVariable newItemVariable = (PsiLocalVariable)newFirstStatement.getDeclaredElements()[0];
final PsiTypeElement newItemTypeElement = elementFactory.createTypeElement(iterationParameter.getType());
newItemVariable.getTypeElement().replace(newItemTypeElement);
newItemVariable.setName(iterationParameterName);
final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
final PsiModifierList modifierList = newItemVariable.getModifierList();
if (modifierList != null) modifierList.setModifierProperty(PsiModifier.FINAL, true);
}
final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
newForLoop = (PsiForStatement)javaStyleManager.shortenClassReferences(newForLoop);
newForLoop = (PsiForStatement)styleManager.reformat(newForLoop);
if (forEachBody instanceof PsiBlockStatement) {
final PsiStatement[] statements = ((PsiBlockStatement)forEachBody).getCodeBlock().getStatements();
for (int i = statements.length - 1; i >= 0; i--) {
newBodyBlock.addAfter(statements[i], newFirstStatement);
}
}
else if (forEachBody != null && !(forEachBody instanceof PsiEmptyStatement)) {
newBodyBlock.addAfter(forEachBody, newFirstStatement);
}
myStatement.replace(newForLoop);
}
}
@@ -52,11 +52,11 @@ import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.ClassKind;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PropertyMemberType;
import com.intellij.refactoring.changeSignature.ChangeSignatureGestureDetector;
import com.intellij.util.DocumentUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -778,6 +778,18 @@ public class QuickFixFactoryImpl extends QuickFixFactory {
return WrapObjectWithOptionalOfNullableFix.createFix(type, expression);
}
@Override
public IntentionAction createNotIterableForEachLoopFix(PsiExpression expression) {
final PsiElement parent = expression.getParent();
if (parent instanceof PsiForeachStatement) {
final PsiType type = expression.getType();
if (InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_ITERATOR)) {
return new ReplaceIteratorForEachLoopWithIteratorForLoopFix((PsiForeachStatement)parent);
}
}
return null;
}
private static boolean timeToOptimizeImports(@NotNull PsiFile file) {
if (!CodeInsightSettings.getInstance().OPTIMIZE_IMPORTS_ON_THE_FLY) return false;
@@ -0,0 +1,12 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class CodeBlockBody {
void foo(Iterator<Integer> it,Iterator<Integer> it1) {
for (Iterator<Integer> it2 = it1; it2.hasNext(); ) {
Integer integer = it2.next();
System.out.println(integer + " a");
System.out.println(integer + " b");
}
}
}
@@ -0,0 +1,10 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class EmptyBody {
void foo(Iterator<Integer> it) {
for (Iterator<Integer> it1 = it; it1.hasNext(); ) {
Integer integer = it1.next();
}
}
}
@@ -0,0 +1,11 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class IncompatibleItemType {
void foo(Iterator<Integer> it) {
for (Iterator<Integer> it1 = it; it1.hasNext(); ) {
String string = it1.next();
System.out.println(string);
}
}
}
@@ -0,0 +1,10 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class MissingBody {
void foo(Iterator<Integer> it1) {
for (Iterator<Integer> it = it1; it.hasNext(); ) {
Integer integer = it.next();
}
}
}
@@ -0,0 +1,11 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class OneStatementBody {
void foo(Iterator<Integer> it) {
for (Iterator<Integer> it1 = it; it1.hasNext(); ) {
Integer integer = it1.next();
System.out.println(integer);
}
}
}
@@ -0,0 +1,11 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class PrimitiveItem {
void foo(Iterator<Integer> it) {
for (Iterator<Integer> it1 = it; it1.hasNext(); ) {
int i = it1.next();
System.out.println(i);
}
}
}
@@ -0,0 +1,11 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class CodeBlockBody {
void foo(Iterator<Integer> it,Iterator<Integer> it1) {
for (Integer integer : <caret>it1) {
System.out.println(integer + " a");
System.out.println(integer + " b");
}
}
}
@@ -0,0 +1,8 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class EmptyBody {
void foo(Iterator<Integer> it) {
for (Integer integer : <caret>it) ;
}
}
@@ -0,0 +1,8 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class IncompatibleItemType {
void foo(Iterator<Integer> it) {
for (String string : <caret>it) System.out.println(string);
}
}
@@ -0,0 +1,8 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class MissingBody {
void foo(Iterator<Integer> it1) {
for (Integer integer : <caret>it1)
}
}
@@ -0,0 +1,8 @@
// "Replace 'for each' loop with iterator 'for' loop" "false"
import java.lang.ref.Reference;
public class NotIterator {
void foo(Reference<String> it) {
for (String string : <caret>it) System.out.println(string);
}
}
@@ -0,0 +1,8 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class OneStatementBody {
void foo(Iterator<Integer> it) {
for (Integer integer : <caret>it) System.out.println(integer);
}
}
@@ -0,0 +1,8 @@
// "Replace 'for each' loop with iterator 'for' loop" "true"
import java.util.Iterator;
public class PrimitiveItem {
void foo(Iterator<Integer> it) {
for (int i : <caret>it) System.out.println(i);
}
}
@@ -0,0 +1,29 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.quickFix;
/**
* @author Pavel.Dolgov
*/
public class ReplaceIteratorForEachLoopWithIteratorForLoopFixTest extends LightQuickFixParameterizedTestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/replaceIteratorForEachWithFor";
}
}