KT-1680 Warn if non-null variable is compared to null

#KT-1680 fixed
This commit is contained in:
Svetlana Isakova
2012-04-19 14:20:36 +04:00
parent 44c5e0ca2e
commit 558d1a0e2f
3 changed files with 23 additions and 0 deletions
@@ -380,6 +380,8 @@ public interface Errors {
}
}, TO_STRING, TO_STRING);
DiagnosticFactory2<JetBinaryExpression, JetBinaryExpression, Boolean> SENSELESS_COMPARISON = DiagnosticFactory2.create(WARNING, "Condition ''{0}'' is always ''{1}''", ELEMENT_TEXT, TO_STRING);
DiagnosticFactory2<PsiElement, CallableMemberDescriptor, DeclarationDescriptor> OVERRIDING_FINAL_MEMBER = DiagnosticFactory2.create(ERROR, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME);
DiagnosticFactory3<JetModifierListOwner, Visibility, CallableMemberDescriptor, DeclarationDescriptor> CANNOT_WEAKEN_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", PositioningStrategies.POSITION_VISIBILITY_MODIFIER, TO_STRING, NAME, NAME);
DiagnosticFactory3<JetModifierListOwner, Visibility, CallableMemberDescriptor, DeclarationDescriptor> CANNOT_CHANGE_ACCESS_PRIVILEGE = DiagnosticFactory3.create(ERROR, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", PositioningStrategies.POSITION_VISIBILITY_MODIFIER, TO_STRING, NAME, NAME);
@@ -950,9 +950,16 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
context.trace.report(EQUALITY_NOT_APPLICABLE.on(expression, operationSign, leftType, rightType));
}
}
if (isSenselessComparisonWithNull(leftType, right) || isSenselessComparisonWithNull(rightType, left)) {
context.trace.report(SENSELESS_COMPARISON.on(expression, expression, operationSign.getReferencedNameElementType() == JetTokens.EXCLEQ));
}
}
}
private boolean isSenselessComparisonWithNull(JetType firstType, JetExpression secondExpression) {
return !firstType.isNullable() && secondExpression instanceof JetConstantExpression && secondExpression.getNode().getElementType() == JetNodeTypes.NULL;
}
protected JetType visitAssignmentOperation(JetBinaryExpression expression, ExpressionTypingContext context) {
return assignmentIsNotAnExpressionError(expression, context);
}
@@ -0,0 +1,14 @@
//KT-1680 Warn if non-null variable is compared to null
package kt1680
fun foo() {
val x = 1
if (<!SENSELESS_COMPARISON!>x != null<!>) {} // <-- need a warning here!
if (<!SENSELESS_COMPARISON!>x == null<!>) {}
if (<!SENSELESS_COMPARISON!>null != x<!>) {}
if (<!SENSELESS_COMPARISON!>null == x<!>) {}
val y : Int? = 1
if (y != null) {}
if (y == null) {}
}