Debian Codegraph @

src/checks/level2/old-style-connect.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 Sergio Martins <[email protected]>
6
7 SPDX-License-Identifier: LGPL-2.0-or-later
8 */
9
10 #include "old-style-connect.h"
11 #include "AccessSpecifierManager.h"
12 #include "ClazyContext.h"
13 #include "ContextUtils.h"
14 #include "FixItUtils.h"
15 #include "HierarchyUtils.h"
16 #include "QtUtils.h"
17 #include "StringUtils.h"
18 #include "Utils.h"
19
20 #include <clang/AST/Decl.h>
21 #include <clang/AST/DeclBase.h>
22 #include <clang/AST/DeclCXX.h>
23 #include <clang/AST/Expr.h>
24 #include <clang/AST/ExprCXX.h>
25 #include <clang/AST/Stmt.h>
26 #include <clang/AST/Type.h>
27 #include <clang/Basic/Diagnostic.h>
28 #include <clang/Basic/IdentifierTable.h>
29 #include <clang/Basic/LLVM.h>
30 #include <clang/Basic/SourceManager.h>
31 #include <clang/Basic/TokenKinds.h>
32 #include <clang/Lex/Lexer.h>
33 #include <clang/Lex/Token.h>
34 #include <llvm/ADT/StringRef.h>
35 #include <llvm/Support/Casting.h>
36 #include <llvm/Support/raw_ostream.h>
37
38 #include <regex>
39
40 using namespace clang;
41
42 namespace clazy
43 {
44 // Copied from Clang's Expr.cpp and added "|| !DerivedType->isRecordType()" to avoid a crash
45 const CXXRecordDecl *getBestDynamicClassType(Expr *expr)
46 {
47 if (!expr) {
48 return nullptr;
49 }
50
51 const Expr *E = expr->getBestDynamicClassTypeExpr();
52 QualType DerivedType = E->getType();
53 if (const auto *PTy = DerivedType->getAs<PointerType>()) {
54 DerivedType = PTy->getPointeeType();
55 }
56
57 if (DerivedType->isDependentType() || !DerivedType->isRecordType()) {
58 return nullptr;
59 }
60
61 const RecordType *Ty = DerivedType->castAs<RecordType>();
62 Decl *D = Ty->getDecl();
63 return cast<CXXRecordDecl>(D);
64 }
65 }
66
67 enum ConnectFlag {
68 ConnectFlag_None = 0, // Not a disconnect or connect
69 ConnectFlag_Connect = 1, // It's a connect
70 ConnectFlag_Disconnect = 2, // It's a disconnect
71 ConnectFlag_QTimerSingleShot = 4,
72 ConnectFlag_OldStyle = 8, // Qt4 style
73 ConnectFlag_4ArgsDisconnect = 16, // disconnect(const char *signal = 0, const QObject *receiver = 0, const char *method = 0) const
74 ConnectFlag_3ArgsDisconnect = 32, // disconnect(SIGNAL(foo))
75 ConnectFlag_2ArgsDisconnect = 64, // disconnect(const QObject *receiver, const char *method = 0) const
76 ConnectFlag_5ArgsConnect =
77 128, // connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
78 ConnectFlag_4ArgsConnect = 256, // connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
79 ConnectFlag_OldStyleButNonLiteral = 0x200, // connect(foo, SIGNAL(bar()), foo, variableWithSlotName); // here the slot name isn't a literal
80 ConnectFlag_QStateAddTransition = 0x400,
81 ConnectFlag_QMenuAddAction = 0x800,
82 ConnectFlag_QMessageBoxOpen = 0x1000,
83 ConnectFlag_QSignalSpy = 0x2000,
84 ConnectFlag_Bogus = 0x4000,
85 };
86
87 static bool classIsOk(StringRef className)
88 {
89 // List of classes we usually use Qt4 syntax
90 return className != "QDBusInterface";
91 }
92
93 template<typename T>
94 int OldStyleConnect::classifyConnect(FunctionDecl *connectFunc, T *connectCall) const
95 {
96 int classification = ConnectFlag_None;
97
98 std::string methodName = trimQtNamespace(connectFunc->getQualifiedNameAsString());
99 if (methodName == "QObject::connect") {
100 classification |= ConnectFlag_Connect;
101 } else if (methodName == "QObject::disconnect") {
102 classification |= ConnectFlag_Disconnect;
103 } else if (methodName == "QTimer::singleShot") {
104 classification |= ConnectFlag_QTimerSingleShot;
105 } else if (methodName == "QState::addTransition") {
106 classification |= ConnectFlag_QStateAddTransition;
107 } else if (methodName == "QMenu::addAction" || methodName == "QWidget::addAction") {
108 classification |= ConnectFlag_QMenuAddAction;
109 } else if (methodName == "QMessageBox::open") {
110 classification |= ConnectFlag_QMessageBoxOpen;
111 } else if (methodName == "QSignalSpy::QSignalSpy") {
112 classification |= ConnectFlag_QSignalSpy;
113 }
114
115 if (classification == ConnectFlag_None) {
116 return classification;
117 }
118
119 if (clazy::connectHasPMFStyle(connectFunc)) {
120 return classification;
121 }
122 classification |= ConnectFlag_OldStyle;
123
124 const unsigned int numParams = connectFunc->getNumParams();
125
126 if (classification & ConnectFlag_Connect) {
127 if (numParams == 5) {
128 classification |= ConnectFlag_5ArgsConnect;
129 } else if (numParams == 4) {
130 classification |= ConnectFlag_4ArgsConnect;
131 } else {
132 classification |= ConnectFlag_Bogus;
133 }
134 } else if (classification & ConnectFlag_Disconnect) {
135 if (numParams == 4) {
136 classification |= ConnectFlag_4ArgsDisconnect;
137 } else if (numParams == 3) {
138 classification |= ConnectFlag_3ArgsDisconnect;
139 } else if (numParams == 2) {
140 classification |= ConnectFlag_2ArgsDisconnect;
141 } else {
142 classification |= ConnectFlag_Bogus;
143 }
144 }
145
146 if (classification & ConnectFlag_OldStyle) {
147 // It's old style, but check if all macros are literals
148 int numLiterals = 0;
149 for (auto arg : connectCall->arguments()) {
150 auto argLocation = arg->getBeginLoc();
151 std::string dummy;
152 if (isSignalOrSlot(argLocation, dummy)) {
153 ++numLiterals;
154 }
155 }
156
157 if ((classification & ConnectFlag_QTimerSingleShot) && numLiterals != 1) {
158 classification |= ConnectFlag_OldStyleButNonLiteral;
159 } else if (((classification & ConnectFlag_Connect) && numLiterals != 2)) {
160 classification |= ConnectFlag_OldStyleButNonLiteral;
161 } else if ((classification & ConnectFlag_4ArgsDisconnect) && numLiterals != 2) {
162 classification |= ConnectFlag_OldStyleButNonLiteral;
163 } else if ((classification & ConnectFlag_QStateAddTransition) && numLiterals != 1) {
164 classification |= ConnectFlag_OldStyleButNonLiteral;
165 } else if ((classification & ConnectFlag_Disconnect) && numLiterals == 0) {
166 classification |= ConnectFlag_OldStyleButNonLiteral;
167 } else if ((classification & ConnectFlag_QMenuAddAction) && numLiterals != 1) {
168 classification |= ConnectFlag_OldStyleButNonLiteral;
169 } else if ((classification & ConnectFlag_QMessageBoxOpen) && numLiterals != 1) {
170 classification |= ConnectFlag_OldStyleButNonLiteral;
171 } else if ((classification & ConnectFlag_QSignalSpy) && numLiterals != 1) {
172 classification |= ConnectFlag_OldStyleButNonLiteral;
173 }
174 }
175
176 return classification;
177 }
178
179 bool OldStyleConnect::isQPointer(Expr *expr) const
180 {
181 std::vector<CXXMemberCallExpr *> memberCalls;
182 clazy::getChilds<CXXMemberCallExpr>(expr, memberCalls);
183
184 return std::ranges::any_of(memberCalls, [](CXXMemberCallExpr *callExpr) {
185 auto *callee = callExpr->getDirectCallee();
186 return callee && dyn_cast<CXXConversionDecl>(callee);
187 });
188 }
189
190 bool OldStyleConnect::isPrivateSlot(const std::string &name) const
191 {
192 return std::ranges::any_of(m_privateSlots, [name](const PrivateSlot &slot) {
193 return slot.name == name;
194 });
195 }
196
197 void OldStyleConnect::VisitStmt(Stmt *s)
198 {
199 auto *call = dyn_cast<CallExpr>(s);
200 auto *ctorExpr = call ? nullptr : dyn_cast<CXXConstructExpr>(s);
201 if (!call && !ctorExpr) {
202 return;
203 }
204
205 if (m_context->lastMethodDecl && m_context->isQtDeveloper() && m_context->lastMethodDecl->getParent()
206 && clazy::name(m_context->lastMethodDecl->getParent()) == "QObject") { // Don't warn of stuff inside qobject.h
207 return;
208 }
209
210 FunctionDecl *function = call ? call->getDirectCallee() : ctorExpr->getConstructor();
211 if (!function) {
212 return;
213 }
214
215 auto *method = dyn_cast<CXXMethodDecl>(function);
216 if (!method) {
217 return;
218 }
219
220 const int classification = call ? classifyConnect(method, call) : classifyConnect(method, ctorExpr);
221
222 if (!(classification & ConnectFlag_OldStyle)) {
223 return;
224 }
225
226 if ((classification & ConnectFlag_OldStyleButNonLiteral)) {
227 return;
228 }
229
230 if (classification & ConnectFlag_Bogus) {
231 emitWarning(s->getBeginLoc(), "Internal error");
232 return;
233 }
234
235 emitWarning(s->getBeginLoc(), "Old Style Connect", call ? fixits(classification, call) : fixits(classification, ctorExpr));
236 }
237
238 void OldStyleConnect::addPrivateSlot(const PrivateSlot &slot)
239 {
240 m_privateSlots.push_back(slot);
241 }
242
243 void OldStyleConnect::VisitMacroExpands(const Token &macroNameTok, const SourceRange &range, const MacroInfo *)
244 {
245 IdentifierInfo *ii = macroNameTok.getIdentifierInfo();
246 if (!ii || ii->getName() != "Q_PRIVATE_SLOT") {
247 return;
248 }
249
250 auto charRange = Lexer::getAsCharRange(range, sm(), lo());
251 const std::string text = Lexer::getSourceText(charRange, sm(), lo()).str();
252
253 static std::regex rx(R"(Q_PRIVATE_SLOT\s*\((.*),.*\s(.*)\(.*)");
254 std::smatch match;
255 if (!regex_match(text, match, rx) || match.size() != 3) {
256 return;
257 }
258
259 addPrivateSlot({match[1], match[2]});
260 }
261
262 // SIGNAL(foo()) -> foo
263 std::string OldStyleConnect::signalOrSlotNameFromMacro(SourceLocation macroLoc)
264 {
265 if (!macroLoc.isMacroID()) {
266 return "error";
267 }
268
269 CharSourceRange expansionRange = sm().getImmediateExpansionRange(macroLoc);
270 SourceRange range = SourceRange(expansionRange.getBegin(), expansionRange.getEnd());
271 auto charRange = Lexer::getAsCharRange(range, sm(), lo());
272 const std::string text = Lexer::getSourceText(charRange, sm(), lo()).str();
273
274 static std::regex rx(R"(\s*(SIGNAL|SLOT)\s*\(\s*(.+)\s*\(.*)");
275
276 std::smatch match;
277 if (regex_match(text, match, rx)) {
278 if (match.size() == 3) {
279 return match[2].str();
280 }
281 return "error2";
282
283 } else {
284 return std::string("regexp failed for ") + text;
285 }
286 }
287
288 bool OldStyleConnect::isSignalOrSlot(SourceLocation loc, std::string &macroName) const
289 {
290 macroName.clear();
291 if (!loc.isMacroID() || loc.isInvalid()) {
292 return false;
293 }
294
295 macroName = Lexer::getImmediateMacroName(loc, sm(), lo()).str();
296 return macroName == "SIGNAL" || macroName == "SLOT";
297 }
298
299 template<typename T>
300 std::vector<FixItHint> OldStyleConnect::fixits(int classification, T *callOrCtor)
301 {
302 if (!callOrCtor) {
303 llvm::errs() << "Call is invalid\n";
304 return {};
305 }
306
307 const SourceLocation locStart = callOrCtor->getBeginLoc();
308
309 if (classification & ConnectFlag_2ArgsDisconnect) {
310 // Not implemented yet
311 std::string msg = "Fix it not implemented for disconnect with 2 args";
312 queueManualFixitWarning(locStart, msg);
313 return {};
314 }
315
316 if (classification & ConnectFlag_3ArgsDisconnect) {
317 // Not implemented yet
318 std::string msg = "Fix it not implemented for disconnect with 3 args";
319 queueManualFixitWarning(locStart, msg);
320 return {};
321 }
322
323 if (classification & ConnectFlag_QMessageBoxOpen) {
324 std::string msg = "Fix it not implemented for QMessageBox::open()";
325 queueManualFixitWarning(locStart, msg);
326 return {};
327 }
328
329 std::vector<FixItHint> fixits;
330 int macroNum = 0;
331 std::string implicitCallee;
332 std::string macroName;
333 CXXMethodDecl *senderMethod = nullptr;
334 for (auto arg : callOrCtor->arguments()) {
335 SourceLocation s = arg->getBeginLoc();
336 static const CXXRecordDecl *lastRecordDecl = nullptr;
337 if (isSignalOrSlot(s, macroName)) {
338 macroNum++;
339 if (!lastRecordDecl && (classification & ConnectFlag_4ArgsConnect)) {
340 // This means it's a connect with implicit receiver
341 lastRecordDecl = Utils::recordForMemberCall(dyn_cast<CXXMemberCallExpr>(callOrCtor), implicitCallee);
342
343 if (macroNum == 1) {
344 llvm::errs() << "This first macro shouldn't enter this path";
345 }
346 if (!lastRecordDecl) {
347 std::string msg = "Failed to get class name for implicit receiver";
348 queueManualFixitWarning(s, msg);
349 return {};
350 }
351 }
352
353 if (!lastRecordDecl || !lastRecordDecl->hasDefinition()) {
354 std::string msg = "Failed to get class name for explicit receiver";
355 queueManualFixitWarning(s, msg);
356 return {};
357 }
358
359 const std::string methodName = signalOrSlotNameFromMacro(s);
360
361 // With LLVM22, we need to explicitly ask for the definition
362 auto methods = Utils::methodsFromString(lastRecordDecl->getDefinition(), methodName);
363 if (methods.empty()) {
364 std::string msg;
365 if (isPrivateSlot(methodName)) {
366 msg = "Converting Q_PRIVATE_SLOTS not implemented yet\n";
367 } else {
368 if (m_context->isQtDeveloper() && classIsOk(clazy::name(lastRecordDecl))) {
369 // This is OK
370 return {};
371 }
372 msg = "No such method " + methodName + " in class " + lastRecordDecl->getNameAsString();
373 }
374
375 queueManualFixitWarning(s, msg);
376 return {};
377 }
378 if (methods.size() != 1) {
379 std::string msg = std::string("Too many overloads (") + std::to_string(methods.size()) + std::string(") for method ") + methodName
380 + " for record " + lastRecordDecl->getNameAsString();
381 queueManualFixitWarning(s, msg);
382 return {};
383 } else {
384 AccessSpecifierManager *a = m_context->accessSpecifierManager;
385 if (!a) {
386 return {};
387 }
388 const bool isSignal = a->qtAccessSpecifierType(methods[0]) == QtAccessSpecifier_Signal;
389 if (isSignal && macroName == "SLOT") {
390 // The method is actually a signal and the user used SLOT()
391 // bail out with the fixing.
392 std::string msg = std::string("Can't fix. SLOT macro used but method " + methodName + " is a signal");
393 queueManualFixitWarning(s, msg);
394 return {};
395 }
396 }
397
398 auto *methodDecl = methods[0];
399 if (methodDecl->isStatic()) {
400 return {};
401 }
402
403 if (macroNum == 1) {
404 // Save the number of parameters of the signal. The slot should not have more arguments.
405 senderMethod = methodDecl;
406 } else if (macroNum == 2) {
407 const unsigned int numReceiverParams = methodDecl->getNumParams();
408 if (numReceiverParams > senderMethod->getNumParams()) {
409 std::string msg = std::string("Receiver has more parameters (") + std::to_string(methodDecl->getNumParams()) + ") than signal ("
410 + std::to_string(senderMethod->getNumParams()) + ')';
411 queueManualFixitWarning(s, msg);
412 return {};
413 }
414
415 for (unsigned int i = 0; i < numReceiverParams; ++i) {
416 ParmVarDecl *receiverParm = methodDecl->getParamDecl(i);
417 ParmVarDecl *senderParm = senderMethod->getParamDecl(i);
418 if (!clazy::isConvertibleTo(senderParm->getType().getTypePtr(), receiverParm->getType().getTypePtrOrNull())) {
419 std::string msg("Sender's parameters are incompatible with the receiver's");
420 queueManualFixitWarning(s, msg);
421 return {};
422 }
423 }
424 }
425
426 if ((classification & ConnectFlag_QTimerSingleShot) && methodDecl->getNumParams() > 0) {
427 std::string msg = "(QTimer) Fixit not implemented for slot with arguments, use a lambda";
428 queueManualFixitWarning(s, msg);
429 return {};
430 }
431
432 if ((classification & ConnectFlag_QMenuAddAction) && methodDecl->getNumParams() > 0) {
433 std::string msg = "(QMenu) Fixit not implemented for slot with arguments, use a lambda";
434 queueManualFixitWarning(s, msg);
435 return {};
436 }
437
438 DeclContext *context = m_context->lastDecl->getDeclContext();
439
440 bool isSpecialProtectedCase = false;
441 if (!clazy::canTakeAddressOf(methodDecl, context, /*by-ref*/ isSpecialProtectedCase)) {
442 std::string msg = "Can't fix " + clazy::accessString(methodDecl->getAccess()) + ' ' + macroName + ' ' + methodDecl->getQualifiedNameAsString();
443 queueManualFixitWarning(s, msg);
444 return {};
445 }
446
447 std::string qualifiedName;
448 auto *contextRecord = clazy::firstContextOfType<CXXRecordDecl>(m_context->lastDecl->getDeclContext());
449 const bool isInInclude = sm().getMainFileID() != sm().getFileID(locStart);
450
451 if (isSpecialProtectedCase && contextRecord) {
452 // We're inside a derived class trying to take address of a protected base member, must use &Derived::method instead of &Base::method.
453 qualifiedName = contextRecord->getNameAsString() + "::" + methodDecl->getNameAsString();
454 } else {
455 qualifiedName = clazy::getMostNeededQualifiedName(sm(), methodDecl, context, locStart, !isInInclude); // (In includes ignore using directives)
456 }
457
458 CharSourceRange expansionRange = sm().getImmediateExpansionRange(s);
459 SourceRange range = SourceRange(expansionRange.getBegin(), expansionRange.getEnd());
460
461 const std::string functionPointer = '&' + qualifiedName;
462 std::string replacement = functionPointer;
463
464 if ((classification & ConnectFlag_4ArgsConnect) && macroNum == 2) {
465 replacement = implicitCallee + ", " + replacement;
466 }
467
468 fixits.push_back(FixItHint::CreateReplacement(range, replacement));
469 lastRecordDecl = nullptr;
470 } else {
471 Expr *expr = arg;
472 const auto *const record = clazy::getBestDynamicClassType(expr);
473 if (record) {
474 lastRecordDecl = record;
475 if (isQPointer(expr)) {
476 auto endLoc = clazy::locForNextToken(astContext(), arg->getBeginLoc(), tok::comma);
477 if (endLoc.isValid()) {
478 fixits.push_back(FixItHint::CreateInsertion(endLoc, ".data()"));
479 } else {
480 return {};
481 }
482 }
483 }
484 }
485 }
486
487 return fixits;
488 }