IDEA-153966 (False inspection alert for "Optional.get() without isPresent check")

This commit is contained in:
Bas Leijdekkers
2016-04-13 18:04:02 +02:00
parent 7a76eccac6
commit 84995a81da
2 changed files with 38 additions and 3 deletions
@@ -151,6 +151,12 @@ public class OptionalGetWithoutIsPresentInspection extends BaseInspection {
PsiElement parent = PsiTreeUtil.getParentOfType(context, PsiIfStatement.class, PsiWhileStatement.class, PsiConditionalExpression.class,
PsiPolyadicExpression.class);
while (parent != null) {
if (parent instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent;
if (JavaTokenType.OROR.equals(polyadicExpression.getOperationTokenType())) {
checker.negate = true;
}
}
parent.accept(checker);
if (checker.hasIsPresentCall()) {
return true;
@@ -180,9 +186,7 @@ public class OptionalGetWithoutIsPresentInspection extends BaseInspection {
@Override
public void visitPolyadicExpression(PsiPolyadicExpression expression) {
final IElementType tokenType = expression.getOperationTokenType();
if (tokenType == JavaTokenType.OROR) {
negate = !negate;
} else if (tokenType != JavaTokenType.ANDAND) {
if (tokenType != JavaTokenType.ANDAND && tokenType != JavaTokenType.OROR) {
return;
}
for (PsiExpression operand : expression.getOperands()) {
@@ -79,6 +79,37 @@ public class OptionalGetWithoutIsPresentInspectionTest extends LightInspectionTe
"}");
}
public void testPolyadicExpression1() {
doTest("import java.util.Optional;" +
"class X {" +
" public void demo(Optional<String> value) {\n" +
" boolean flag = value.isPresent() && \"Yes\".equals(value.get());\n" +
" }" +
"}");
}
public void testPolyadicExpression2() {
doTest("import java.util.Optional;" +
"class X {" +
" boolean m(Optional<String> o) {" +
" return !o.isPresent() || o.get().equals(\"j\");" +
" }" +
"}");
}
public void testPolyadicExpression3() {
doTest("import java.util.Optional;" +
"class X {" +
" String g() {" +
" Optional<String> o = Optional.empty();" +
" if(o == null || !o.isPresent()) {" +
" return \"\";" +
" }" +
" return o.get();" +
" }" +
"}");
}
public void testOptionalGetWithoutIsPresent() {
doTest();
}