in lib/src/rules/prefer_is_empty.dart [95:170]
void _check(BinaryExpression expression, int value,
{required bool constantOnRight}) {
// Don't lint if we're in a const constructor initializer.
var constructorInitializer =
expression.thisOrAncestorOfType<ConstructorInitializer>();
if (constructorInitializer != null) {
var constructorDecl = constructorInitializer.parent;
if (constructorDecl is! ConstructorDeclaration ||
constructorDecl.constKeyword != null) {
return;
}
}
// Or in a const context.
// See: https://github.com/dart-lang/linter/issues/1719
if (expression.inConstantContext) {
return;
}
var operator = expression.operator;
if (value == 0) {
if (operator.type == TokenType.EQ_EQ ||
operator.type == TokenType.LT_EQ) {
rule.reportLint(expression, errorCode: PreferIsEmpty.useIsEmpty);
} else if (operator.type == TokenType.GT ||
operator.type == TokenType.BANG_EQ) {
rule.reportLint(expression, errorCode: PreferIsEmpty.useIsNotEmpty);
} else if (operator.type == TokenType.LT) {
rule.reportLint(expression, errorCode: PreferIsEmpty.alwaysFalse);
} else if (operator.type == TokenType.GT_EQ) {
rule.reportLint(expression, errorCode: PreferIsEmpty.alwaysTrue);
}
} else if (value == 1) {
if (constantOnRight) {
// 'length >= 1' is same as 'isNotEmpty',
// and 'length < 1' is same as 'isEmpty'
if (operator.type == TokenType.GT_EQ) {
rule.reportLint(expression, errorCode: PreferIsEmpty.useIsNotEmpty);
} else if (operator.type == TokenType.LT) {
rule.reportLint(expression, errorCode: PreferIsEmpty.useIsEmpty);
}
} else {
// '1 <= length' is same as 'isNotEmpty',
// and '1 > length' is same as 'isEmpty'
if (operator.type == TokenType.LT_EQ) {
rule.reportLint(expression, errorCode: PreferIsEmpty.useIsNotEmpty);
} else if (operator.type == TokenType.GT) {
rule.reportLint(expression, errorCode: PreferIsEmpty.useIsEmpty);
}
}
} else if (value < 0) {
if (constantOnRight) {
// 'length' is always >= 0, so comparing with negative makes no sense.
if (operator.type == TokenType.EQ_EQ ||
operator.type == TokenType.LT_EQ ||
operator.type == TokenType.LT) {
rule.reportLint(expression, errorCode: PreferIsEmpty.alwaysFalse);
} else if (operator.type == TokenType.BANG_EQ ||
operator.type == TokenType.GT_EQ ||
operator.type == TokenType.GT) {
rule.reportLint(expression, errorCode: PreferIsEmpty.alwaysTrue);
}
} else {
// 'length' is always >= 0, so comparing with negative makes no sense.
if (operator.type == TokenType.EQ_EQ ||
operator.type == TokenType.GT_EQ ||
operator.type == TokenType.GT) {
rule.reportLint(expression, errorCode: PreferIsEmpty.alwaysFalse);
} else if (operator.type == TokenType.BANG_EQ ||
operator.type == TokenType.LT_EQ ||
operator.type == TokenType.LT) {
rule.reportLint(expression, errorCode: PreferIsEmpty.alwaysTrue);
}
}
}
}