Debian Codegraph @

src/checks/manuallevel/used-qunused-variable.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2024 Alexander Lohnau <[email protected]>
3 SPDX-License-Identifier: LGPL-2.0-or-later
4 */
5
6 #include "used-qunused-variable.h"
7 #include "ClazyContext.h"
8 #include "MacroUtils.h"
9 #include "PreProcessorVisitor.h"
10 #include "TypeUtils.h"
11 #include "Utils.h"
12
13 #include <clang/AST/AST.h>
14 #include <clang/AST/Decl.h>
15 #include <clang/AST/RecursiveASTVisitor.h>
16
17 using namespace clang;
18
19 class ParameterUsageVisitor : public RecursiveASTVisitor<ParameterUsageVisitor>
20 {
21 public:
22 explicit ParameterUsageVisitor(const ParmVarDecl *param)
23 : param(param)
24 {
25 }
26
27 bool VisitStmt(Stmt *stmt)
28 {
29 if (checkUsage(stmt)) {
30 paramUsages.push_back(stmt);
31 }
32 return true;
33 }
34
35 std::vector<Stmt *> paramUsages;
36 Stmt *qunusedParamUsage = nullptr;
37
38 private:
39 const ParmVarDecl *param;
40
41 bool checkUsage(Stmt *S, Stmt *parentStmt = nullptr)
42 {
43 if (!S)
44 return false;
45 if (auto *DRE = dyn_cast<DeclRefExpr>(S); DRE && DRE->getDecl() == param) {
46 return true;
47 }
48
49 if (auto *cs = dyn_cast<CompoundStmt>(S)) {
50 for (auto *child : cs->children()) {
51 if (auto *castExpr = dyn_cast<CastExpr>(child); castExpr && castExpr->getType().getAsString() == "void") {
52 for (auto *possibleDeclRef : castExpr->children()) {
53 if (auto *declRef = dyn_cast<DeclRefExpr>(possibleDeclRef); declRef && declRef->getDecl() == param) {
54 // We found a void cast
55 qunusedParamUsage = possibleDeclRef;
56 }
57 }
58 }
59 if (checkUsage(child, cs)) {
60 return true;
61 }
62 }
63 }
64
65 return false;
66 }
67 };
68
69 void UsedQUnusedVariable::VisitDecl(clang::Decl *decl)
70 {
71 const auto *fncDecl = dyn_cast<FunctionDecl>(decl);
72 if (!fncDecl) {
73 return;
74 }
75 for (auto *param : fncDecl->parameters()) {
76 if (param->isUsed()) {
77 ParameterUsageVisitor visitor(param);
78
79 // Visit the compound statement (the function body) to find usages
80 visitor.TraverseStmt(fncDecl->getBody());
81
82 if (visitor.paramUsages.size() > 1 && visitor.qunusedParamUsage) {
83 if (auto beginLoc = visitor.qunusedParamUsage->getBeginLoc();
84 beginLoc.isMacroID() && Lexer::getImmediateMacroName(beginLoc, sm(), lo()) == "Q_UNUSED") {
85 emitWarning(visitor.qunusedParamUsage, "Q_UNUSED used even though variable has usages");
86 } else {
87 emitWarning(visitor.qunusedParamUsage, "void cast used even though variable has usages");
88 }
89 }
90 }
91 }
92 }