[java-dfa] Correctly unbox variables for contract check

Fixes IDEA-343951 Warning about boolean value is always true is wrong

GitOrigin-RevId: 365f32fc0ff0fc293bf2608e3b0ad1bb3b58f040
This commit is contained in:
Tagir Valeev
2024-01-26 22:01:45 +00:00
committed by intellij-monorepo-bot
parent 99b3a9a6b0
commit 7b77a3c1ad
3 changed files with 25 additions and 4 deletions
@@ -1,6 +1,7 @@
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.dataFlow;
import com.intellij.codeInsight.Nullability;
import com.intellij.codeInspection.dataFlow.jvm.SpecialField;
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState;
import com.intellij.codeInspection.dataFlow.types.*;
@@ -381,11 +382,11 @@ public abstract class ContractValue {
public DfaCondition makeCondition(DfaValueFactory factory, DfaCallArguments arguments) {
DfaValue left = myLeft.makeDfaValue(factory, arguments);
DfaValue right = myRight.makeDfaValue(factory, arguments);
if (left.getDfType() instanceof DfPrimitiveType) {
right = DfaUtil.boxUnbox(right, left.getDfType());
if (left.getDfType() instanceof DfPrimitiveType primitiveType) {
right = DfaUtil.boxUnbox(right, DfTypes.typedObject(primitiveType.getPsiType(), Nullability.UNKNOWN));
}
if (right.getDfType() instanceof DfPrimitiveType) {
left = DfaUtil.boxUnbox(left, right.getDfType());
if (right.getDfType() instanceof DfPrimitiveType primitiveType) {
left = DfaUtil.boxUnbox(left, DfTypes.typedObject(primitiveType.getPsiType(), Nullability.UNKNOWN));
}
return left.cond(myRelationType, right);
}
@@ -0,0 +1,19 @@
public class BoxedBooleanMethodWithCast {
// IDEA-343951
public static boolean checkObjectType(Object object) {
if (object instanceof Boolean) {
final boolean booleanValue = meansTrue((Boolean) object);
return booleanValue;
}
return false;
}
public static void main(String[] args) {
System.out.println("True = " + checkObjectType(Boolean.TRUE));
System.out.println("False = " + checkObjectType(Boolean.FALSE));
}
public static boolean meansTrue(Boolean bool) {
return Boolean.TRUE.equals(bool);
}
}
@@ -743,4 +743,5 @@ public class DataFlowInspectionTest extends DataFlowInspectionTestCase {
public void testNullWarningAfterInstanceofCheck() { doTest(); }
public void testNullWarningAfterInstanceofAndNullCheck() { doTest(); }
public void testInitializedViaSuperCall() { doTest(); }
public void testBoxedBooleanMethodWithCast() { doTest(); }
}