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