[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Nov 10 11:06:54 PST 2023
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tidy
Author: None (schenker)
<details>
<summary>Changes</summary>
With this PR, `bugprone-assert-side-effect` assumes that operator methods that are not marked as `const` have side effects. This matches the existing rule for non-operator methods.
E.g. the following snippet is now reported and was previously not:
```
std::stringstream ss;
assert(ss << 1);
```
---
Full diff: https://github.com/llvm/llvm-project/pull/71974.diff
2 Files Affected:
- (modified) clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp (+4)
- (modified) clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp (+12-1)
``````````diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 07a987359d4d8d7..599f5ac70e7a229 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
}
if (const auto *OpCallExpr = dyn_cast<CXXOperatorCallExpr>(E)) {
+ if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+ if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FuncDecl))
+ return !MethodDecl->isConst();
+
OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
index 6c41e1e320adeac..49d3d456deb9d35 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
@@ -11,7 +11,7 @@ class MyClass {
MyClass &operator=(const MyClass &rhs) { return *this; }
- int operator-() { return 1; }
+ int operator-() const { return 1; }
operator bool() const { return true; }
@@ -84,5 +84,16 @@ int main() {
msvc_assert(mc2 = mc);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in msvc_assert() condition discarded in release builds
+ struct {
+ int operator<<(int i) const { return i; }
+ } constOp;
+ assert(constOp << 1);
+
+ struct {
+ int operator<<(int i) { return i; }
+ } nonConstOp;
+ assert(nonConstOp << 1);
+ // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() condition discarded in release builds
+
return 0;
}
``````````
</details>
https://github.com/llvm/llvm-project/pull/71974
More information about the cfe-commits
mailing list