File indexing completed on 2024-05-12 05:40:56

0001 /*
0002     SPDX-FileCopyrightText: 2016 Sergio Martins <smartins@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "mutable-container-key.h"
0008 #include "StringUtils.h"
0009 #include "Utils.h"
0010 #include "clazy_stl.h"
0011 
0012 #include <clang/AST/DeclBase.h>
0013 #include <clang/AST/DeclTemplate.h>
0014 #include <clang/AST/TemplateBase.h>
0015 #include <clang/AST/Type.h>
0016 #include <llvm/ADT/StringRef.h>
0017 
0018 #include <vector>
0019 
0020 class ClazyContext;
0021 
0022 using namespace clang;
0023 
0024 static bool isInterestingContainer(StringRef name)
0025 {
0026     static const std::vector<StringRef> containers = {"QMap", "QHash"};
0027     return clazy::contains(containers, name);
0028 }
0029 
0030 MutableContainerKey::MutableContainerKey(const std::string &name, ClazyContext *context)
0031     : CheckBase(name, context, Option_CanIgnoreIncludes)
0032 {
0033 }
0034 
0035 void MutableContainerKey::VisitDecl(clang::Decl *decl)
0036 {
0037     auto *tsdecl = Utils::templateSpecializationFromVarDecl(decl);
0038     if (!tsdecl || !isInterestingContainer(clazy::name(tsdecl))) {
0039         return;
0040     }
0041 
0042     const TemplateArgumentList &templateArguments = tsdecl->getTemplateArgs();
0043     if (templateArguments.size() != 2) {
0044         return;
0045     }
0046 
0047     QualType qt = templateArguments[0].getAsType();
0048     const Type *t = qt.getTypePtrOrNull();
0049     if (!t) {
0050         return;
0051     }
0052 
0053     auto *record = t->isRecordType() ? t->getAsCXXRecordDecl() : nullptr;
0054     if (!clazy::classIsOneOf(record, {"QPointer", "QWeakPointer", "QPersistentModelIndex", "weak_ptr"})) {
0055         return;
0056     }
0057 
0058     emitWarning(decl->getBeginLoc(), "Associative container key might be modified externally");
0059 }