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->getDecl())
35 if (
const auto *TemplateSpecType = Type->getAs<TemplateSpecializationType>())
36 if (
const TemplateDecl *Decl =
37 TemplateSpecType->getTemplateName().getAsTemplateDecl())
46 for (
const Decl *Decl : DS->decls()) {
47 if (
const auto *VD = dyn_cast<VarDecl>(Decl)) {
49 VD->getType().getCanonicalType().getUnqualifiedType();
51 LockGuards.push_back(VD);
62 const ast_matchers::MatchFinder::MatchResult &Result) {
67 auto AddAndClearCurrentGroup = [&]() {
68 if (!CurrentLockGuardGroup.empty()) {
69 LockGuardGroups.push_back(CurrentLockGuardGroup);
70 CurrentLockGuardGroup.clear();
74 for (
const Stmt *Stmt :
Block->body()) {
75 if (
const auto *DS = dyn_cast<DeclStmt>(Stmt)) {
78 if (!LockGuards.empty()) {
79 CurrentLockGuardGroup.append(LockGuards);
83 AddAndClearCurrentGroup();
86 AddAndClearCurrentGroup();
88 return LockGuardGroups;
93 const TypeLoc LockGuardTypeLoc = SourceInfo->getTypeLoc();
95 return {LockGuardTypeLoc.getBeginLoc(), LockGuardTypeLoc.getEndLoc()};
100 const auto TemplateLoc =
101 SourceInfo->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
105 return {TemplateLoc.getTemplateNameLoc(),
106 TemplateLoc.getLAngleLoc().getLocWithOffset(-1)};
110 "use 'std::scoped_lock' instead of 'std::lock_guard'";
115 WarnOnSingleLocks(Options.get(
"WarnOnSingleLocks", true)),
116 WarnOnUsingAndTypedef(Options.get(
"WarnOnUsingAndTypedef", true)) {}
119 Options.store(Opts,
"WarnOnSingleLocks", WarnOnSingleLocks);
120 Options.store(Opts,
"WarnOnUsingAndTypedef", WarnOnUsingAndTypedef);
124 const auto LockGuardClassDecl =
125 namedDecl(hasName(
"lock_guard"), isInStdNamespace());
127 const auto LockGuardType =
128 qualType(anyOf(hasUnqualifiedDesugaredType(
129 recordType(hasDeclaration(LockGuardClassDecl))),
130 hasUnqualifiedDesugaredType(templateSpecializationType(
131 hasDeclaration(LockGuardClassDecl)))));
133 const auto LockVarDecl = varDecl(hasType(LockGuardType));
135 if (WarnOnSingleLocks) {
138 has(declStmt(has(LockVarDecl)).bind(
"lock-decl-single")),
139 unless(has(declStmt(unless(equalsBoundNode(
"lock-decl-single")),
140 has(LockVarDecl))))),
145 compoundStmt(has(declStmt(has(LockVarDecl)).bind(
"lock-decl-multiple")),
146 has(declStmt(unless(equalsBoundNode(
"lock-decl-multiple")),
148 .bind(
"block-multiple"),
151 if (WarnOnUsingAndTypedef) {
153 Finder->addMatcher(typedefDecl(hasType(hasUnderlyingType(LockGuardType)))
154 .bind(
"lock-guard-typedef"),
158 Finder->addMatcher(typeAliasDecl(hasType(templateSpecializationType(
159 hasDeclaration(LockGuardClassDecl))))
160 .bind(
"lock-guard-using-alias"),
165 usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(LockGuardClassDecl)))
166 .bind(
"lock-guard-using-decl"),
172 if (
const auto *DS = Result.Nodes.getNodeAs<DeclStmt>(
"lock-decl-single")) {
174 diagOnMultipleLocks({Decls}, Result);
178 if (
const auto *Compound =
179 Result.Nodes.getNodeAs<CompoundStmt>(
"block-multiple")) {
184 if (
const auto *Typedef =
185 Result.Nodes.getNodeAs<TypedefDecl>(
"lock-guard-typedef")) {
186 diagOnSourceInfo(Typedef->getTypeSourceInfo(), Result);
190 if (
const auto *UsingAlias =
191 Result.Nodes.getNodeAs<TypeAliasDecl>(
"lock-guard-using-alias")) {
192 diagOnSourceInfo(UsingAlias->getTypeSourceInfo(), Result);
196 if (
const auto *Using =
197 Result.Nodes.getNodeAs<UsingDecl>(
"lock-guard-using-decl")) {
198 diagOnUsingDecl(Using, Result);
202void UseScopedLockCheck::diagOnSingleLock(
203 const VarDecl *LockGuard,
const MatchFinder::MatchResult &Result) {
206 const SourceRange LockGuardTypeRange =
209 if (LockGuardTypeRange.isInvalid())
214 const auto *CtorCall =
215 dyn_cast_if_present<CXXConstructExpr>(LockGuard->getInit());
219 if (CtorCall->getNumArgs() == 1) {
220 Diag << FixItHint::CreateReplacement(LockGuardTypeRange,
225 if (CtorCall->getNumArgs() == 2) {
226 const Expr *
const *CtorArgs = CtorCall->getArgs();
228 const Expr *MutexArg = CtorArgs[0];
229 const Expr *AdoptLockArg = CtorArgs[1];
231 const StringRef MutexSourceText = Lexer::getSourceText(
232 CharSourceRange::getTokenRange(MutexArg->getSourceRange()),
233 *Result.SourceManager, Result.Context->getLangOpts());
234 const StringRef AdoptLockSourceText = Lexer::getSourceText(
235 CharSourceRange::getTokenRange(AdoptLockArg->getSourceRange()),
236 *Result.SourceManager, Result.Context->getLangOpts());
238 Diag << FixItHint::CreateReplacement(LockGuardTypeRange,
"std::scoped_lock")
239 << FixItHint::CreateReplacement(
240 SourceRange(MutexArg->getBeginLoc(), AdoptLockArg->getEndLoc()),
241 (llvm::Twine(AdoptLockSourceText) +
", " + MutexSourceText)
246 llvm_unreachable(
"Invalid argument number of std::lock_guard constructor");
249void UseScopedLockCheck::diagOnMultipleLocks(
251 const ast_matchers::MatchFinder::MatchResult &Result) {
253 if (Group.size() == 1) {
254 if (WarnOnSingleLocks)
255 diagOnSingleLock(Group[0], Result);
257 diag(Group[0]->getBeginLoc(),
258 "use single 'std::scoped_lock' instead of multiple "
259 "'std::lock_guard'");
261 for (
const VarDecl *Lock : llvm::drop_begin(Group))
262 diag(Lock->getLocation(),
"additional 'std::lock_guard' declared here",
263 DiagnosticIDs::Note);
268void UseScopedLockCheck::diagOnSourceInfo(
269 const TypeSourceInfo *LockGuardSourceInfo,
270 const ast_matchers::MatchFinder::MatchResult &Result) {
271 const TypeLoc TL = LockGuardSourceInfo->getTypeLoc();
273 if (
const auto TTL = TL.getAs<TemplateSpecializationTypeLoc>()) {
276 const SourceRange LockGuardRange =
278 if (LockGuardRange.isInvalid())
281 Diag << FixItHint::CreateReplacement(LockGuardRange,
"scoped_lock");
285void UseScopedLockCheck::diagOnUsingDecl(
286 const UsingDecl *UsingDecl,
287 const ast_matchers::MatchFinder::MatchResult &Result) {
289 << 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 SourceRange getLockGuardNameRange(const TypeSourceInfo *SourceInfo)
static SourceRange getLockGuardRange(const TypeSourceInfo *SourceInfo)
static bool isLockGuardDecl(const NamedDecl *Decl)
static SmallVector< SmallVector< const VarDecl * > > findLocksInCompoundStmt(const CompoundStmt *Block, const ast_matchers::MatchFinder::MatchResult &Result)
static SmallVector< const VarDecl * > getLockGuardsFromDecl(const DeclStmt *DS)
static const StringRef UseScopedLockMessage
llvm::StringMap< ClangTidyValue > OptionMap