diff options
author | Fawzi Mohamed <fawzi.mohamed@qt.io> | 2021-01-29 23:20:31 +0100 |
---|---|---|
committer | Fawzi Mohamed <fawzi.mohamed@qt.io> | 2021-02-03 14:05:16 +0000 |
commit | 7015ef04b77f4e4318a46535951e4fa14450c6d3 (patch) | |
tree | 2485c4972c3c54a3b0619236063f508b602fcc4c /src/libs/qmljs/qmljscheck.cpp | |
parent | cc00af8334043326799ac281803cadb479b5efc4 (diff) | |
download | qt-creator-7015ef04b77f4e4318a46535951e4fa14450c6d3.tar.gz |
qmljs: add check for comparisons not depending on values
currently we mainly try to warn about primitive == null/undefined or
primitive === non primitive.
There are other that we could warn about null==null null==undefined,
but I feel that they might be triggered too much by clean code.
Change-Id: Id43d838d60a4e13f361be34e4bb38211777a081e
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
Diffstat (limited to 'src/libs/qmljs/qmljscheck.cpp')
-rw-r--r-- | src/libs/qmljs/qmljscheck.cpp | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp index b0bfcdfd17..efa69af492 100644 --- a/src/libs/qmljs/qmljscheck.cpp +++ b/src/libs/qmljs/qmljscheck.cpp @@ -1275,6 +1275,30 @@ static bool shouldAvoidNonStrictEqualityCheck(const Value *lhs, const Value *rhs return false; } +static bool equalIsAlwaysFalse(const Value *lhs, const Value *rhs) +{ + if ((lhs->asNullValue() || lhs->asUndefinedValue()) + && (rhs->asNumberValue() || rhs->asBooleanValue() || rhs->asStringValue())) + return true; + return false; +} + +static bool strictCompareConstant(const Value *lhs, const Value *rhs) +{ + if (lhs->asUnknownValue() || rhs->asUnknownValue()) + return false; + if (lhs->asBooleanValue() && !rhs->asBooleanValue()) + return true; + if (lhs->asNumberValue() && !rhs->asNumberValue()) + return true; + if (lhs->asStringValue() && !rhs->asStringValue()) + return true; + if (lhs->asObjectValue() && (!rhs->asObjectValue() || !rhs->asNullValue() || !rhs->asUndefinedValue())) + return true; + return false; +} + + bool Check::visit(BinaryExpression *ast) { const QString source = _doc->source(); @@ -1300,6 +1324,18 @@ bool Check::visit(BinaryExpression *ast) || shouldAvoidNonStrictEqualityCheck(rhsValue, lhsValue)) { addMessage(MaybeWarnEqualityTypeCoercion, ast->operatorToken); } + if (equalIsAlwaysFalse(lhsValue, rhsValue) + || equalIsAlwaysFalse(rhsValue, lhsValue)) + addMessage(WarnLogicalValueDoesNotDependOnValues, ast->operatorToken); + } + if (ast->op == QSOperator::StrictEqual || ast->op == QSOperator::StrictNotEqual) { + Evaluate eval(&_scopeChain); + const Value *lhsValue = eval(ast->left); + const Value *rhsValue = eval(ast->right); + if (strictCompareConstant(lhsValue, rhsValue) + || strictCompareConstant(rhsValue, lhsValue)) { + addMessage(WarnLogicalValueDoesNotDependOnValues, ast->operatorToken); + } } // check odd + ++ combinations |