Skip to content

Commit b6f6be4

Browse files
committed
[clang-tidy][NFC] Remove duplicated code
Remove duplicated matchers by moving some of them to utils/Matchers.h. Add some anonymous namespaces and renamed some code to avoid ODR issues.
1 parent d12e45a commit b6f6be4

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+298
-288
lines changed

clang-tools-extra/clang-tidy/abseil/AbseilMatcher.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
//
77
//===----------------------------------------------------------------------===//
88

9+
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H
10+
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H
11+
912
#include "clang/AST/ASTContext.h"
1013
#include "clang/ASTMatchers/ASTMatchFinder.h"
1114
#include <algorithm>
@@ -57,3 +60,5 @@ AST_POLYMORPHIC_MATCHER(
5760
}
5861

5962
} // namespace clang::ast_matchers
63+
64+
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H

clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "DurationFactoryFloatCheck.h"
10+
#include "../utils/LexerUtils.h"
1011
#include "DurationRewriter.h"
1112
#include "clang/AST/ASTContext.h"
1213
#include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -18,15 +19,6 @@ using namespace clang::ast_matchers;
1819

1920
namespace clang::tidy::abseil {
2021

21-
// Returns `true` if `Range` is inside a macro definition.
22-
static bool insideMacroDefinition(const MatchFinder::MatchResult &Result,
23-
SourceRange Range) {
24-
return !clang::Lexer::makeFileCharRange(
25-
clang::CharSourceRange::getCharRange(Range),
26-
*Result.SourceManager, Result.Context->getLangOpts())
27-
.isValid();
28-
}
29-
3022
void DurationFactoryFloatCheck::registerMatchers(MatchFinder *Finder) {
3123
Finder->addMatcher(
3224
callExpr(callee(functionDecl(DurationFactoryFunction())),
@@ -45,7 +37,9 @@ void DurationFactoryFloatCheck::check(const MatchFinder::MatchResult &Result) {
4537
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>("call");
4638

4739
// Don't try and replace things inside of macro definitions.
48-
if (insideMacroDefinition(Result, MatchedCall->getSourceRange()))
40+
if (tidy::utils::lexer::insideMacroDefinition(MatchedCall->getSourceRange(),
41+
*Result.SourceManager,
42+
Result.Context->getLangOpts()))
4943
return;
5044

5145
const Expr *Arg = MatchedCall->getArg(0)->IgnoreImpCasts();

clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,15 @@ using ::clang::transformer::makeRule;
3030
using ::clang::transformer::node;
3131
using ::clang::transformer::RewriteRuleWith;
3232

33+
namespace {
34+
3335
AST_MATCHER(Type, isCharType) { return Node.isCharType(); }
36+
} // namespace
3437

35-
static const char DefaultStringLikeClasses[] = "::std::basic_string;"
38+
static const char StringLikeClassesDefault[] = "::std::basic_string;"
3639
"::std::basic_string_view;"
3740
"::absl::string_view";
38-
static const char DefaultAbseilStringsMatchHeader[] = "absl/strings/match.h";
41+
static const char AbseilStringsMatchHeaderDefault[] = "absl/strings/match.h";
3942

4043
static transformer::RewriteRuleWith<std::string>
4144
makeRewriteRule(ArrayRef<StringRef> StringLikeClassNames,
@@ -84,9 +87,9 @@ StringFindStrContainsCheck::StringFindStrContainsCheck(
8487
StringRef Name, ClangTidyContext *Context)
8588
: TransformerClangTidyCheck(Name, Context),
8689
StringLikeClassesOption(utils::options::parseStringList(
87-
Options.get("StringLikeClasses", DefaultStringLikeClasses))),
90+
Options.get("StringLikeClasses", StringLikeClassesDefault))),
8891
AbseilStringsMatchHeaderOption(Options.get(
89-
"AbseilStringsMatchHeader", DefaultAbseilStringsMatchHeader)) {
92+
"AbseilStringsMatchHeader", AbseilStringsMatchHeaderDefault)) {
9093
setRule(
9194
makeRewriteRule(StringLikeClassesOption, AbseilStringsMatchHeaderOption));
9295
}

clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "TimeSubtractionCheck.h"
10+
#include "../utils/LexerUtils.h"
1011
#include "DurationRewriter.h"
1112
#include "clang/AST/ASTContext.h"
1213
#include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -18,15 +19,6 @@ using namespace clang::ast_matchers;
1819

1920
namespace clang::tidy::abseil {
2021

21-
// Returns `true` if `Range` is inside a macro definition.
22-
static bool insideMacroDefinition(const MatchFinder::MatchResult &Result,
23-
SourceRange Range) {
24-
return !clang::Lexer::makeFileCharRange(
25-
clang::CharSourceRange::getCharRange(Range),
26-
*Result.SourceManager, Result.Context->getLangOpts())
27-
.isValid();
28-
}
29-
3022
static bool isConstructorAssignment(const MatchFinder::MatchResult &Result,
3123
const Expr *Node) {
3224
// For C++14 and earlier there are elidable constructors that must be matched
@@ -130,7 +122,9 @@ void TimeSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
130122
const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>("binop");
131123
std::string InverseName =
132124
Result.Nodes.getNodeAs<FunctionDecl>("func_decl")->getNameAsString();
133-
if (insideMacroDefinition(Result, BinOp->getSourceRange()))
125+
if (tidy::utils::lexer::insideMacroDefinition(BinOp->getSourceRange(),
126+
*Result.SourceManager,
127+
Result.Context->getLangOpts()))
134128
return;
135129

136130
std::optional<DurationScale> Scale = getScaleForTimeInverse(InverseName);
@@ -139,7 +133,9 @@ void TimeSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
139133

140134
const auto *OuterCall = Result.Nodes.getNodeAs<CallExpr>("outer_call");
141135
if (OuterCall) {
142-
if (insideMacroDefinition(Result, OuterCall->getSourceRange()))
136+
if (tidy::utils::lexer::insideMacroDefinition(
137+
OuterCall->getSourceRange(), *Result.SourceManager,
138+
Result.Context->getLangOpts()))
143139
return;
144140

145141
// We're working with the first case of matcher, and need to replace the
@@ -165,7 +161,9 @@ void TimeSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
165161
.bind("arg"))),
166162
*BinOp, *Result.Context));
167163
if (MaybeCallArg && MaybeCallArg->getArg(0)->IgnoreImpCasts() == BinOp &&
168-
!insideMacroDefinition(Result, MaybeCallArg->getSourceRange())) {
164+
!tidy::utils::lexer::insideMacroDefinition(
165+
MaybeCallArg->getSourceRange(), *Result.SourceManager,
166+
Result.Context->getLangOpts())) {
169167
// Handle the case where the matched expression is inside a call which
170168
// converts it from the inverse to a Duration. In this case, we replace
171169
// the outer with just the subtraction expression, which gives the right

clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ void UpgradeDurationConversionsCheck::check(
139139

140140
// We gather source locations from template matches not in template
141141
// instantiations for future matches.
142-
internal::Matcher<Stmt> IsInsideTemplate =
143-
hasAncestor(decl(anyOf(classTemplateDecl(), functionTemplateDecl())));
142+
auto IsInsideTemplate = stmt(
143+
hasAncestor(decl(anyOf(classTemplateDecl(), functionTemplateDecl()))));
144144
if (!match(IsInsideTemplate, *ArgExpr, *Result.Context).empty())
145145
MatchedTemplateLocations.insert(Loc);
146146

clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,13 @@ void BadSignalToKillThreadCheck::registerMatchers(MatchFinder *Finder) {
2525
this);
2626
}
2727

28-
static Preprocessor *PP;
29-
3028
void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) {
3129
const auto IsSigterm = [](const auto &KeyValue) -> bool {
3230
return KeyValue.first->getName() == "SIGTERM" &&
3331
KeyValue.first->hasMacroDefinition();
3432
};
3533
const auto TryExpandAsInteger =
36-
[](Preprocessor::macro_iterator It) -> std::optional<unsigned> {
34+
[this](Preprocessor::macro_iterator It) -> std::optional<unsigned> {
3735
if (It == PP->macro_end())
3836
return std::nullopt;
3937
const MacroInfo *MI = PP->getMacroInfo(It->first);
@@ -64,8 +62,8 @@ void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) {
6462
}
6563

6664
void BadSignalToKillThreadCheck::registerPPCallbacks(
67-
const SourceManager &SM, Preprocessor *Pp, Preprocessor *ModuleExpanderPP) {
68-
PP = Pp;
65+
const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
66+
this->PP = PP;
6967
}
7068

7169
} // namespace clang::tidy::bugprone

clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ class BadSignalToKillThreadCheck : public ClangTidyCheck {
2626
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
2727
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
2828
Preprocessor *ModuleExpanderPP) override;
29+
30+
private:
2931
std::optional<unsigned> SigtermValue;
32+
Preprocessor *PP = nullptr;
3033
};
3134

3235
} // namespace clang::tidy::bugprone

clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ using namespace clang::ast_matchers;
1515

1616
namespace clang::tidy::bugprone {
1717

18+
namespace {
19+
1820
AST_MATCHER(clang::VarDecl, hasConstantDeclaration) {
1921
const Expr *Init = Node.getInit();
2022
if (Init && !Init->isValueDependent()) {
@@ -25,6 +27,8 @@ AST_MATCHER(clang::VarDecl, hasConstantDeclaration) {
2527
return false;
2628
}
2729

30+
} // namespace
31+
2832
DynamicStaticInitializersCheck::DynamicStaticInitializersCheck(
2933
StringRef Name, ClangTidyContext *Context)
3034
: ClangTidyCheck(Name, Context),

clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1881,6 +1881,8 @@ static bool prefixSuffixCoverUnderThreshold(std::size_t Threshold,
18811881

18821882
} // namespace filter
18831883

1884+
namespace {
1885+
18841886
/// Matches functions that have at least the specified amount of parameters.
18851887
AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N) {
18861888
return Node.getNumParams() >= N;
@@ -1903,6 +1905,8 @@ AST_MATCHER(FunctionDecl, isOverloadedUnaryOrBinaryOperator) {
19031905
}
19041906
}
19051907

1908+
} // namespace
1909+
19061910
/// Returns the DefaultMinimumLength if the Value of requested minimum length
19071911
/// is less than 2. Minimum lengths of 0 or 1 are not accepted.
19081912
static inline unsigned clampMinimumLength(const unsigned Value) {

clang-tools-extra/clang-tidy/bugprone/EmptyCatchCheck.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ using ::clang::ast_matchers::internal::Matcher;
2020
namespace clang::tidy::bugprone {
2121

2222
namespace {
23-
AST_MATCHER(CXXCatchStmt, isInMacro) {
23+
AST_MATCHER(CXXCatchStmt, isCatchInMacro) {
2424
return Node.getBeginLoc().isMacroID() || Node.getEndLoc().isMacroID() ||
2525
Node.getCatchLoc().isMacroID();
2626
}
@@ -89,7 +89,8 @@ void EmptyCatchCheck::registerMatchers(MatchFinder *Finder) {
8989
hasCanonicalType(AllowedNamedExceptionTypes)));
9090

9191
Finder->addMatcher(
92-
cxxCatchStmt(unless(isExpansionInSystemHeader()), unless(isInMacro()),
92+
cxxCatchStmt(unless(isExpansionInSystemHeader()),
93+
unless(isCatchInMacro()),
9394
unless(hasCaughtType(IgnoredExceptionType)),
9495
hasHandler(compoundStmt(
9596
statementCountIs(0),

clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ using namespace clang::ast_matchers;
1515

1616
namespace clang::tidy::bugprone {
1717

18+
namespace {
1819
AST_MATCHER(BinaryOperator, isLogicalOperator) { return Node.isLogicalOp(); }
1920

2021
AST_MATCHER(UnaryOperator, isUnaryPrePostOperator) {
@@ -26,6 +27,8 @@ AST_MATCHER(CXXOperatorCallExpr, isPrePostOperator) {
2627
Node.getOperator() == OO_MinusMinus;
2728
}
2829

30+
} // namespace
31+
2932
void IncDecInConditionsCheck::registerMatchers(MatchFinder *Finder) {
3033
auto OperatorMatcher = expr(
3134
anyOf(binaryOperator(anyOf(isComparisonOperator(), isLogicalOperator())),

clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ AST_MATCHER(FunctionType, typeHasNoReturnAttr) {
3333
} // namespace ast_matchers
3434
namespace tidy::bugprone {
3535

36-
static internal::Matcher<Stmt>
37-
loopEndingStmt(internal::Matcher<Stmt> Internal) {
38-
internal::Matcher<QualType> isNoReturnFunType =
36+
static ast_matchers::internal::Matcher<Stmt>
37+
loopEndingStmt(ast_matchers::internal::Matcher<Stmt> Internal) {
38+
ast_matchers::internal::Matcher<QualType> isNoReturnFunType =
3939
ignoringParens(functionType(typeHasNoReturnAttr()));
40-
internal::Matcher<Decl> isNoReturnDecl =
40+
ast_matchers::internal::Matcher<Decl> isNoReturnDecl =
4141
anyOf(declHasNoReturnAttr(), functionDecl(hasType(isNoReturnFunType)),
4242
varDecl(hasType(blockPointerType(pointee(isNoReturnFunType)))));
4343

clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp

Lines changed: 5 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "MultipleNewInOneExpressionCheck.h"
10+
#include "../utils/Matchers.h"
1011
#include "clang/AST/ASTContext.h"
1112
#include "clang/ASTMatchers/ASTMatchFinder.h"
1213
#include "clang/Lex/Lexer.h"
@@ -51,29 +52,6 @@ bool isExprValueStored(const Expr *E, ASTContext &C) {
5152

5253
} // namespace
5354

54-
AST_MATCHER_P(CXXTryStmt, hasHandlerFor,
55-
ast_matchers::internal::Matcher<QualType>, InnerMatcher) {
56-
for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) {
57-
const CXXCatchStmt *CatchS = Node.getHandler(I);
58-
// Check for generic catch handler (match anything).
59-
if (CatchS->getCaughtType().isNull())
60-
return true;
61-
ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
62-
if (InnerMatcher.matches(CatchS->getCaughtType(), Finder, &Result)) {
63-
*Builder = std::move(Result);
64-
return true;
65-
}
66-
}
67-
return false;
68-
}
69-
70-
AST_MATCHER(CXXNewExpr, mayThrow) {
71-
FunctionDecl *OperatorNew = Node.getOperatorNew();
72-
if (!OperatorNew)
73-
return false;
74-
return !OperatorNew->getType()->castAs<FunctionProtoType>()->isNothrow();
75-
}
76-
7755
void MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) {
7856
auto BadAllocType =
7957
recordType(hasDeclaration(cxxRecordDecl(hasName("::std::bad_alloc"))));
@@ -85,9 +63,10 @@ void MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) {
8563
auto CatchBadAllocType =
8664
qualType(hasCanonicalType(anyOf(BadAllocType, BadAllocReferenceType,
8765
ExceptionType, ExceptionReferenceType)));
88-
auto BadAllocCatchingTryBlock = cxxTryStmt(hasHandlerFor(CatchBadAllocType));
66+
auto BadAllocCatchingTryBlock =
67+
cxxTryStmt(matchers::hasHandlerFor(CatchBadAllocType));
8968

90-
auto NewExprMayThrow = cxxNewExpr(mayThrow());
69+
auto NewExprMayThrow = cxxNewExpr(matchers::mayThrow());
9170
auto HasNewExpr1 = expr(anyOf(NewExprMayThrow.bind("new1"),
9271
hasDescendant(NewExprMayThrow.bind("new1"))));
9372
auto HasNewExpr2 = expr(anyOf(NewExprMayThrow.bind("new2"),
@@ -115,7 +94,7 @@ void MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) {
11594
hasAncestor(BadAllocCatchingTryBlock)),
11695
this);
11796
Finder->addMatcher(
118-
cxxNewExpr(mayThrow(),
97+
cxxNewExpr(matchers::mayThrow(),
11998
hasDescendant(NewExprMayThrow.bind("new2_in_new1")),
12099
hasAncestor(BadAllocCatchingTryBlock))
121100
.bind("new1"),

clang-tools-extra/clang-tidy/bugprone/MultipleStatementMacroCheck.cpp

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,13 @@ namespace clang::tidy::bugprone {
1616

1717
namespace {
1818

19-
AST_MATCHER(Expr, isInMacro) { return Node.getBeginLoc().isMacroID(); }
19+
AST_MATCHER(Expr, isExprInMacro) { return Node.getBeginLoc().isMacroID(); }
20+
21+
} // namespace
2022

2123
/// Find the next statement after `S`.
22-
const Stmt *nextStmt(const MatchFinder::MatchResult &Result, const Stmt *S) {
24+
static const Stmt *nextStmt(const MatchFinder::MatchResult &Result,
25+
const Stmt *S) {
2326
auto Parents = Result.Context->getParents(*S);
2427
if (Parents.empty())
2528
return nullptr;
@@ -40,8 +43,8 @@ using ExpansionRanges = std::vector<SourceRange>;
4043
/// \brief Get all the macro expansion ranges related to `Loc`.
4144
///
4245
/// The result is ordered from most inner to most outer.
43-
ExpansionRanges getExpansionRanges(SourceLocation Loc,
44-
const MatchFinder::MatchResult &Result) {
46+
static ExpansionRanges
47+
getExpansionRanges(SourceLocation Loc, const MatchFinder::MatchResult &Result) {
4548
ExpansionRanges Locs;
4649
while (Loc.isMacroID()) {
4750
Locs.push_back(
@@ -51,10 +54,9 @@ ExpansionRanges getExpansionRanges(SourceLocation Loc,
5154
return Locs;
5255
}
5356

54-
} // namespace
55-
5657
void MultipleStatementMacroCheck::registerMatchers(MatchFinder *Finder) {
57-
const auto Inner = expr(isInMacro(), unless(compoundStmt())).bind("inner");
58+
const auto Inner =
59+
expr(isExprInMacro(), unless(compoundStmt())).bind("inner");
5860
Finder->addMatcher(
5961
stmt(anyOf(ifStmt(hasThen(Inner)), ifStmt(hasElse(Inner)).bind("else"),
6062
whileStmt(hasBody(Inner)), forStmt(hasBody(Inner))))

clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -322,12 +322,12 @@ SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) {
322322
return P.getSourceRange();
323323
}
324324

325-
} // namespace
326-
327325
AST_MATCHER(FunctionDecl, isStandardFunction) {
328326
return isStandardFunction(&Node);
329327
}
330328

329+
} // namespace
330+
331331
SignalHandlerCheck::SignalHandlerCheck(StringRef Name,
332332
ClangTidyContext *Context)
333333
: ClangTidyCheck(Name, Context),

0 commit comments

Comments
 (0)