1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
|
//===--- UseScopedLockCheck.cpp - clang-tidy ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "UseScopedLockCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
using namespace clang::ast_matchers;
namespace clang::tidy::modernize {
static bool isLockGuardDecl(const NamedDecl *Decl) {
return Decl->getDeclName().isIdentifier() &&
Decl->getName() == "lock_guard" && Decl->isInStdNamespace();
}
static bool isLockGuard(const QualType &Type) {
if (const auto *Record = Type->getAs<RecordType>())
if (const RecordDecl *Decl = Record->getDecl())
return isLockGuardDecl(Decl);
if (const auto *TemplateSpecType = Type->getAs<TemplateSpecializationType>())
if (const TemplateDecl *Decl =
TemplateSpecType->getTemplateName().getAsTemplateDecl())
return isLockGuardDecl(Decl);
return false;
}
static llvm::SmallVector<const VarDecl *>
getLockGuardsFromDecl(const DeclStmt *DS) {
llvm::SmallVector<const VarDecl *> LockGuards;
for (const Decl *Decl : DS->decls()) {
if (const auto *VD = dyn_cast<VarDecl>(Decl)) {
const QualType Type =
VD->getType().getCanonicalType().getUnqualifiedType();
if (isLockGuard(Type))
LockGuards.push_back(VD);
}
}
return LockGuards;
}
// Scans through the statements in a block and groups consecutive
// 'std::lock_guard' variable declarations together.
static llvm::SmallVector<llvm::SmallVector<const VarDecl *>>
findLocksInCompoundStmt(const CompoundStmt *Block,
const ast_matchers::MatchFinder::MatchResult &Result) {
// store groups of consecutive 'std::lock_guard' declarations
llvm::SmallVector<llvm::SmallVector<const VarDecl *>> LockGuardGroups;
llvm::SmallVector<const VarDecl *> CurrentLockGuardGroup;
auto AddAndClearCurrentGroup = [&]() {
if (!CurrentLockGuardGroup.empty()) {
LockGuardGroups.push_back(CurrentLockGuardGroup);
CurrentLockGuardGroup.clear();
}
};
for (const Stmt *Stmt : Block->body()) {
if (const auto *DS = dyn_cast<DeclStmt>(Stmt)) {
llvm::SmallVector<const VarDecl *> LockGuards = getLockGuardsFromDecl(DS);
if (!LockGuards.empty()) {
CurrentLockGuardGroup.append(LockGuards);
continue;
}
}
AddAndClearCurrentGroup();
}
AddAndClearCurrentGroup();
return LockGuardGroups;
}
static TemplateSpecializationTypeLoc
getTemplateLockGuardTypeLoc(const TypeSourceInfo *SourceInfo) {
const TypeLoc Loc = SourceInfo->getTypeLoc();
const auto ElaboratedLoc = Loc.getAs<ElaboratedTypeLoc>();
if (!ElaboratedLoc)
return {};
return ElaboratedLoc.getNamedTypeLoc().getAs<TemplateSpecializationTypeLoc>();
}
// Find the exact source range of the 'lock_guard' token
static SourceRange getLockGuardRange(const TypeSourceInfo *SourceInfo) {
const TypeLoc LockGuardTypeLoc = SourceInfo->getTypeLoc();
return {LockGuardTypeLoc.getBeginLoc(), LockGuardTypeLoc.getEndLoc()};
}
// Find the exact source range of the 'lock_guard' name token
static SourceRange getLockGuardNameRange(const TypeSourceInfo *SourceInfo) {
const TemplateSpecializationTypeLoc TemplateLoc =
getTemplateLockGuardTypeLoc(SourceInfo);
if (!TemplateLoc)
return {};
return {TemplateLoc.getTemplateNameLoc(),
TemplateLoc.getLAngleLoc().getLocWithOffset(-1)};
}
const static StringRef UseScopedLockMessage =
"use 'std::scoped_lock' instead of 'std::lock_guard'";
UseScopedLockCheck::UseScopedLockCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
WarnOnSingleLocks(Options.get("WarnOnSingleLocks", true)),
WarnOnUsingAndTypedef(Options.get("WarnOnUsingAndTypedef", true)) {}
void UseScopedLockCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "WarnOnSingleLocks", WarnOnSingleLocks);
Options.store(Opts, "WarnOnUsingAndTypedef", WarnOnUsingAndTypedef);
}
void UseScopedLockCheck::registerMatchers(MatchFinder *Finder) {
const auto LockGuardClassDecl =
namedDecl(hasName("lock_guard"), isInStdNamespace());
const auto LockGuardType = qualType(anyOf(
hasUnqualifiedDesugaredType(
recordType(hasDeclaration(LockGuardClassDecl))),
elaboratedType(namesType(hasUnqualifiedDesugaredType(
templateSpecializationType(hasDeclaration(LockGuardClassDecl)))))));
const auto LockVarDecl = varDecl(hasType(LockGuardType));
if (WarnOnSingleLocks) {
Finder->addMatcher(
compoundStmt(
unless(isExpansionInSystemHeader()),
has(declStmt(has(LockVarDecl)).bind("lock-decl-single")),
unless(has(declStmt(unless(equalsBoundNode("lock-decl-single")),
has(LockVarDecl))))),
this);
}
Finder->addMatcher(
compoundStmt(unless(isExpansionInSystemHeader()),
has(declStmt(has(LockVarDecl)).bind("lock-decl-multiple")),
has(declStmt(unless(equalsBoundNode("lock-decl-multiple")),
has(LockVarDecl))))
.bind("block-multiple"),
this);
if (WarnOnUsingAndTypedef) {
// Match 'typedef std::lock_guard<std::mutex> Lock'
Finder->addMatcher(typedefDecl(unless(isExpansionInSystemHeader()),
hasUnderlyingType(LockGuardType))
.bind("lock-guard-typedef"),
this);
// Match 'using Lock = std::lock_guard<std::mutex>'
Finder->addMatcher(
typeAliasDecl(
unless(isExpansionInSystemHeader()),
hasType(elaboratedType(namesType(templateSpecializationType(
hasDeclaration(LockGuardClassDecl))))))
.bind("lock-guard-using-alias"),
this);
// Match 'using std::lock_guard'
Finder->addMatcher(
usingDecl(unless(isExpansionInSystemHeader()),
hasAnyUsingShadowDecl(hasTargetDecl(LockGuardClassDecl)))
.bind("lock-guard-using-decl"),
this);
}
}
void UseScopedLockCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *DS = Result.Nodes.getNodeAs<DeclStmt>("lock-decl-single")) {
llvm::SmallVector<const VarDecl *> Decls = getLockGuardsFromDecl(DS);
diagOnMultipleLocks({Decls}, Result);
return;
}
if (const auto *Compound =
Result.Nodes.getNodeAs<CompoundStmt>("block-multiple")) {
diagOnMultipleLocks(findLocksInCompoundStmt(Compound, Result), Result);
return;
}
if (const auto *Typedef =
Result.Nodes.getNodeAs<TypedefDecl>("lock-guard-typedef")) {
diagOnSourceInfo(Typedef->getTypeSourceInfo(), Result);
return;
}
if (const auto *UsingAlias =
Result.Nodes.getNodeAs<TypeAliasDecl>("lock-guard-using-alias")) {
diagOnSourceInfo(UsingAlias->getTypeSourceInfo(), Result);
return;
}
if (const auto *Using =
Result.Nodes.getNodeAs<UsingDecl>("lock-guard-using-decl")) {
diagOnUsingDecl(Using, Result);
}
}
void UseScopedLockCheck::diagOnSingleLock(
const VarDecl *LockGuard, const MatchFinder::MatchResult &Result) {
auto Diag = diag(LockGuard->getBeginLoc(), UseScopedLockMessage);
const SourceRange LockGuardTypeRange =
getLockGuardRange(LockGuard->getTypeSourceInfo());
if (LockGuardTypeRange.isInvalid())
return;
// Create Fix-its only if we can find the constructor call to properly handle
// 'std::lock_guard l(m, std::adopt_lock)' case.
const auto *CtorCall = dyn_cast<CXXConstructExpr>(LockGuard->getInit());
if (!CtorCall)
return;
if (CtorCall->getNumArgs() == 1) {
Diag << FixItHint::CreateReplacement(LockGuardTypeRange,
"std::scoped_lock");
return;
}
if (CtorCall->getNumArgs() == 2) {
const Expr *const *CtorArgs = CtorCall->getArgs();
const Expr *MutexArg = CtorArgs[0];
const Expr *AdoptLockArg = CtorArgs[1];
const StringRef MutexSourceText = Lexer::getSourceText(
CharSourceRange::getTokenRange(MutexArg->getSourceRange()),
*Result.SourceManager, Result.Context->getLangOpts());
const StringRef AdoptLockSourceText = Lexer::getSourceText(
CharSourceRange::getTokenRange(AdoptLockArg->getSourceRange()),
*Result.SourceManager, Result.Context->getLangOpts());
Diag << FixItHint::CreateReplacement(LockGuardTypeRange, "std::scoped_lock")
<< FixItHint::CreateReplacement(
SourceRange(MutexArg->getBeginLoc(), AdoptLockArg->getEndLoc()),
(llvm::Twine(AdoptLockSourceText) + ", " + MutexSourceText)
.str());
return;
}
llvm_unreachable("Invalid argument number of std::lock_guard constructor");
}
void UseScopedLockCheck::diagOnMultipleLocks(
const llvm::SmallVector<llvm::SmallVector<const VarDecl *>> &LockGroups,
const ast_matchers::MatchFinder::MatchResult &Result) {
for (const llvm::SmallVector<const VarDecl *> &Group : LockGroups) {
if (Group.size() == 1) {
if (WarnOnSingleLocks)
diagOnSingleLock(Group[0], Result);
} else {
diag(Group[0]->getBeginLoc(),
"use single 'std::scoped_lock' instead of multiple "
"'std::lock_guard'");
for (const VarDecl *Lock : llvm::drop_begin(Group))
diag(Lock->getLocation(), "additional 'std::lock_guard' declared here",
DiagnosticIDs::Note);
}
}
}
void UseScopedLockCheck::diagOnSourceInfo(
const TypeSourceInfo *LockGuardSourceInfo,
const ast_matchers::MatchFinder::MatchResult &Result) {
const TypeLoc TL = LockGuardSourceInfo->getTypeLoc();
if (const auto ElaboratedTL = TL.getAs<ElaboratedTypeLoc>()) {
auto Diag = diag(ElaboratedTL.getBeginLoc(), UseScopedLockMessage);
const SourceRange LockGuardRange =
getLockGuardNameRange(LockGuardSourceInfo);
if (LockGuardRange.isInvalid())
return;
Diag << FixItHint::CreateReplacement(LockGuardRange, "scoped_lock");
}
}
void UseScopedLockCheck::diagOnUsingDecl(
const UsingDecl *UsingDecl,
const ast_matchers::MatchFinder::MatchResult &Result) {
diag(UsingDecl->getLocation(), UseScopedLockMessage)
<< FixItHint::CreateReplacement(UsingDecl->getLocation(), "scoped_lock");
}
} // namespace clang::tidy::modernize
|