Debian Codegraph @

src/checks/level2/qstring-allocations.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 SPDX-FileCopyrightText: 2024 Alexander Lohnau <[email protected]>
7
8 SPDX-License-Identifier: LGPL-2.0-or-later
9 */
10
11 #include "qstring-allocations.h"
12 #include "ClazyContext.h"
13 #include "FixItUtils.h"
14 #include "HierarchyUtils.h"
15 #include "QtUtils.h"
16 #include "StringUtils.h"
17 #include "Utils.h"
18 #include "clazy_stl.h"
19
20 #include <clang/AST/Decl.h>
21 #include <clang/AST/DeclCXX.h>
22 #include <clang/AST/Expr.h>
23 #include <clang/AST/ExprCXX.h>
24 #include <clang/AST/Stmt.h>
25 #include <clang/AST/StmtIterator.h>
26 #include <clang/Basic/Diagnostic.h>
27 #include <clang/Basic/LLVM.h>
28 #include <clang/Basic/SourceLocation.h>
29 #include <clang/Frontend/CompilerInstance.h>
30 #include <clang/Lex/Lexer.h>
31 #include <llvm/ADT/StringRef.h>
32 #include <llvm/Support/Casting.h>
33 #include <llvm/Support/raw_ostream.h>
34
35 #include <cassert>
36 #include <utility>
37
38 using namespace clang;
39
40 inline bool hasCharPtrArgument(clang::FunctionDecl *func, int expected_arguments = -1)
41 {
42 if (expected_arguments != -1 && (int)func->param_size() != expected_arguments) {
43 return false;
44 }
45
46 for (auto *param : Utils::functionParameters(func)) {
47 if (clazy::startsWith(param->getType().getAsString(), "const char *")) { // On Qt6.8, an "&" is at the end
48 return true;
49 }
50 }
51
52 return false;
53 }
54
55 enum Fixit {
56 FixitNone = 0,
57 QLatin1StringAllocations = 0x1,
58 FromLatin1_FromUtf8Allocations = 0x2,
59 CharPtrAllocations = 0x4,
60 };
61
62 struct Latin1Expr {
63 CXXConstructExpr *qlatin1ctorexpr;
64 bool enableFixit;
65 [[nodiscard]] bool isValid() const
66 {
67 return qlatin1ctorexpr != nullptr;
68 }
69 };
70
71 void QStringAllocations::VisitStmt(clang::Stmt *stm)
72 {
73 if (m_context->isQtDeveloper() && clazy::isBootstrapping(m_context->m_pp)) {
74 // During bootstrap many QString::fromLatin1() are used instead of tr(), which causes
75 // much noise
76 return;
77 }
78
79 VisitCtor(stm);
80 VisitOperatorCall(stm);
81 VisitFromLatin1OrUtf8(stm);
82 VisitAssignOperatorQLatin1String(stm);
83 }
84
85 static bool betterTakeQLatin1String(CXXMethodDecl *method, StringLiteral *lt)
86 {
87 static const std::vector<StringRef> methods = {
88 "append",
89 "compare",
90 "endsWith",
91 "startsWith",
92 "insert",
93 "lastIndexOf",
94 "prepend",
95 "replace",
96 "contains",
97 "indexOf",
98 };
99
100 if (!clazy::isOfClass(method, "QString")) {
101 return false;
102 }
103
104 return (!lt || Utils::isAscii(lt)) && clazy::contains(methods, clazy::name(method));
105 }
106
107 // Returns the first occurrence of a QLatin1String(char*) CTOR call
108 Latin1Expr QStringAllocations::qlatin1CtorExpr(Stmt *stm, ConditionalOperator *&ternary)
109 {
110 if (!stm) {
111 return {};
112 }
113
114 auto *constructExpr = dyn_cast<CXXConstructExpr>(stm);
115 if (constructExpr) {
116 CXXConstructorDecl *ctor = constructExpr->getConstructor();
117 const int numArgs = ctor->getNumParams();
118 if (clazy::isOfClass(ctor, "QLatin1String")) {
119 if (Utils::containsStringLiteral(constructExpr, /*allowEmpty=*/false, 2)) {
120 return {constructExpr, /*enableFixits=*/numArgs == 1};
121 }
122
123 if (Utils::userDefinedLiteral(constructExpr, qtNamespaced("QLatin1String"), lo())) {
124 return {constructExpr, /*enableFixits=*/false};
125 }
126 }
127 }
128
129 // C++17 elides the QLatin1String constructor
130 if (Utils::userDefinedLiteral(stm, qtNamespaced("QLatin1String"), lo())) {
131 return {constructExpr, /*enableFixits=*/false};
132 }
133
134 if (!ternary) {
135 ternary = dyn_cast<ConditionalOperator>(stm);
136 }
137
138 for (auto *child : stm->children()) {
139 auto expr = qlatin1CtorExpr(child, ternary);
140 if (expr.isValid()) {
141 return expr;
142 }
143 }
144
145 return {};
146 }
147
148 // Returns true if there's a literal in the hierarchy, but aborts if it's parented on CallExpr
149 // so, returns true for: QLatin1String("foo") but false for QLatin1String(indirection("foo"));
150 //
151 static bool containsStringLiteralNoCallExpr(Stmt *stmt)
152 {
153 if (!stmt) {
154 return false;
155 }
156
157 auto *sl = dyn_cast<StringLiteral>(stmt);
158 if (sl) {
159 return true;
160 }
161
162 for (auto *child : stmt->children()) {
163 if (!child) {
164 continue;
165 }
166 auto *callExpr = dyn_cast<CallExpr>(child);
167 if (!callExpr && containsStringLiteralNoCallExpr(child)) {
168 return true;
169 }
170 }
171
172 return false;
173 }
174
175 // For QString::fromLatin1("foo") returns "foo"
176 static StringLiteral *stringLiteralForCall(Stmt *call)
177 {
178 if (!call) {
179 return nullptr;
180 }
181
182 std::vector<StringLiteral *> literals;
183 clazy::getChilds(call, literals, 3);
184 return literals.empty() ? nullptr : literals[0];
185 }
186
187 void QStringAllocations::VisitCtor(Stmt *stm)
188 {
189 auto *ctorExpr = dyn_cast<CXXConstructExpr>(stm);
190 if (!ctorExpr) {
191 return;
192 }
193
194 if (!Utils::containsStringLiteral(ctorExpr, /**allowEmpty=*/true)) {
195 return;
196 }
197
198 // With llvm 10, for some reason, the child CXXConstructExpr of QStringList foo = {"foo}; aren't visited :(.
199 // Do it manually.
200 if (clazy::isOfClass(ctorExpr->getConstructor(), "QStringList")
201 || ctorExpr->getConstructor()->getQualifiedNameAsString()
202 == qtNamespaced("QList<" + qtNamespaced("QString") + ">::QList")) { // In Qt6, QStringList is an alias
203 auto *p = clazy::getFirstChildOfType2<CXXConstructExpr>(ctorExpr);
204 while (p) {
205 if (clazy::isOfClass(p, "QString")) {
206 VisitCtor(p);
207 }
208 p = clazy::getFirstChildOfType2<CXXConstructExpr>(p);
209 }
210 } else {
211 VisitCtor(ctorExpr);
212 }
213 }
214
215 void QStringAllocations::VisitCtor(CXXConstructExpr *ctorExpr)
216 {
217 CXXConstructorDecl *ctorDecl = ctorExpr->getConstructor();
218 if (!clazy::isOfClass(ctorDecl, "QString")) {
219 return;
220 }
221
222 if (Utils::insideCTORCall(m_context->parentMap, ctorExpr, {"QRegExp", "QIcon"})) {
223 // https://blogs.kde.org/2015/11/05/qregexp-qstringliteral-crash-exit
224 return;
225 }
226
227 if (!isOptionSet("no-msvc-compat")) {
228 auto *initializerList = clazy::getFirstParentOfType<InitListExpr>(m_context->parentMap, ctorExpr);
229 if (initializerList != nullptr) {
230 return; // Nothing to do here, MSVC doesn't like it
231 }
232
233 StringLiteral *lt = stringLiteralForCall(ctorExpr);
234 if (lt && lt->getNumConcatenated() > 1) {
235 return; // Nothing to do here, MSVC doesn't like it
236 }
237 }
238
239 bool isQLatin1String = false;
240 std::string paramType;
241 if (hasCharPtrArgument(ctorDecl, 1)) {
242 paramType = "const char*";
243 } else if (ctorDecl->param_size() == 1
244 && (clazy::hasArgumentOfType(ctorDecl, qtNamespaced("QLatin1String"), lo())
245 || clazy::hasArgumentOfType(ctorDecl, qtNamespaced("QLatin1StringView"), lo()))) {
246 paramType = "QLatin1String";
247 isQLatin1String = true;
248 } else {
249 return;
250 }
251
252 std::string msg = std::string("QString(") + paramType + std::string(") being called");
253
254 if (isQLatin1String) {
255 ConditionalOperator *ternary = nullptr;
256 Latin1Expr qlatin1expr = qlatin1CtorExpr(ctorExpr, ternary);
257 if (!qlatin1expr.isValid()) {
258 return;
259 }
260
261 auto *qlatin1Ctor = qlatin1expr.qlatin1ctorexpr;
262
263 if (qlatin1Ctor->getBeginLoc().isMacroID()) {
264 auto macroName = Lexer::getImmediateMacroName(qlatin1Ctor->getBeginLoc(), sm(), lo());
265 if (macroName == "Q_GLOBAL_STATIC_WITH_ARGS") { // bug #391807
266 return;
267 }
268 }
269
270 std::vector<FixItHint> fixits;
271 if (qlatin1expr.enableFixit) {
272 if (!qlatin1Ctor->getBeginLoc().isMacroID()) {
273 if (!ternary) {
274 fixits = fixItReplaceWordWithWord(qlatin1Ctor, "QStringLiteral", "QLatin1String");
275 bool shouldRemoveQString = qlatin1Ctor->getBeginLoc().getRawEncoding() != ctorExpr->getBeginLoc().getRawEncoding()
276 && dyn_cast_or_null<CXXBindTemporaryExpr>(clazy::parent(m_context->parentMap, ctorExpr));
277 if (shouldRemoveQString) {
278 // This is the case of QString(QLatin1String("foo")), which we just fixed to be QString(QStringLiteral("foo")), so now remove QString
279 auto removalFixits = clazy::fixItRemoveToken(astContext(), ctorExpr, true);
280 std::ranges::copy(removalFixits, std::back_inserter(fixits));
281 }
282 } else {
283 fixits = fixItReplaceWordWithWordInTernary(ternary);
284 }
285 }
286 }
287
288 maybeEmitWarning(ctorExpr->getBeginLoc(), msg, fixits);
289 } else {
290 std::vector<FixItHint> fixits;
291 if (clazy::hasChildren(ctorExpr)) {
292 auto *pointerDecay = dyn_cast<ImplicitCastExpr>(*(ctorExpr->child_begin()));
293 if (clazy::hasChildren(pointerDecay)) {
294 auto *lt = dyn_cast<StringLiteral>(*pointerDecay->child_begin());
295 if (lt) {
296 Stmt *grandParent = clazy::parent(m_context->parentMap, lt, 2);
297 Stmt *grandGrandParent = clazy::parent(m_context->parentMap, lt, 3);
298 Stmt *grandGrandGrandParent = clazy::parent(m_context->parentMap, lt, 4);
299 if (grandParent == ctorExpr && grandGrandParent && isa<CXXBindTemporaryExpr>(grandGrandParent) && grandGrandGrandParent
300 && isa<CXXFunctionalCastExpr>(grandGrandGrandParent)) {
301 // This is the case of QString("foo"), replace QString
302
303 const bool literalIsEmpty = lt->getLength() == 0;
304 if (literalIsEmpty && clazy::getFirstParentOfType<MemberExpr>(m_context->parentMap, ctorExpr) == nullptr) {
305 fixits = fixItReplaceWordWithWord(ctorExpr, "QLatin1String", "QString");
306 } else if (!ctorExpr->getBeginLoc().isMacroID()) {
307 fixits = fixItReplaceWordWithWord(ctorExpr, "QStringLiteral", "QString");
308 }
309 } else {
310 auto *parentMemberCallExpr =
311 clazy::getFirstParentOfType<CXXMemberCallExpr>(m_context->parentMap,
312 lt,
313 /*maxDepth=*/6); // 6 seems like a nice max from the ASTs I've seen
314
315 std::string replacement = "QStringLiteral";
316 if (parentMemberCallExpr) {
317 FunctionDecl *fDecl = parentMemberCallExpr->getDirectCallee();
318 if (fDecl) {
319 auto *method = dyn_cast<CXXMethodDecl>(fDecl);
320 if (method && betterTakeQLatin1String(method, lt)) {
321 replacement = "QLatin1String";
322 }
323 }
324 }
325
326 fixits = fixItRawLiteral(lt, replacement, nullptr);
327 }
328 }
329 }
330 }
331
332 maybeEmitWarning(ctorExpr->getBeginLoc(), msg, fixits);
333 }
334 }
335
336 std::vector<FixItHint> QStringAllocations::fixItReplaceWordWithWord(clang::Stmt *begin, const std::string &replacement, const std::string &replacee)
337 {
338 StringLiteral *lt = stringLiteralForCall(begin);
339 if (replacee == "QLatin1String") {
340 if (lt && !Utils::isAscii(lt)) {
341 maybeEmitWarning(lt->getBeginLoc(), "Don't use QLatin1String with non-latin1 literals");
342 return {};
343 }
344 }
345
346 if (Utils::literalContainsEscapedBytes(lt, sm(), lo())) {
347 return {};
348 }
349
350 std::vector<FixItHint> fixits;
351 FixItHint fixit = clazy::fixItReplaceWordWithWord(astContext(), begin, replacement, replacee);
352 if (!fixit.isNull()) {
353 fixits.push_back(fixit);
354 }
355
356 return fixits;
357 }
358
359 std::vector<FixItHint> QStringAllocations::fixItReplaceWordWithWordInTernary(clang::ConditionalOperator *ternary)
360 {
361 std::vector<CXXConstructExpr *> constructExprs;
362
363 auto addConstructExpr = [&constructExprs](Expr *expr) {
364 if (auto *functionalCast = dyn_cast<CXXFunctionalCastExpr>(expr)) {
365 expr = functionalCast->getSubExpr();
366 }
367
368 if (auto *constructExpr = dyn_cast<CXXConstructExpr>(expr)) {
369 constructExprs.push_back(constructExpr);
370 }
371 };
372
373 addConstructExpr(ternary->getTrueExpr());
374 addConstructExpr(ternary->getFalseExpr());
375
376 if (constructExprs.size() != 2) {
377 llvm::errs() << "Weird ternary operator with " << constructExprs.size() << " constructExprs at " << ternary->getBeginLoc().printToString(sm()) << "\n";
378 ternary->dump();
379 assert(false);
380 return {};
381 }
382
383 std::vector<FixItHint> fixits;
384 fixits.reserve(2);
385 for (CXXConstructExpr *constructExpr : constructExprs) {
386 SourceLocation rangeStart = constructExpr->getBeginLoc();
387 SourceLocation rangeEnd = Lexer::getLocForEndOfToken(rangeStart, -1, sm(), lo());
388 fixits.push_back(FixItHint::CreateReplacement(SourceRange(rangeStart, rangeEnd), "QStringLiteral"));
389 }
390
391 return fixits;
392 }
393
394 // true for: QString::fromLatin1().arg()
395 // false for: QString::fromLatin1("")
396 // true for: QString s = QString::fromLatin1("foo")
397 // false for: s += QString::fromLatin1("foo"), etc.
398 static bool isQStringLiteralCandidate(Stmt *s, ParentMap *map, const LangOptions &lo, const SourceManager &sm, int currentCall = 0)
399 {
400 if (!s) {
401 return false;
402 }
403
404 auto *memberExpr = dyn_cast<MemberExpr>(s);
405 if (memberExpr) {
406 return true;
407 }
408
409 auto *constructExpr = dyn_cast<CXXConstructExpr>(s);
410 if (clazy::isOfClass(constructExpr, "QString")) {
411 return true;
412 }
413
414 if (Utils::isAssignOperator(dyn_cast<CXXOperatorCallExpr>(s), "QString", "QLatin1String", lo)) {
415 return true;
416 }
417
418 if (Utils::isAssignOperator(dyn_cast<CXXOperatorCallExpr>(s), "QString", "QString", lo)) {
419 return true;
420 }
421
422 auto *callExpr = dyn_cast<CallExpr>(s);
423 StringLiteral *literal = stringLiteralForCall(callExpr);
424 auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(s);
425 if (operatorCall && clazy::returnTypeName(operatorCall, lo) != "QTestData") {
426 // QTest::newRow will static_assert when using QLatin1String
427 // Q_STATIC_ASSERT_X(QMetaTypeId2<T>::Defined, "Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object
428 // system");
429
430 std::string className = clazy::classNameFor(operatorCall);
431 if (className == "QString") {
432 return false;
433 }
434 if (className.empty() && clazy::hasArgumentOfType(operatorCall->getDirectCallee(), "QString", lo)) {
435 return false;
436 }
437 }
438
439 // C++17 elides the QString constructor call in QString s = QString::fromLatin1("foo");
440 if (currentCall > 0) {
441 auto exprWithCleanups = dyn_cast<ExprWithCleanups>(s);
442 if (exprWithCleanups) {
443 if (auto bindTemp = dyn_cast<CXXBindTemporaryExpr>(exprWithCleanups->getSubExpr())) {
444 if (dyn_cast<CallExpr>(bindTemp->getSubExpr()))
445 return true;
446 }
447 }
448 }
449
450 if (currentCall > 0 && callExpr) {
451 auto *fDecl = callExpr->getDirectCallee();
452 return !(fDecl && betterTakeQLatin1String(dyn_cast<CXXMethodDecl>(fDecl), literal));
453 }
454
455 if (currentCall == 0 || dyn_cast<ImplicitCastExpr>(s) || dyn_cast<CXXBindTemporaryExpr>(s)
456 || dyn_cast<MaterializeTemporaryExpr>(s)) { // recurse over this cruft
457 return isQStringLiteralCandidate(clazy::parent(map, s), map, lo, sm, currentCall + 1);
458 }
459
460 return false;
461 }
462
463 std::vector<FixItHint> QStringAllocations::fixItReplaceFromLatin1OrFromUtf8(CallExpr *callExpr, FromFunction fromFunction)
464 {
465 std::vector<FixItHint> fixits;
466
467 std::string replacement = isQStringLiteralCandidate(callExpr, m_context->parentMap, lo(), sm()) ? "QStringLiteral" : "QLatin1String";
468 if (replacement == "QStringLiteral" && callExpr->getBeginLoc().isMacroID()) {
469 queueManualFixitWarning(callExpr->getBeginLoc(), "Can't use QStringLiteral in macro!");
470 return {};
471 }
472
473 StringLiteral *literal = stringLiteralForCall(callExpr);
474 if (literal) {
475 if (Utils::literalContainsEscapedBytes(literal, sm(), lo())) {
476 return {};
477 }
478 if (!Utils::isAscii(literal)) {
479 // QString::fromLatin1() to QLatin1String() is fine
480 // QString::fromUtf8() to QStringLiteral() is fine
481 // all other combinations are not
482 if (replacement == "QStringLiteral" && fromFunction == FromLatin1) {
483 return {};
484 }
485 if (replacement == "QLatin1String" && fromFunction == FromUtf8) {
486 replacement = "QStringLiteral";
487 }
488 }
489
490 auto classNameLoc = Lexer::getLocForEndOfToken(callExpr->getBeginLoc(), 0, sm(), lo());
491 auto scopeOperatorLoc = Lexer::getLocForEndOfToken(classNameLoc, 0, sm(), lo());
492 auto methodNameLoc = Lexer::getLocForEndOfToken(scopeOperatorLoc, -1, sm(), lo());
493 SourceRange range(callExpr->getBeginLoc(), methodNameLoc);
494 fixits.push_back(FixItHint::CreateReplacement(range, replacement));
495 }
496 return fixits;
497 }
498
499 namespace
500 {
501 // Start at <loc> and go left as long as there's whitespace, stopping at <start> in the worst case
502 SourceLocation eatLeadingWhitespace(SourceLocation start, SourceLocation loc, const SourceManager &sm, const LangOptions &lo)
503 {
504 const SourceRange range(start, loc);
505 const CharSourceRange cr = Lexer::getAsCharRange(range, sm, lo);
506 const StringRef str = Lexer::getSourceText(cr, sm, lo);
507 const int initialPos = sm.getDecomposedLoc(loc).second - sm.getDecomposedLoc(start).second;
508 int i = initialPos;
509 while (--i >= 0) {
510 if (!isHorizontalWhitespace(str[i]))
511 return loc.getLocWithOffset(i - initialPos + 1);
512 }
513 return loc;
514 }
515 }
516
517 std::vector<FixItHint> QStringAllocations::fixItRawLiteral(StringLiteral *lt, const std::string &replacement, CXXOperatorCallExpr *operatorCall)
518 {
519 std::vector<FixItHint> fixits;
520
521 SourceRange range = clazy::rangeForLiteral(astContext(), lt);
522 if (range.isInvalid()) {
523 if (lt) {
524 queueManualFixitWarning(lt->getBeginLoc(), "Internal error: Can't calculate source location");
525 }
526 return {};
527 }
528
529 SourceLocation start = lt->getBeginLoc();
530 if (!start.isMacroID()) {
531 if (Utils::literalContainsEscapedBytes(lt, sm(), lo())) {
532 return {};
533 }
534
535 // Turn str == "" into str.isEmpty()
536 if (operatorCall && operatorCall->getOperator() == OO_EqualEqual && lt->getLength() == 0) {
537 // For some reason this returns the same as getStartLoc
538 // SourceLocation start = operatorCall->getArg(0)->getEndLoc();
539 // So instead, we have to start from the "==" sign and eat whitespace to the left
540 SourceLocation start = eatLeadingWhitespace(operatorCall->getBeginLoc(), operatorCall->getExprLoc(), sm(), lo());
541 fixits.push_back(clazy::createReplacement({start, range.getEnd()}, ".isEmpty()"));
542 return fixits;
543 }
544
545 // Turn str != "" into !str.isEmpty()
546 if (operatorCall && operatorCall->getOperator() == OO_ExclaimEqual && lt->getLength() == 0) {
547 // For some reason this returns the same as getStartLoc
548 // SourceLocation start = operatorCall->getArg(0)->getEndLoc();
549 // So instead, we have to start from the "==" sign and eat whitespace to the left
550 SourceLocation start = eatLeadingWhitespace(operatorCall->getBeginLoc(), operatorCall->getExprLoc(), sm(), lo());
551 fixits.push_back(clazy::createReplacement({start, range.getEnd()}, ".isEmpty()"));
552 fixits.push_back(clazy::createInsertion(operatorCall->getBeginLoc(), "!"));
553 return fixits;
554 }
555
556 std::string revisedReplacement = lt->getLength() == 0 ? "QLatin1String" : replacement; // QLatin1String("") is better than QStringLiteral("")
557 if (revisedReplacement == "QStringLiteral" && lt->getBeginLoc().isMacroID()) {
558 return {};
559 }
560
561 clazy::insertParentMethodCall(revisedReplacement, range, /**by-ref*/ fixits);
562 }
563
564 return fixits;
565 }
566
567 void QStringAllocations::VisitOperatorCall(Stmt *stm)
568 {
569 auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(stm);
570 if (!operatorCall) {
571 return;
572 }
573
574 if (clazy::returnTypeName(operatorCall, lo()) == "QTestData") {
575 // QTest::newRow will static_assert when using QLatin1String
576 // Q_STATIC_ASSERT_X(QMetaTypeId2<T>::Defined, "Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object
577 // system");
578 return;
579 }
580
581 std::vector<StringLiteral *> stringLiterals;
582 clazy::getChilds<StringLiteral>(operatorCall, stringLiterals);
583
584 // We're only after string literals, str.contains(some_method_returning_const_char_is_fine())
585 if (stringLiterals.empty()) {
586 return;
587 }
588
589 FunctionDecl *funcDecl = operatorCall->getDirectCallee();
590 if (!funcDecl) {
591 return;
592 }
593
594 auto *methodDecl = dyn_cast<CXXMethodDecl>(funcDecl);
595 if (methodDecl && !clazy::isOfClass(methodDecl, "QString")) {
596 return;
597 }
598
599 // For Qt6.8, we have the operators in the QString class deprecated and have defined them using macros
600 // Meaning we only have a function and /not/ a method
601 if (!methodDecl && funcDecl->isThisDeclarationADefinition() && funcDecl->getBeginLoc().isValid()) {
602 StringRef fileName = sm().getFilename(sm().getExpansionLoc(funcDecl->getBeginLoc()));
603 if (!fileName.contains("qstring.h")) {
604 return;
605 }
606 }
607
608 if (!hasCharPtrArgument(funcDecl)) {
609 return;
610 }
611
612 std::vector<FixItHint> fixits;
613
614 std::vector<StringLiteral *> literals;
615 clazy::getChilds<StringLiteral>(stm, literals, 3);
616
617 if (!isOptionSet("no-msvc-compat") && !literals.empty()) {
618 if (literals[0]->getNumConcatenated() > 1) {
619 return; // Nothing to do here, MSVC doesn't like it
620 }
621 }
622
623 if (!literals.empty()) {
624 const std::string replacement = Utils::isAscii(literals[0]) ? "QLatin1String" : "QStringLiteral";
625 fixits = fixItRawLiteral(literals[0], replacement, operatorCall);
626 }
627
628 std::string msg("QString(const char*) being called");
629 maybeEmitWarning(stm->getBeginLoc(), msg, fixits);
630 }
631
632 void QStringAllocations::VisitFromLatin1OrUtf8(Stmt *stmt)
633 {
634 auto *callExpr = dyn_cast<CallExpr>(stmt);
635 if (!callExpr) {
636 return;
637 }
638
639 FunctionDecl *functionDecl = callExpr->getDirectCallee();
640 if (!clazy::functionIsOneOf(functionDecl, {"fromLatin1", "fromUtf8"})) {
641 return;
642 }
643
644 auto *methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
645 if (!clazy::isOfClass(methodDecl, "QString")) {
646 return;
647 }
648
649 bool isKnownLiteralOverload = false;
650 for (auto e : Utils::functionParameters(functionDecl)) {
651 if (e->getType().getAsString(lo()) == "QByteArrayView") {
652 isKnownLiteralOverload = true;
653 }
654 }
655 if (!isKnownLiteralOverload && (!Utils::callHasDefaultArguments(callExpr) || !hasCharPtrArgument(functionDecl, 2))) { // QString::fromLatin1("foo", 1) is ok
656 return;
657 }
658 if (!containsStringLiteralNoCallExpr(callExpr)) {
659 return;
660 }
661
662 if (!isOptionSet("no-msvc-compat")) {
663 StringLiteral *lt = stringLiteralForCall(callExpr);
664 if (lt && lt->getNumConcatenated() > 1) {
665 return; // Nothing to do here, MSVC doesn't like it
666 }
667 }
668
669 std::vector<ConditionalOperator *> ternaries;
670 clazy::getChilds(callExpr, ternaries); // In Qt5 it is always 2 levels down, but in Qt6 more
671 if (!ternaries.empty()) {
672 auto *ternary = ternaries[0];
673 if (Utils::ternaryOperatorIsOfStringLiteral(ternary)) {
674 maybeEmitWarning(stmt->getBeginLoc(), std::string("QString::fromLatin1() being passed a literal"));
675 }
676
677 return;
678 }
679
680 const FromFunction fromFunction = clazy::name(functionDecl) == "fromLatin1" ? FromLatin1 : FromUtf8;
681 const std::vector<FixItHint> fixits = fixItReplaceFromLatin1OrFromUtf8(callExpr, fromFunction);
682
683 if (clazy::name(functionDecl) == "fromLatin1") {
684 maybeEmitWarning(stmt->getBeginLoc(), std::string("QString::fromLatin1() being passed a literal"), fixits);
685 } else {
686 maybeEmitWarning(stmt->getBeginLoc(), std::string("QString::fromUtf8() being passed a literal"), fixits);
687 }
688 }
689
690 void QStringAllocations::VisitAssignOperatorQLatin1String(Stmt *stmt)
691 {
692 auto *callExpr = dyn_cast<CXXOperatorCallExpr>(stmt);
693 if (!callExpr) {
694 return;
695 }
696 if (!Utils::isAssignOperator(callExpr, "QString", qtNamespaced("QLatin1String"), lo())
697 && !Utils::isAssignOperator(callExpr, "QString", qtNamespaced("QLatin1StringView"), lo())) {
698 return;
699 }
700
701 if (!containsStringLiteralNoCallExpr(stmt)) {
702 return;
703 }
704
705 ConditionalOperator *ternary = nullptr;
706 Stmt *begin = qlatin1CtorExpr(stmt, ternary).qlatin1ctorexpr;
707
708 if (!begin) {
709 return;
710 }
711
712 const std::vector<FixItHint> fixits =
713 ternary == nullptr ? fixItReplaceWordWithWord(begin, "QStringLiteral", "QLatin1String") : fixItReplaceWordWithWordInTernary(ternary);
714
715 maybeEmitWarning(stmt->getBeginLoc(), std::string("QString::operator=(QLatin1String(\"literal\")"), fixits);
716 }
717
718 void QStringAllocations::maybeEmitWarning(SourceLocation loc, std::string error, std::vector<FixItHint> fixits)
719 {
720 if (clazy::isUIFile(loc, sm())) {
721 // Don't bother warning for generated UI files.
722 // We do the check here instead of at the beginning so users that don't use UI files don't have to pay the performance price.
723 return;
724 }
725
726 if (m_context->isQtDeveloper() && Utils::filenameForLoc(loc, sm()) == "qstring.cpp") {
727 // There's an error replacing an internal fromLatin1() because the replacement code doesn't expect to be working on QString itself
728 // not worth to fix, it's only 1 case in qstring.cpp, and related to Qt 1.x compat
729 fixits = {};
730 }
731
732 emitWarning(loc, std::move(error), fixits);
733 }