[java-intentions] Add fix to replace an unresolved type with initializer type

Fixes IDEA-225526 Replace var with inferred type in Java 9 or below

GitOrigin-RevId: 465b0163a2a8b3e8f0346b350a5e373d9b958817
This commit is contained in:
Tagir Valeev
2025-06-24 18:59:51 +00:00
committed by intellij-monorepo-bot
parent 163bfe5b17
commit c498114575
6 changed files with 40 additions and 0 deletions
@@ -656,6 +656,7 @@ public final class DefaultJavaErrorFixProvider extends AbstractJavaErrorFixProvi
fixes(EXPRESSION_SUPER_UNQUALIFIED_DEFAULT_METHOD, (error, sink) ->
QualifySuperArgumentFix.registerQuickFixAction(error.context(), sink));
fix(REFERENCE_UNRESOLVED, error -> HighlightFixUtil.createUnresolvedReferenceFix(error.psi()));
fix(REFERENCE_UNRESOLVED, error -> HighlightFixUtil.createVariableTypeFix(error.psi()));
fix(REFERENCE_QUALIFIER_PRIMITIVE,
error -> error.psi() instanceof PsiReferenceExpression ref ? myFactory.createRenameWrongRefFix(ref) : null);
fix(CAST_INTERSECTION_NOT_INTERFACE, error -> {
@@ -25,6 +25,7 @@ import com.intellij.pom.java.JavaFeature;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.impl.IncompleteModelUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.search.GlobalSearchScope;
@@ -1116,6 +1117,19 @@ public final class HighlightFixUtil {
.toList();
}
static @Nullable CommonIntentionAction createVariableTypeFix(PsiJavaCodeReferenceElement ref) {
if (!(ref.getParent() instanceof PsiTypeElement typeElement)) return null;
if (!(typeElement.getParent() instanceof PsiLocalVariable localVariable)) return null;
PsiExpression initializer = localVariable.getInitializer();
if (initializer == null) return null;
PsiType type = initializer.getType();
if (type == null || !PsiTypesUtil.isDenotableType(type, localVariable)) return null;
if (PsiTypes.voidType().equals(type) || PsiTypes.nullType().equals(type)) return null;
if (IncompleteModelUtil.hasUnresolvedComponent(type)) return null;
return PriorityIntentionActionWrapper.highPriority(
QuickFixFactory.getInstance().createSetVariableTypeFix(localVariable, type));
}
private static final class ReturnModel {
final PsiReturnStatement myStatement;
final PsiType myType;
@@ -0,0 +1,6 @@
// "Set variable type to 'int'" "true-preview"
public class Demo {
void test() {
int s = 123;
}
}
@@ -0,0 +1,6 @@
// "Set variable type to 'int'" "true-preview"
public class Demo {
void test() {
in<caret>tt s = 123;
}
}
@@ -0,0 +1,6 @@
// "Set variable type to 'intt'" "false"
public class Demo {
void test(intt s1) {
in<caret>tt s = s1;
}
}
@@ -0,0 +1,7 @@
// "Set variable type to 'int'" "false"
public class Demo {
void test() {
in<caret>tt s;
s = 123;
}
}