Debian Codegraph @

src/Clazy.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2015 Klarälvdalens Datakonsult AB a KDAB Group company [email protected]
3 SPDX-FileContributor: Sérgio Martins <[email protected]>
4
5 SPDX-FileCopyrightText: 2015-2017 Sergio Martins <[email protected]>
6
7 SPDX-License-Identifier: LGPL-2.0-or-later
8 */
9
10 #include "Clazy.h"
11 #include "AccessSpecifierManager.h"
12 #include "ClazyVisitHelper.h"
13 #include "FixItExporter.h"
14 #include "Utils.h"
15 #include "checkbase.h"
16 #include "clazy_stl.h"
17
18 #include <algorithm>
19 #include <clang/AST/ASTConsumer.h>
20 #include <clang/AST/ASTContext.h>
21 #include <clang/AST/Decl.h>
22 #include <clang/AST/DeclBase.h>
23 #include <clang/AST/DeclCXX.h>
24 #include <clang/AST/ParentMap.h>
25 #include <clang/AST/Stmt.h>
26 #include <clang/AST/StmtCXX.h>
27 #include <clang/Basic/Diagnostic.h>
28 #include <clang/Basic/LLVM.h>
29 #include <clang/Basic/SourceLocation.h>
30 #include <clang/Basic/SourceManager.h>
31 #include <clang/Frontend/CompilerInstance.h>
32 #include <clang/Frontend/FrontendAction.h>
33 #include <clang/Frontend/FrontendPluginRegistry.h>
34 #include <llvm/Support/Casting.h>
35 #include <llvm/Support/raw_ostream.h>
36
37 #include <cstdlib>
38 #include <mutex>
39
40 using namespace clang;
41 using namespace clang::ast_matchers;
42
43 ClazyASTConsumer::ClazyASTConsumer(ClazyContext *context)
44 : m_context(context)
45 {
46 m_matchFinder = new clang::ast_matchers::MatchFinder();
47 }
48
49 void ClazyASTConsumer::addCheck(const std::pair<CheckBase *, RegisteredCheck> &check)
50 {
51 CheckBase *checkBase = check.first;
52 m_visitors.addCheck(check.second.options, checkBase);
53 checkBase->registerASTMatchers(*m_matchFinder);
54 }
55
56 ClazyASTConsumer::~ClazyASTConsumer()
57 {
58 delete m_matchFinder;
59 delete m_context;
60 }
61
62 bool ClazyASTConsumer::VisitDecl(Decl *decl)
63 {
64 return clazy::VisitHelper::VisitDecl(decl, m_context, m_visitors);
65 }
66
67 bool ClazyASTConsumer::VisitStmt(Stmt *stmt)
68 {
69 return clazy::VisitHelper::VisitStmt(stmt, m_context, m_visitors);
70 }
71
72 void ClazyASTConsumer::HandleTranslationUnit(ASTContext &ctx)
73 {
74 // FIXME: EndSourceFile() is called automatically, but not BeginsSourceFile()
75 if (m_context->exporter) {
76 m_context->exporter->BeginSourceFile(clang::LangOptions());
77 }
78
79 if ((m_context->options & ClazyContext::ClazyOption_OnlyQt) && !m_context->isQt()) {
80 return;
81 }
82
83 // Run our RecursiveAstVisitor based checks:
84 TraverseDecl(ctx.getTranslationUnitDecl());
85
86 // Run our AstMatcher base checks:
87 m_matchFinder->matchAST(ctx);
88 }
89
90 static bool parseArgument(const std::string &arg, std::vector<std::string> &args)
91 {
92 auto it = std::ranges::find(args, arg);
93 if (it != args.end()) {
94 args.erase(it);
95 return true;
96 }
97
98 return false;
99 }
100
101 ClazyASTAction::ClazyASTAction()
102 : PluginASTAction()
103 , m_checkManager(CheckManager::instance())
104 {
105 }
106
107 std::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
108 {
109 // NOTE: This method needs to be kept reentrant (but not necessarily thread-safe)
110 // Might be called from multiple threads via libclang, each thread operates on a different instance though
111
112 std::lock_guard<std::mutex> lock(CheckManager::lock());
113
114 auto astConsumer = std::make_unique<ClazyASTConsumer>(m_context);
115 for (const auto &requestedCheck : m_checks) {
116 auto *check = requestedCheck.factory();
117 check->m_context = m_context;
118 if (requestedCheck.options & RegisteredCheck::Option_PreprocessorCallbacks) {
119 check->enablePreProcessorCallbacks(ci.getPreprocessor());
120 }
121 astConsumer->addCheck({check, requestedCheck});
122 }
123
124 return std::unique_ptr<clang::ASTConsumer>(astConsumer.release());
125 }
126
127 static std::string getEnvVariable(const char *name)
128 {
129 const char *result = getenv(name);
130 if (result) {
131 return result;
132 }
133 return "";
134 }
135
136 bool ClazyASTAction::ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_)
137 {
138 // NOTE: This method needs to be kept reentrant (but not necessarily thread-safe)
139 // Might be called from multiple threads via libclang, each thread operates on a different instance though
140
141 std::vector<std::string> args = args_;
142
143 const std::string headerFilter = getEnvVariable("CLAZY_HEADER_FILTER");
144 const std::string ignoreDirs = getEnvVariable("CLAZY_IGNORE_DIRS");
145 std::string exportFixesFilename;
146
147 if (parseArgument("help", args)) {
148 m_context = new ClazyContext(&ci.getASTContext(),
149 ci.getSourceManager(),
150 ci.getASTContext().getLangOpts(),
151 ci.getPreprocessor().getPreprocessorOpts(),
152 headerFilter,
153 ignoreDirs,
154 exportFixesFilename,
155 {},
156 ClazyContext::ClazyOption_None);
157 m_context->registerPreprocessorCallbacks(ci.getPreprocessor());
158 PrintHelp(llvm::errs());
159 return true;
160 }
161
162 if (parseArgument("export-fixes", args) || getenv("CLAZY_EXPORT_FIXES")) {
163 m_options |= ClazyContext::ClazyOption_ExportFixes;
164 }
165
166 if (parseArgument("only-qt", args)) {
167 m_options |= ClazyContext::ClazyOption_OnlyQt;
168 }
169
170 if (parseArgument("qt-developer", args)) {
171 m_options |= ClazyContext::ClazyOption_QtDeveloper;
172 }
173
174 if (parseArgument("visit-implicit-code", args)) {
175 m_options |= ClazyContext::ClazyOption_VisitImplicitCode;
176 }
177
178 if (parseArgument("ignore-included-files", args)) {
179 m_options |= ClazyContext::ClazyOption_IgnoreIncludedFiles;
180 }
181
182 if (parseArgument("export-fixes", args)) {
183 exportFixesFilename = args.at(0);
184 }
185
186 m_context = new ClazyContext(&ci.getASTContext(),
187 ci.getSourceManager(),
188 ci.getASTContext().getLangOpts(),
189 ci.getPreprocessor().getPreprocessorOpts(),
190 headerFilter,
191 ignoreDirs,
192 exportFixesFilename,
193 {},
194 m_options);
195 m_context->registerPreprocessorCallbacks(ci.getPreprocessor());
196
197 // This argument is for debugging purposes
198 const bool dbgPrintRequestedChecks = parseArgument("print-requested-checks", args);
199
200 {
201 std::lock_guard<std::mutex> lock(CheckManager::lock());
202 m_checks = m_checkManager->requestedChecks(args);
203 }
204
205 if (args.size() > 1) {
206 // Too many arguments.
207 llvm::errs() << "Too many arguments: ";
208 for (const std::string &a : args) {
209 llvm::errs() << a << ' ';
210 }
211 llvm::errs() << "\n";
212
213 PrintHelp(llvm::errs());
214 return false;
215 }
216 if (args.size() == 1 && m_checks.empty()) {
217 // Checks were specified but couldn't be found
218 llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
219 PrintHelp(llvm::errs());
220 return false;
221 }
222
223 if (dbgPrintRequestedChecks) {
224 printRequestedChecks();
225 }
226
227 return true;
228 }
229
230 void ClazyASTAction::printRequestedChecks() const
231 {
232 llvm::errs() << "Requested checks: ";
233 const unsigned int numChecks = m_checks.size();
234 for (unsigned int i = 0; i < numChecks; ++i) {
235 llvm::errs() << m_checks.at(i).name;
236 const bool isLast = i == numChecks - 1;
237 if (!isLast) {
238 llvm::errs() << ", ";
239 }
240 }
241
242 llvm::errs() << "\n";
243 }
244
245 void ClazyASTAction::PrintHelp(llvm::raw_ostream &ros) const
246 {
247 std::lock_guard<std::mutex> lock(CheckManager::lock());
248 RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);
249
250 std::ranges::sort(checks, checkLessThanByLevel);
251
252 ros << "Available checks and FixIts:\n\n";
253
254 int lastPrintedLevel = -1;
255 const auto numChecks = checks.size();
256 for (unsigned int i = 0; i < numChecks; ++i) {
257 const RegisteredCheck &check = checks[i];
258 const std::string levelStr = "level" + std::to_string(check.level);
259 if (lastPrintedLevel < check.level) {
260 lastPrintedLevel = check.level;
261
262 if (check.level > 0) {
263 ros << "\n";
264 }
265
266 ros << "- Checks from " << levelStr << ":\n";
267 }
268
269 auto padded = check.name;
270 padded.insert(padded.end(), 39 - padded.size(), ' ');
271 ros << " - " << check.name;
272 ;
273 auto fixits = m_checkManager->availableFixIts(check.name);
274 if (!fixits.empty()) {
275 ros << " (";
276 bool isFirst = true;
277 for (const auto &fixit : fixits) {
278 if (isFirst) {
279 isFirst = false;
280 } else {
281 ros << ',';
282 }
283
284 ros << fixit.name;
285 }
286 ros << ')';
287 }
288 ros << "\n";
289 }
290 ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n";
291 ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
292 ros << " export CLAZY_CHECKS=\"level0\"\n";
293 ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n";
294 ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n";
295 ros << "or pass as compiler arguments, for example:\n";
296 ros << " -Xclang -plugin-arg-clazy -Xclang reserve-candidates,qstring-allocations\n";
297 ros << "\n";
298 }
299
300 ClazyStandaloneASTAction::ClazyStandaloneASTAction(const std::string &checkList,
301 const std::string &headerFilter,
302 const std::string &ignoreDirs,
303 const std::string &exportFixesFilename,
304 const std::vector<std::string> &translationUnitPaths,
305 ClazyContext::ClazyOptions options)
306 : m_checkList(checkList.empty() ? "level1" : checkList)
307 , m_headerFilter(headerFilter.empty() ? getEnvVariable("CLAZY_HEADER_FILTER") : headerFilter)
308 , m_ignoreDirs(ignoreDirs.empty() ? getEnvVariable("CLAZY_IGNORE_DIRS") : ignoreDirs)
309 , m_exportFixesFilename(exportFixesFilename)
310 , m_translationUnitPaths(translationUnitPaths)
311 , m_options(options)
312 {
313 }
314
315 std::unique_ptr<ASTConsumer> ClazyStandaloneASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
316 {
317 auto *cm = CheckManager::instance();
318
319 std::vector<std::string> checks;
320 checks.push_back(m_checkList);
321 const RegisteredCheck::List requestedChecks = cm->requestedChecks(checks);
322
323 if (requestedChecks.empty()) {
324 llvm::errs() << "No checks were requested!\n\n";
325 return nullptr;
326 }
327
328 auto *context = new ClazyContext(&ci.getASTContext(),
329 ci.getSourceManager(),
330 ci.getASTContext().getLangOpts(),
331 ci.getPreprocessor().getPreprocessorOpts(),
332 m_headerFilter,
333 m_ignoreDirs,
334 m_exportFixesFilename,
335 m_translationUnitPaths,
336 m_options);
337 context->registerPreprocessorCallbacks(ci.getPreprocessor());
338 auto *astConsumer = new ClazyASTConsumer(context);
339
340 for (const auto &requestedCheck : requestedChecks) {
341 auto *check = requestedCheck.factory();
342 check->m_context = context;
343 if (requestedCheck.options & RegisteredCheck::Option_PreprocessorCallbacks) {
344 check->enablePreProcessorCallbacks(ci.getPreprocessor());
345 }
346 astConsumer->addCheck({check, requestedCheck});
347 }
348
349 return std::unique_ptr<ASTConsumer>(astConsumer);
350 }
351
352 volatile int ClazyPluginAnchorSource = 0;
353
354 static FrontendPluginRegistry::Add<ClazyASTAction> X("clazy", "clang lazy plugin");