Debian Codegraph @

src/checks/level0/wrong-qglobalstatic.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2015 Sergio Martins <[email protected]>
3 SPDX-FileCopyrightText: 2024 Alexander Lohnau <[email protected]>
4
5 SPDX-License-Identifier: LGPL-2.0-or-later
6 */
7
8 #include "wrong-qglobalstatic.h"
9 #include "MacroUtils.h"
10 #include "StringUtils.h"
11 #include "TemplateUtils.h"
12
13 #include <clang/AST/DeclCXX.h>
14 #include <clang/AST/ExprCXX.h>
15 #include <clang/AST/Stmt.h>
16 #include <clang/AST/Type.h>
17 #include <clang/Basic/LLVM.h>
18 #include <clang/Basic/SourceLocation.h>
19 #include <llvm/ADT/StringRef.h>
20 #include <llvm/Support/Casting.h>
21
22 #include <vector>
23
24 using namespace clang;
25
26 void WrongQGlobalStatic::VisitStmt(clang::Stmt *stmt)
27 {
28 auto *ctorExpr = dyn_cast<CXXConstructExpr>(stmt);
29 if (!ctorExpr) {
30 return;
31 }
32
33 CXXConstructorDecl *ctorDecl = ctorExpr->getConstructor();
34 if (!ctorDecl) {
35 return;
36 }
37 if (StringRef name = clazy::name(ctorDecl); name != "QGlobalStatic" && name != "QGlobalStaticCompoundStmt") {
38 return; // Only consider relevant Qt5 and Qt6 ctors
39 }
40
41 SourceLocation loc = stmt->getBeginLoc();
42 if (clazy::isInMacro(astContext(), loc, "Q_GLOBAL_STATIC_WITH_ARGS")) {
43 return;
44 }
45
46 CXXRecordDecl *record = ctorDecl->getParent();
47 std::vector<QualType> typeList = clazy::getTemplateArgumentsTypes(record);
48 CXXRecordDecl *usersClass = nullptr;
49 std::string underlyingTypeName;
50 if (typeList.empty()) {
51 return;
52 }
53 if (clazy::classNameFor(typeList[0]) == "Holder") { // In Qt6, we need to look into the Holder for the user-defined class/type name
54 auto templateTypes = clazy::getTemplateArgumentsTypes(typeList[0]->getAsCXXRecordDecl());
55 if (templateTypes.empty()) {
56 return;
57 }
58 QualType qgsType = templateTypes[0];
59 if (auto *typePtr = qgsType.getTypePtrOrNull(); typePtr && typePtr->isRecordType()) {
60 for (auto *decl : typePtr->getAsCXXRecordDecl()->decls()) {
61 if (auto *typedefDecl = dyn_cast<TypedefDecl>(decl); typedefDecl && typedefDecl->getNameAsString() == "QGS_Type") {
62 usersClass = typedefDecl->getUnderlyingType()->getAsCXXRecordDecl();
63 underlyingTypeName = typedefDecl->getUnderlyingType().getAsString();
64 break;
65 }
66 }
67 }
68 } else if (auto *t = typeList[0].getTypePtrOrNull()) {
69 usersClass = t->getAsCXXRecordDecl();
70 underlyingTypeName = typeList[0].getAsString();
71 }
72
73 if (usersClass) {
74 if (usersClass->hasTrivialDefaultConstructor() && usersClass->hasTrivialDestructor()) {
75 emitWarning(loc, "Don't use Q_GLOBAL_STATIC with trivial type (" + usersClass->getNameAsString() + ')');
76 }
77 } else {
78 // Not a class, why use Q_GLOBAL_STATIC ?
79 emitWarning(loc, "Don't use Q_GLOBAL_STATIC with non-class type (" + underlyingTypeName + ')');
80 }
81 }