infer more contracts for if statements without else (IDEA-132872)

This commit is contained in:
peter
2014-11-20 17:57:46 +01:00
parent 9ad4a2bfb7
commit 2a143c0890
2 changed files with 20 additions and 20 deletions

View File

@@ -34,7 +34,6 @@ import com.siyeh.ig.psiutils.SideEffectChecker;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -178,7 +177,7 @@ class ContractInferenceInterpreter {
}
});
if (notNull) {
return ContainerUtil.concat(fromDelegate, Arrays.asList(new MethodContract(myEmptyConstraints, NOT_NULL_VALUE)));
return ContainerUtil.concat(fromDelegate, Collections.singletonList(new MethodContract(myEmptyConstraints, NOT_NULL_VALUE)));
}
return fromDelegate;
}
@@ -365,7 +364,7 @@ class ContractInferenceInterpreter {
PsiStatement elseBranch = ((PsiIfStatement)statement).getElseBranch();
if (elseBranch != null) {
result.addAll(visitStatements(falseStates, elseBranch));
} else if (alwaysReturns(thenBranch)) {
} else {
states = falseStates;
continue;
}
@@ -404,22 +403,6 @@ class ContractInferenceInterpreter {
return false;
}
private static boolean alwaysReturns(@Nullable PsiStatement statement) {
if (statement instanceof PsiReturnStatement || statement instanceof PsiThrowStatement) return true;
if (statement instanceof PsiBlockStatement) {
for (PsiStatement child : ((PsiBlockStatement)statement).getCodeBlock().getStatements()) {
if (alwaysReturns(child)) {
return true;
}
}
}
if (statement instanceof PsiIfStatement) {
return alwaysReturns(((PsiIfStatement)statement).getThenBranch()) &&
alwaysReturns(((PsiIfStatement)statement).getElseBranch());
}
return false;
}
@Nullable
private static ValueConstraint getLiteralConstraint(@Nullable PsiExpression expr) {
if (expr instanceof PsiLiteralExpression) {

View File

@@ -148,7 +148,7 @@ class ContractInferenceFromSourceTest extends LightCodeInsightFixtureTestCase {
return true;
}
""")
assert c == []
assert c == ['null -> true']
}
void "test assertion"() {
@@ -391,6 +391,23 @@ class ContractInferenceFromSourceTest extends LightCodeInsightFixtureTestCase {
assert c == ['null -> null']
}
public void "test return after if without else"() {
def c = inferContracts("""
public static boolean isBlank(String s) {
if (s != null) {
final int l = s.length();
for (int i = 0; i < l; i++) {
final char c = s.charAt(i);
if (c != ' ') {
return false;
}
}
}
return true;
} """)
assert c == ['null -> true']
}
private String inferContract(String method) {
return assertOneElement(inferContracts(method))
}