[java-intentions] Support type inference when suggesting to insert `return` (IJ-CR...
authorTagir Valeev <Tagir.Valeev@jetbrains.com>
Tue, 11 May 2021 10:07:50 +0000 (17:07 +0700)
committerintellij-monorepo-bot <intellij-monorepo-bot-no-reply@jetbrains.com>
Tue, 11 May 2021 12:00:19 +0000 (12:00 +0000)
GitOrigin-RevId: 0203d3a738d59d12c711ff8589f4293ec2bbf89f

java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightFixUtil.java
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/insertReturn/afterGeneric.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/insertReturn/beforeGeneric.java [new file with mode: 0644]

index ae9dec7245d857457a50762636bb103ec5f0b7ea..94c0863503fbd554f3e2763524a774b5d90c06e6 100644 (file)
@@ -418,10 +418,19 @@ public final class HighlightFixUtil {
       PsiElement blockParent = block.getParent();
       if (blockParent instanceof PsiMethod) {
         PsiType returnType = ((PsiMethod)blockParent).getReturnType();
-        if (returnType != null && returnType.isAssignableFrom(type)) {
+        if (returnType != null && isPossibleReturnValue(expression, type, returnType)) {
           QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createInsertReturnFix(expression));
         }
       }
     }
   }
+
+  private static boolean isPossibleReturnValue(PsiExpression expression, PsiType type, PsiType returnType) {
+    if (returnType.isAssignableFrom(type)) return true;
+    if (!(type instanceof PsiClassType) || !(returnType instanceof PsiClassType)) return false;
+    if (!returnType.isAssignableFrom(TypeConversionUtil.erasure(type))) return false;
+    PsiExpression copy = (PsiExpression)LambdaUtil.copyWithExpectedType(expression, returnType);
+    PsiType copyType = copy.getType();
+    return copyType != null && returnType.isAssignableFrom(copyType);
+  }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/insertReturn/afterGeneric.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/insertReturn/afterGeneric.java
new file mode 100644 (file)
index 0000000..3156866
--- /dev/null
@@ -0,0 +1,8 @@
+// "Insert 'return'" "true"
+import java.util.*;
+
+class Test {
+  List<String> getList() {
+    new ArrayList<>()<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/insertReturn/beforeGeneric.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/insertReturn/beforeGeneric.java
new file mode 100644 (file)
index 0000000..3156866
--- /dev/null
@@ -0,0 +1,8 @@
+// "Insert 'return'" "true"
+import java.util.*;
+
+class Test {
+  List<String> getList() {
+    new ArrayList<>()<caret>
+  }
+}
\ No newline at end of file