[clang-tidy] Add check for assignment or comparision operators' operand in readability-math-missing-parentheses (#141345)

Fixes false negative in #141249. 

Add check for math binary operators which are operands of assignment or
comparision operators.

Closes #141249.
This commit is contained in:
flovent
2025-06-05 20:18:01 +08:00
committed by GitHub
parent 60808a45dc
commit a12f4f0031
3 changed files with 30 additions and 7 deletions

View File

@@ -16,13 +16,15 @@ using namespace clang::ast_matchers;
namespace clang::tidy::readability {
void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
unless(isAssignmentOperator()),
unless(isComparisonOperator()),
unless(hasAnyOperatorName("&&", "||")),
hasDescendant(binaryOperator()))
.bind("binOp"),
this);
Finder->addMatcher(
binaryOperator(
unless(hasParent(binaryOperator(unless(isAssignmentOperator()),
unless(isComparisonOperator())))),
unless(isAssignmentOperator()), unless(isComparisonOperator()),
unless(hasAnyOperatorName("&&", "||")),
hasDescendant(binaryOperator()))
.bind("binOp"),
this);
}
static int getPrecedence(const BinaryOperator *BinOp) {

View File

@@ -245,6 +245,11 @@ Changes in existing checks
tolerating fix-it breaking compilation when functions is used as pointers
to avoid matching usage of functions within the current compilation unit.
- Improved :doc:`readability-math-missing-parentheses
<clang-tidy/checks/readability/math-missing-parentheses>` check by fixing
false negatives where math expressions are the operand of assignment operators
or comparison operators.
- Improved :doc:`readability-qualified-auto
<clang-tidy/checks/readability/qualified-auto>` check by adding the option
`AllowedTypes`, that excludes specified types from adding qualifiers.

View File

@@ -157,3 +157,19 @@ namespace PR92516 {
for (j = i + 1, 2; j < 1; ++j) {}
}
}
namespace PR141249 {
void AssignAsParentBinOp(int* netChange, int* nums, int k, int i) {
//CHECK-MESSAGES: :[[@LINE+2]]:30: warning: '-' has higher precedence than '^'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses]
//CHECK-FIXES: netChange[i] = nums[i] ^ (k - nums[i]);
netChange[i] = nums[i] ^ k - nums[i];
}
}
void CompareAsParentBinOp(int b) {
//CHECK-MESSAGES: :[[@LINE+2]]:12: warning: '*' has higher precedence than '-'; add parentheses to explicitly specify the order of operations [readability-math-missing-parentheses]
//CHECK-FIXES: if (b == (1 * 2) - 3) {
if (b == 1 * 2 - 3) {
}
}