Debian Codegraph @

src/checks/level2/missing-qobject-macro.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2015 Sergio Martins <[email protected]>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7 #include "missing-qobject-macro.h"
8 #include "ClazyContext.h"
9 #include "FixItUtils.h"
10 #include "PreProcessorVisitor.h"
11 #include "QtUtils.h"
12
13 #include <clang/AST/DeclBase.h>
14 #include <clang/AST/DeclCXX.h>
15 #include <clang/Basic/IdentifierTable.h>
16 #include <clang/Basic/LLVM.h>
17 #include <clang/Basic/SourceManager.h>
18 #include <clang/Lex/Token.h>
19 #include <filesystem>
20 #include <llvm/ADT/StringRef.h>
21 #include <llvm/Support/Casting.h>
22
23 using namespace clang;
24
25 void MissingQObjectMacro::VisitMacroExpands(const clang::Token &MacroNameTok, const clang::SourceRange &range, const MacroInfo *)
26 {
27 IdentifierInfo *ii = MacroNameTok.getIdentifierInfo();
28 if (ii && ii->getName() == "Q_OBJECT") {
29 registerQ_OBJECT(range.getBegin());
30 }
31 }
32
33 void MissingQObjectMacro::VisitDecl(clang::Decl *decl)
34 {
35 auto *record = dyn_cast<CXXRecordDecl>(decl);
36 if (!record || !record->hasDefinition() || record->getDefinition() != record || !clazy::isQObject(record, m_context->qtNamespace())) {
37 return;
38 }
39
40 if (record->getDescribedClassTemplate() != nullptr) { // moc doesn't accept Q_OBJECT in templates
41 return;
42 }
43
44 if (isa<CXXRecordDecl>(record->getDeclContext())) { // moc doesn't accept Q_OBJECT in nested classes
45 return;
46 }
47
48 if (m_context->usingPreCompiledHeaders()) {
49 return;
50 }
51
52 const SourceLocation startLoc = decl->getBeginLoc();
53
54 for (const SourceLocation &loc : m_qobjectMacroLocations) {
55 if (sm().getFileID(loc) != sm().getFileID(startLoc)) {
56 continue; // Different file
57 }
58
59 if (sm().isBeforeInSLocAddrSpace(startLoc, loc) && sm().isBeforeInSLocAddrSpace(loc, decl->getEndLoc())) {
60 return; // We found a Q_OBJECT after start and before end, it's ours.
61 }
62 }
63
64 std::vector<FixItHint> fixits;
65 const SourceLocation pos = record->getBraceRange().getBegin().getLocWithOffset(1);
66 fixits.push_back(clazy::createInsertion(pos, "\n\tQ_OBJECT"));
67
68 const std::string fileName = sm().getFilename(startLoc).str();
69 if (clazy::endsWith(fileName, ".cpp")) {
70 const std::string basename = std::filesystem::path(fileName).stem().string();
71
72 if (!m_hasAddedMocFile && !m_context->preprocessorVisitor->hasInclude(basename + ".moc", false)) {
73 const SourceLocation pos = sm().getLocForEndOfFile(sm().getFileID(startLoc));
74 fixits.push_back(clazy::createInsertion(pos, "\n#include \"" + basename + ".moc\"\n"));
75 m_hasAddedMocFile = true;
76 }
77 }
78
79 emitWarning(startLoc, record->getQualifiedNameAsString() + " is missing a Q_OBJECT macro", fixits);
80 }
81
82 void MissingQObjectMacro::registerQ_OBJECT(SourceLocation loc)
83 {
84 m_qobjectMacroLocations.push_back(loc);
85 }