From cc8b90376cec98152c2ec45876ebc5df524a0b05 Mon Sep 17 00:00:00 2001 From: Tagir Valeev Date: Thu, 20 Mar 2025 18:11:14 +0100 Subject: [PATCH] [java-highlighting] Do not allow unchecked conversion for explicit new expression types Fixes IDEA-326353 Generics error is not displayed in new expression GitOrigin-RevId: 661bf57ed3451096fcee245204dd30adae49e9e1 --- .../src/com/intellij/psi/GenericsUtil.java | 13 ++++++++-- .../CaptureForBoundCheck.java | 8 ++++++ .../RawAtFBoundAtNew.java | 26 +++++++++++++++++++ .../lambda/GenericsHighlighting8Test.java | 1 + 4 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/RawAtFBoundAtNew.java diff --git a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java index db383980fef4..fe99a81e58a7 100644 --- a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java @@ -468,8 +468,17 @@ public final class GenericsUtil { //Given a generic type declaration C (n > 0), the direct supertypes of the parameterized type C where at least one of the Ri is a wildcard //type argument, are the direct supertypes of the parameterized type C which is the result of applying capture conversion to C. PsiType capturedType = PsiUtil.captureToplevelWildcards(type, referenceParameterList); - //allow unchecked conversions in method calls but not in type declaration - return checkNotInBounds(capturedType, bound, PsiTreeUtil.getParentOfType(referenceParameterList, PsiCallExpression.class) != null); + //allow unchecked conversions in method calls, new expression args, or in diamond types, but not in other places + boolean uncheckedConversionByDefault; + PsiElement parent = referenceParameterList.getParent(); + if (parent instanceof PsiReferenceExpression || parent instanceof PsiNewExpression) { + uncheckedConversionByDefault = true; + } + else { + PsiTypeElement[] elements = referenceParameterList.getTypeParameterElements(); + uncheckedConversionByDefault = elements.length == 1 && elements[0].getType() instanceof PsiDiamondType; + } + return checkNotInBounds(capturedType, bound, uncheckedConversionByDefault); } public static boolean checkNotInBounds(PsiType type, PsiType bound, boolean uncheckedConversionByDefault) { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/CaptureForBoundCheck.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/CaptureForBoundCheck.java index 323840286822..ea89adaa4ef8 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/CaptureForBoundCheck.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/CaptureForBoundCheck.java @@ -17,4 +17,12 @@ class EnumBug { EnumSet<Option> enumSetRaw = EnumSet.