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 return Decl->getDeclName().isIdentifier() &&
32 Decl->getName() ==
"scoped_lock" && Decl->isInStdNamespace();
36 if (
const auto *Record = Type->getAsCanonical<RecordType>())
37 return Record->getDecl();
39 if (
const auto *TemplateSpecType = Type->getAs<TemplateSpecializationType>())
40 return TemplateSpecType->getTemplateName().getAsTemplateDecl();
60 return LockDecl->getName();
66 for (
const Decl *Decl : DS->decls()) {
67 if (
const auto *VD = dyn_cast<VarDecl>(Decl)) {
69 VD->getType().getCanonicalType().getUnqualifiedType();
71 LockGuards.push_back(VD);
82 const ast_matchers::MatchFinder::MatchResult &Result) {
87 auto AddAndClearCurrentGroup = [&]() {
88 if (!CurrentLockGuardGroup.empty()) {
89 LockGuardGroups.push_back(CurrentLockGuardGroup);
90 CurrentLockGuardGroup.clear();
94 for (
const Stmt *Stmt :
Block->body()) {
95 if (
const auto *DS = dyn_cast<DeclStmt>(Stmt)) {
98 if (!LockGuards.empty()) {
99 CurrentLockGuardGroup.append(LockGuards);
103 AddAndClearCurrentGroup();
106 AddAndClearCurrentGroup();
108 return LockGuardGroups;
113 const TypeLoc LockGuardTypeLoc = SourceInfo->getTypeLoc();
115 return {LockGuardTypeLoc.getBeginLoc(), LockGuardTypeLoc.getEndLoc()};
120 const auto TemplateLoc =
121 SourceInfo->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
125 return {TemplateLoc.getTemplateNameLoc(),
126 TemplateLoc.getLAngleLoc().getLocWithOffset(-1)};
130 "use 'std::scoped_lock' instead of 'std::lock_guard'";
135 WarnOnSingleLocks(Options.get(
"WarnOnSingleLocks", true)),
136 WarnOnUsingAndTypedef(Options.get(
"WarnOnUsingAndTypedef", true)) {}
139 Options.store(Opts,
"WarnOnSingleLocks", WarnOnSingleLocks);
140 Options.store(Opts,
"WarnOnUsingAndTypedef", WarnOnUsingAndTypedef);
144 const auto LockGuardClassDecl =
145 namedDecl(hasName(
"lock_guard"), isInStdNamespace());
146 const auto ScopedLockClassDecl =
147 namedDecl(hasName(
"scoped_lock"), isInStdNamespace());
148 const auto LockClassDecl = anyOf(LockGuardClassDecl, ScopedLockClassDecl);
150 const auto LockGuardType = qualType(hasUnqualifiedDesugaredType(
151 mapAnyOf(recordType, templateSpecializationType)
152 .with(hasDeclaration(LockGuardClassDecl))));
154 const auto LockType = qualType(hasUnqualifiedDesugaredType(
155 mapAnyOf(recordType, templateSpecializationType)
156 .with(hasDeclaration(LockClassDecl))));
158 const auto LockGuardVarDecl = varDecl(hasType(LockGuardType));
159 const auto LockVarDecl = varDecl(hasType(LockType));
161 if (WarnOnSingleLocks) {
164 has(declStmt(has(LockGuardVarDecl)).bind(
"lock-decl-single")),
165 unless(has(declStmt(unless(equalsBoundNode(
"lock-decl-single")),
166 has(LockVarDecl))))),
171 compoundStmt(has(declStmt(has(LockVarDecl)).bind(
"lock-decl-multiple")),
172 has(declStmt(unless(equalsBoundNode(
"lock-decl-multiple")),
174 .bind(
"block-multiple"),
177 if (WarnOnUsingAndTypedef) {
179 Finder->addMatcher(typedefDecl(hasType(hasUnderlyingType(LockGuardType)))
180 .bind(
"lock-guard-typedef"),
184 Finder->addMatcher(typeAliasDecl(hasType(templateSpecializationType(
185 hasDeclaration(LockGuardClassDecl))))
186 .bind(
"lock-guard-using-alias"),
191 usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(LockGuardClassDecl)))
192 .bind(
"lock-guard-using-decl"),
198 if (
const auto *DS = Result.Nodes.getNodeAs<DeclStmt>(
"lock-decl-single")) {
200 diagOnMultipleLocks({Decls}, Result);
204 if (
const auto *Compound =
205 Result.Nodes.getNodeAs<CompoundStmt>(
"block-multiple")) {
210 if (
const auto *Typedef =
211 Result.Nodes.getNodeAs<TypedefDecl>(
"lock-guard-typedef")) {
212 diagOnSourceInfo(Typedef->getTypeSourceInfo(), Result);
216 if (
const auto *UsingAlias =
217 Result.Nodes.getNodeAs<TypeAliasDecl>(
"lock-guard-using-alias")) {
218 diagOnSourceInfo(UsingAlias->getTypeSourceInfo(), Result);
222 if (
const auto *Using =
223 Result.Nodes.getNodeAs<UsingDecl>(
"lock-guard-using-decl")) {
224 diagOnUsingDecl(Using, Result);
228void UseScopedLockCheck::diagOnSingleLock(
229 const VarDecl *LockGuard,
const MatchFinder::MatchResult &Result) {
232 const SourceRange LockGuardTypeRange =
235 if (LockGuardTypeRange.isInvalid())
240 const auto *CtorCall =
241 dyn_cast_if_present<CXXConstructExpr>(LockGuard->getInit());
245 if (CtorCall->getNumArgs() == 1) {
246 Diag << FixItHint::CreateReplacement(LockGuardTypeRange,
251 if (CtorCall->getNumArgs() == 2) {
252 const Expr *
const *CtorArgs = CtorCall->getArgs();
254 const Expr *MutexArg = CtorArgs[0];
255 const Expr *AdoptLockArg = CtorArgs[1];
257 const StringRef MutexSourceText = Lexer::getSourceText(
258 CharSourceRange::getTokenRange(MutexArg->getSourceRange()),
259 *Result.SourceManager, Result.Context->getLangOpts());
260 const StringRef AdoptLockSourceText = Lexer::getSourceText(
261 CharSourceRange::getTokenRange(AdoptLockArg->getSourceRange()),
262 *Result.SourceManager, Result.Context->getLangOpts());
264 Diag << FixItHint::CreateReplacement(LockGuardTypeRange,
"std::scoped_lock")
265 << FixItHint::CreateReplacement(
266 SourceRange(MutexArg->getBeginLoc(), AdoptLockArg->getEndLoc()),
267 (llvm::Twine(AdoptLockSourceText) +
", " + MutexSourceText)
272 llvm_unreachable(
"Invalid argument number of std::lock_guard constructor");
275void UseScopedLockCheck::diagOnMultipleLocks(
277 const ast_matchers::MatchFinder::MatchResult &Result) {
279 if (Group.size() == 1) {
280 if (WarnOnSingleLocks &&
282 Group[0]->getType().getCanonicalType().getUnqualifiedType()))
283 diagOnSingleLock(Group[0], Result);
287 diag(Group[0]->getBeginLoc(),
288 "use single 'std::scoped_lock' instead of multiple locks");
290 for (
const VarDecl *Lock : llvm::drop_begin(Group)) {
291 const QualType
Type =
292 Lock->getType().getCanonicalType().getUnqualifiedType();
293 diag(Lock->getLocation(),
297 DiagnosticIDs::Note);
302void UseScopedLockCheck::diagOnSourceInfo(
303 const TypeSourceInfo *LockGuardSourceInfo,
304 const ast_matchers::MatchFinder::MatchResult &Result) {
305 const TypeLoc TL = LockGuardSourceInfo->getTypeLoc();
307 if (
const auto TTL = TL.getAs<TemplateSpecializationTypeLoc>()) {
310 const SourceRange LockGuardRange =
312 if (LockGuardRange.isInvalid())
315 Diag << FixItHint::CreateReplacement(LockGuardRange,
"scoped_lock");
319void UseScopedLockCheck::diagOnUsingDecl(
320 const UsingDecl *UsingDecl,
321 const ast_matchers::MatchFinder::MatchResult &Result) {
323 << 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
@ Type
An inlay hint that for a type annotation.
static bool isLockGuard(const QualType &Type)
static bool isScopedLockDecl(const NamedDecl *Decl)
static SourceRange getLockGuardNameRange(const TypeSourceInfo *SourceInfo)
static SourceRange getLockGuardRange(const TypeSourceInfo *SourceInfo)
static StringRef getLockClassName(const QualType &Type)
static bool isLockGuardDecl(const NamedDecl *Decl)
static SmallVector< SmallVector< const VarDecl * > > findLocksInCompoundStmt(const CompoundStmt *Block, const ast_matchers::MatchFinder::MatchResult &Result)
static const NamedDecl * getLockClassDecl(const QualType &Type)
static bool isScopedLock(const QualType &Type)
static SmallVector< const VarDecl * > getLockGuardsFromDecl(const DeclStmt *DS)
static const StringRef UseScopedLockMessage
llvm::StringMap< ClangTidyValue > OptionMap