| 1 |
/* |
| 2 |
SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB a KDAB Group company [email protected] |
| 3 |
SPDX-FileContributor: Shivam Kunwar <[email protected]> |
| 4 |
|
| 5 |
SPDX-License-Identifier: LGPL-2.0-or-later |
| 6 |
*/ |
| 7 |
|
| 8 |
#include "unused-result-check.h" |
| 9 |
#include "StringUtils.h" |
| 10 |
|
| 11 |
#include <clang/AST/AST.h> |
| 12 |
#include <clang/AST/ExprCXX.h> |
| 13 |
#include <clang/ASTMatchers/ASTMatchFinder.h> |
| 14 |
#include <clang/ASTMatchers/ASTMatchers.h> |
| 15 |
#include <clang/ASTMatchers/ASTMatchersInternal.h> |
| 16 |
|
| 17 |
using namespace clang::ast_matchers; |
| 18 |
|
| 19 |
using namespace clang; |
| 20 |
|
| 21 |
class Caller : public ClazyAstMatcherCallback |
| 22 |
{ |
| 23 |
public: |
| 24 |
explicit Caller(CheckBase *check) |
| 25 |
: ClazyAstMatcherCallback(check) |
| 26 |
{ |
| 27 |
} |
| 28 |
void run(const MatchFinder::MatchResult &result) override |
| 29 |
{ |
| 30 |
if (const auto *callExpr = result.Nodes.getNodeAs<CXXMemberCallExpr>("opCallExpr")) { |
| 31 |
if (const auto *methodDecl = callExpr->getMethodDecl(); methodDecl && methodDecl->isConst() && !methodDecl->getReturnType()->isVoidType()) { |
| 32 |
const auto &parents = result.Context->getParents(*callExpr); |
| 33 |
|
| 34 |
if (parents[0].get<Stmt>() != nullptr && parents[0].get<Decl>() == nullptr) { |
| 35 |
if (!llvm::dyn_cast<Expr>(parents[0].get<Stmt>()) && !llvm::dyn_cast<ReturnStmt>(parents[0].get<Stmt>()) |
| 36 |
&& !llvm::dyn_cast<IfStmt>(parents[0].get<Stmt>()) && !llvm::dyn_cast<WhileStmt>(parents[0].get<Stmt>()) |
| 37 |
&& !llvm::dyn_cast<DoStmt>(parents[0].get<Stmt>()) && !llvm::dyn_cast<SwitchStmt>(parents[0].get<Stmt>()) |
| 38 |
&& !llvm::dyn_cast<ForStmt>(parents[0].get<Stmt>()) |
| 39 |
&& !llvm::dyn_cast<CXXThisExpr>(parents[0].get<Stmt>()) |
| 40 |
// Ignore this false positive from a Qt header for now, we pass a mutable pointer to a static function |
| 41 |
&& clazy::qualifiedMethodName(callExpr->getMethodDecl()) != "QMetaType::registerHelper") { |
| 42 |
m_check->emitWarning(callExpr->getExprLoc(), "Result of const member function is not used."); |
| 43 |
} |
| 44 |
} else if (parents[0].get<Decl>() != nullptr && parents[0].get<Stmt>() == nullptr) { |
| 45 |
if (!llvm::dyn_cast<VarDecl>(parents[0].get<Decl>()) && !llvm::dyn_cast<CXXConstructorDecl>(parents[0].get<Decl>())) { |
| 46 |
m_check->emitWarning(callExpr->getExprLoc(), "Result of const member function is not used."); |
| 47 |
} |
| 48 |
} |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
}; |
| 53 |
|
| 54 |
UnusedResultCheck::~UnusedResultCheck() = default; |
| 55 |
|
| 56 |
void UnusedResultCheck::registerASTMatchers(MatchFinder &finder) |
| 57 |
{ |
| 58 |
m_astMatcherCallBack = std::make_unique<Caller>(this); |
| 59 |
finder.addMatcher(cxxMemberCallExpr().bind("opCallExpr"), m_astMatcherCallBack.get()); |
| 60 |
} |