| 1 |
/* |
| 2 |
SPDX-FileCopyrightText: 2018 Sergio Martins <[email protected]> |
| 3 |
|
| 4 |
SPDX-License-Identifier: LGPL-2.0-or-later |
| 5 |
*/ |
| 6 |
|
| 7 |
#include "qrequiredresult-candidates.h" |
| 8 |
#include "QtUtils.h" |
| 9 |
#include "TypeUtils.h" |
| 10 |
#include "Utils.h" |
| 11 |
|
| 12 |
#include <clang/AST/AST.h> |
| 13 |
|
| 14 |
using namespace clang; |
| 15 |
|
| 16 |
static bool hasUnusedResultAttr(clang::FunctionDecl *func) |
| 17 |
{ |
| 18 |
auto RetType = func->getReturnType(); |
| 19 |
if (const auto *Ret = RetType->getAsRecordDecl()) { |
| 20 |
if (const auto *R = Ret->getAttr<clang::WarnUnusedResultAttr>()) { |
| 21 |
return R != nullptr; |
| 22 |
} |
| 23 |
} else if (const auto *ET = RetType->getAs<clang::EnumType>()) { |
| 24 |
if (const clang::EnumDecl *ED = ET->getDecl()) { |
| 25 |
if (const auto *R = ED->getAttr<clang::WarnUnusedResultAttr>()) { |
| 26 |
return R != nullptr; |
| 27 |
} |
| 28 |
} |
| 29 |
} |
| 30 |
return func->getAttr<clang::WarnUnusedResultAttr>() != nullptr; |
| 31 |
} |
| 32 |
|
| 33 |
void QRequiredResultCandidates::VisitDecl(clang::Decl *decl) |
| 34 |
{ |
| 35 |
auto *method = dyn_cast<CXXMethodDecl>(decl); |
| 36 |
if (!method || !method->isConst()) { |
| 37 |
return; |
| 38 |
} |
| 39 |
|
| 40 |
if (method->isThisDeclarationADefinition() && !method->hasInlineBody()) { // Don't warn twice |
| 41 |
return; |
| 42 |
} |
| 43 |
|
| 44 |
if (hasUnusedResultAttr(method)) { // Also catches nodiscard |
| 45 |
return; |
| 46 |
} |
| 47 |
|
| 48 |
if (method->getAccess() == AS_private) { // We're only interested on our public API |
| 49 |
return; |
| 50 |
} |
| 51 |
|
| 52 |
QualType qt = method->getReturnType(); |
| 53 |
CXXRecordDecl *returnClass = qt->getAsCXXRecordDecl(); |
| 54 |
returnClass = returnClass ? returnClass->getCanonicalDecl() : nullptr; |
| 55 |
if (!returnClass) { |
| 56 |
return; |
| 57 |
} |
| 58 |
|
| 59 |
CXXRecordDecl *classDecl = method->getParent(); |
| 60 |
classDecl = classDecl ? classDecl->getCanonicalDecl() : nullptr; |
| 61 |
|
| 62 |
if (classDecl == nullptr || classDecl->getAccess() == AS_private) { // A nested private class. We're only interested on our public API |
| 63 |
return; |
| 64 |
} |
| 65 |
|
| 66 |
if (returnClass == classDecl) { |
| 67 |
const std::string methodName = clazy::name(method).str(); |
| 68 |
if (methodName.empty()) { // fixes assert |
| 69 |
return; |
| 70 |
} |
| 71 |
|
| 72 |
if (clazy::startsWith(methodName, "to") || clazy::startsWith(methodName, "operator") || !clazy::endsWith(methodName, "ed")) { |
| 73 |
return; |
| 74 |
} |
| 75 |
|
| 76 |
emitWarning(decl, "Add Q_REQUIRED_RESULT to " + method->getQualifiedNameAsString() + "()"); |
| 77 |
} |
| 78 |
} |