10#include "clang/AST/ASTContext.h"
11#include "clang/AST/Decl.h"
12#include "clang/AST/Stmt.h"
13#include "clang/AST/Type.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15#include "clang/ASTMatchers/ASTMatchers.h"
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Lex/Lexer.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Twine.h"
26 return Decl->getDeclName().isIdentifier() &&
27 Decl->getName() ==
"lock_guard" && Decl->isInStdNamespace();
31 if (
const auto *Record = Type->getAsCanonical<RecordType>())
32 if (
const RecordDecl *Decl = Record->getOriginalDecl())
35 if (
const auto *TemplateSpecType = Type->getAs<TemplateSpecializationType>())
36 if (
const TemplateDecl *Decl =
37 TemplateSpecType->getTemplateName().getAsTemplateDecl())
43static llvm::SmallVector<const VarDecl *>
45 llvm::SmallVector<const VarDecl *> LockGuards;
47 for (
const Decl *Decl : DS->decls()) {
48 if (
const auto *VD = dyn_cast<VarDecl>(Decl)) {
50 VD->getType().getCanonicalType().getUnqualifiedType();
52 LockGuards.push_back(VD);
61static llvm::SmallVector<llvm::SmallVector<const VarDecl *>>
63 const ast_matchers::MatchFinder::MatchResult &Result) {
65 llvm::SmallVector<llvm::SmallVector<const VarDecl *>> LockGuardGroups;
66 llvm::SmallVector<const VarDecl *> CurrentLockGuardGroup;
68 auto AddAndClearCurrentGroup = [&]() {
69 if (!CurrentLockGuardGroup.empty()) {
70 LockGuardGroups.push_back(CurrentLockGuardGroup);
71 CurrentLockGuardGroup.clear();
75 for (
const Stmt *Stmt :
Block->body()) {
76 if (
const auto *DS = dyn_cast<DeclStmt>(Stmt)) {
79 if (!LockGuards.empty()) {
80 CurrentLockGuardGroup.append(LockGuards);
84 AddAndClearCurrentGroup();
87 AddAndClearCurrentGroup();
89 return LockGuardGroups;
94 const TypeLoc LockGuardTypeLoc = SourceInfo->getTypeLoc();
96 return {LockGuardTypeLoc.getBeginLoc(), LockGuardTypeLoc.getEndLoc()};
101 const auto TemplateLoc =
102 SourceInfo->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
106 return {TemplateLoc.getTemplateNameLoc(),
107 TemplateLoc.getLAngleLoc().getLocWithOffset(-1)};
111 "use 'std::scoped_lock' instead of 'std::lock_guard'";
116 WarnOnSingleLocks(Options.get(
"WarnOnSingleLocks", true)),
117 WarnOnUsingAndTypedef(Options.get(
"WarnOnUsingAndTypedef", true)) {}
120 Options.store(Opts,
"WarnOnSingleLocks", WarnOnSingleLocks);
121 Options.store(Opts,
"WarnOnUsingAndTypedef", WarnOnUsingAndTypedef);
125 const auto LockGuardClassDecl =
126 namedDecl(hasName(
"lock_guard"), isInStdNamespace());
128 const auto LockGuardType =
129 qualType(anyOf(hasUnqualifiedDesugaredType(
130 recordType(hasDeclaration(LockGuardClassDecl))),
131 hasUnqualifiedDesugaredType(templateSpecializationType(
132 hasDeclaration(LockGuardClassDecl)))));
134 const auto LockVarDecl = varDecl(hasType(LockGuardType));
136 if (WarnOnSingleLocks) {
139 unless(isExpansionInSystemHeader()),
140 has(declStmt(has(LockVarDecl)).bind(
"lock-decl-single")),
141 unless(has(declStmt(unless(equalsBoundNode(
"lock-decl-single")),
142 has(LockVarDecl))))),
147 compoundStmt(unless(isExpansionInSystemHeader()),
148 has(declStmt(has(LockVarDecl)).bind(
"lock-decl-multiple")),
149 has(declStmt(unless(equalsBoundNode(
"lock-decl-multiple")),
151 .bind(
"block-multiple"),
154 if (WarnOnUsingAndTypedef) {
156 Finder->addMatcher(typedefDecl(unless(isExpansionInSystemHeader()),
157 hasType(hasUnderlyingType(LockGuardType)))
158 .bind(
"lock-guard-typedef"),
162 Finder->addMatcher(typeAliasDecl(unless(isExpansionInSystemHeader()),
163 hasType(templateSpecializationType(
164 hasDeclaration(LockGuardClassDecl))))
165 .bind(
"lock-guard-using-alias"),
170 usingDecl(unless(isExpansionInSystemHeader()),
171 hasAnyUsingShadowDecl(hasTargetDecl(LockGuardClassDecl)))
172 .bind(
"lock-guard-using-decl"),
178 if (
const auto *DS = Result.Nodes.getNodeAs<DeclStmt>(
"lock-decl-single")) {
180 diagOnMultipleLocks({Decls}, Result);
184 if (
const auto *Compound =
185 Result.Nodes.getNodeAs<CompoundStmt>(
"block-multiple")) {
190 if (
const auto *Typedef =
191 Result.Nodes.getNodeAs<TypedefDecl>(
"lock-guard-typedef")) {
192 diagOnSourceInfo(Typedef->getTypeSourceInfo(), Result);
196 if (
const auto *UsingAlias =
197 Result.Nodes.getNodeAs<TypeAliasDecl>(
"lock-guard-using-alias")) {
198 diagOnSourceInfo(UsingAlias->getTypeSourceInfo(), Result);
202 if (
const auto *Using =
203 Result.Nodes.getNodeAs<UsingDecl>(
"lock-guard-using-decl")) {
204 diagOnUsingDecl(Using, Result);
208void UseScopedLockCheck::diagOnSingleLock(
209 const VarDecl *LockGuard,
const MatchFinder::MatchResult &Result) {
212 const SourceRange LockGuardTypeRange =
215 if (LockGuardTypeRange.isInvalid())
220 const auto *CtorCall = dyn_cast<CXXConstructExpr>(LockGuard->getInit());
224 if (CtorCall->getNumArgs() == 1) {
225 Diag << FixItHint::CreateReplacement(LockGuardTypeRange,
230 if (CtorCall->getNumArgs() == 2) {
231 const Expr *
const *CtorArgs = CtorCall->getArgs();
233 const Expr *MutexArg = CtorArgs[0];
234 const Expr *AdoptLockArg = CtorArgs[1];
236 const StringRef MutexSourceText = Lexer::getSourceText(
237 CharSourceRange::getTokenRange(MutexArg->getSourceRange()),
238 *Result.SourceManager, Result.Context->getLangOpts());
239 const StringRef AdoptLockSourceText = Lexer::getSourceText(
240 CharSourceRange::getTokenRange(AdoptLockArg->getSourceRange()),
241 *Result.SourceManager, Result.Context->getLangOpts());
243 Diag << FixItHint::CreateReplacement(LockGuardTypeRange,
"std::scoped_lock")
244 << FixItHint::CreateReplacement(
245 SourceRange(MutexArg->getBeginLoc(), AdoptLockArg->getEndLoc()),
246 (llvm::Twine(AdoptLockSourceText) +
", " + MutexSourceText)
251 llvm_unreachable(
"Invalid argument number of std::lock_guard constructor");
254void UseScopedLockCheck::diagOnMultipleLocks(
255 const llvm::SmallVector<llvm::SmallVector<const VarDecl *>> &LockGroups,
256 const ast_matchers::MatchFinder::MatchResult &Result) {
257 for (
const llvm::SmallVector<const VarDecl *> &Group : LockGroups) {
258 if (Group.size() == 1) {
259 if (WarnOnSingleLocks)
260 diagOnSingleLock(Group[0], Result);
262 diag(Group[0]->getBeginLoc(),
263 "use single 'std::scoped_lock' instead of multiple "
264 "'std::lock_guard'");
266 for (
const VarDecl *Lock : llvm::drop_begin(Group))
267 diag(Lock->getLocation(),
"additional 'std::lock_guard' declared here",
268 DiagnosticIDs::Note);
273void UseScopedLockCheck::diagOnSourceInfo(
274 const TypeSourceInfo *LockGuardSourceInfo,
275 const ast_matchers::MatchFinder::MatchResult &Result) {
276 const TypeLoc TL = LockGuardSourceInfo->getTypeLoc();
278 if (
const auto TTL = TL.getAs<TemplateSpecializationTypeLoc>()) {
281 const SourceRange LockGuardRange =
283 if (LockGuardRange.isInvalid())
286 Diag << FixItHint::CreateReplacement(LockGuardRange,
"scoped_lock");
290void UseScopedLockCheck::diagOnUsingDecl(
291 const UsingDecl *UsingDecl,
292 const ast_matchers::MatchFinder::MatchResult &Result) {
294 << FixItHint::CreateReplacement(UsingDecl->getLocation(),
"scoped_lock");
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
UseScopedLockCheck(StringRef Name, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static bool isLockGuard(const QualType &Type)
static llvm::SmallVector< llvm::SmallVector< const VarDecl * > > findLocksInCompoundStmt(const CompoundStmt *Block, const ast_matchers::MatchFinder::MatchResult &Result)
static SourceRange getLockGuardNameRange(const TypeSourceInfo *SourceInfo)
static SourceRange getLockGuardRange(const TypeSourceInfo *SourceInfo)
static bool isLockGuardDecl(const NamedDecl *Decl)
static llvm::SmallVector< const VarDecl * > getLockGuardsFromDecl(const DeclStmt *DS)
static const StringRef UseScopedLockMessage
llvm::StringMap< ClangTidyValue > OptionMap