Debian Codegraph @

src/checks/level0/no-module-include.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2023 Johnny Jazeix <[email protected]>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7 #include "no-module-include.h"
8 #include "ClazyContext.h"
9 #include "PreProcessorVisitor.h"
10
11 #include <clang/Basic/LLVM.h>
12
13 #include <vector>
14
15 using namespace clang;
16
17 NoModuleInclude::NoModuleInclude(const std::string &name, Options options)
18 : CheckBase(name, options)
19 , m_modulesList{
20 "Core",
21 "Gui",
22 "Qml",
23 "QmlModels",
24 "Test",
25 "Network",
26 "DBus",
27 "Quick",
28 "Svg",
29 "Widgets",
30 "Xml",
31 "Concurrent",
32 "Multimedia",
33 "Sql",
34 "PrintSupport",
35 "NetworkAuth",
36 "QmlBuiltins",
37 "QmlIntegration",
38 "QuickTest" // Does not have an uppercase include, but we gotta live with it
39 }
40 {
41 for (const std::string &module : m_modulesList) {
42 m_filesToIgnore.emplace_back("Qt" + module + "Depends");
43 }
44 }
45
46 void NoModuleInclude::VisitInclusionDirective(clang::SourceLocation HashLoc,
47 const clang::Token & /*IncludeTok*/,
48 clang::StringRef FileName,
49 bool /*IsAngled*/,
50 clang::CharSourceRange FilenameRange,
51 clazy::OptionalFileEntryRef /*File*/,
52 clang::StringRef /*SearchPath*/,
53 clang::StringRef /*RelativePath*/,
54 const clang::Module * /*SuggestedModule*/,
55 bool /*ModuleImported*/,
56 clang::SrcMgr::CharacteristicKind /*FileType*/)
57 {
58 if (shouldIgnoreFile(HashLoc)) {
59 return;
60 }
61
62 for (const std::string &module : m_modulesList) {
63 if (module == "DBus") { // Avoid false positive for generated files
64 if (const auto fileEntry = sm().getFileEntryRefForID(sm().getFileID(HashLoc))) {
65 llvm::StringRef fileName = fileEntry->getName();
66 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileBuffer = llvm::MemoryBuffer::getFile(fileName);
67 if (fileBuffer) {
68 llvm::StringRef fileContent = fileBuffer.get()->getBuffer();
69 if (clazy::startsWith(fileContent, "/*\n * This file was generated by qdbusxml2cpp")
70 || clazy::startsWith(fileContent, "/*\r\n * This file was generated by qdbusxml2cpp")) {
71 continue;
72 }
73 }
74 }
75 }
76
77 const std::string qtModule = "Qt" + module;
78 if (FileName.str() == qtModule + "/" + qtModule || FileName.str() == qtModule) {
79 emitWarning(FilenameRange.getAsRange().getBegin(), "Module " + qtModule + " should not be included directly");
80 }
81 }
82 }