Skip to content

Commit 01bea27

Browse files
authored
[clang-tidy][NFC] Fix misc-const-correctness warnings (10/N) (#167127)
1 parent ce7f9f9 commit 01bea27

21 files changed

+177
-165
lines changed

clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ static SmallVector<BindArgument, 4>
252252
buildBindArguments(const MatchFinder::MatchResult &Result,
253253
const CallableInfo &Callable) {
254254
SmallVector<BindArgument, 4> BindArguments;
255-
static llvm::Regex MatchPlaceholder("^_([0-9]+)$");
255+
static const llvm::Regex MatchPlaceholder("^_([0-9]+)$");
256256

257257
const auto *BindCall = Result.Nodes.getNodeAs<CallExpr>("bind");
258258

@@ -267,7 +267,7 @@ buildBindArguments(const MatchFinder::MatchResult &Result,
267267
if (Callable.Type == CT_MemberFunction)
268268
--ArgIndex;
269269

270-
bool IsObjectPtr = (I == 1 && Callable.Type == CT_MemberFunction);
270+
const bool IsObjectPtr = (I == 1 && Callable.Type == CT_MemberFunction);
271271
B.E = E;
272272
B.SourceTokens = getSourceTextForExpr(Result, E);
273273

@@ -340,13 +340,13 @@ static void addPlaceholderArgs(const LambdaProperties &LP,
340340
MaxPlaceholderIt->PlaceHolderIndex == 0))
341341
return;
342342

343-
size_t PlaceholderCount = MaxPlaceholderIt->PlaceHolderIndex;
343+
const size_t PlaceholderCount = MaxPlaceholderIt->PlaceHolderIndex;
344344
Stream << "(";
345345
StringRef Delimiter = "";
346346
for (size_t I = 1; I <= PlaceholderCount; ++I) {
347347
Stream << Delimiter << "auto &&";
348348

349-
int ArgIndex = findPositionOfPlaceholderUse(Args, I);
349+
const int ArgIndex = findPositionOfPlaceholderUse(Args, I);
350350

351351
if (ArgIndex != -1 && Args[ArgIndex].IsUsed)
352352
Stream << " " << Args[ArgIndex].UsageIdentifier;
@@ -392,7 +392,7 @@ findCandidateCallOperators(const CXXRecordDecl *RecordDecl, size_t NumArgs) {
392392
std::vector<const FunctionDecl *> Candidates;
393393

394394
for (const clang::CXXMethodDecl *Method : RecordDecl->methods()) {
395-
OverloadedOperatorKind OOK = Method->getOverloadedOperator();
395+
const OverloadedOperatorKind OOK = Method->getOverloadedOperator();
396396

397397
if (OOK != OverloadedOperatorKind::OO_Call)
398398
continue;
@@ -410,7 +410,7 @@ findCandidateCallOperators(const CXXRecordDecl *RecordDecl, size_t NumArgs) {
410410
continue;
411411
const FunctionDecl *FD = FTD->getTemplatedDecl();
412412

413-
OverloadedOperatorKind OOK = FD->getOverloadedOperator();
413+
const OverloadedOperatorKind OOK = FD->getOverloadedOperator();
414414
if (OOK != OverloadedOperatorKind::OO_Call)
415415
continue;
416416

@@ -471,7 +471,7 @@ getCallMethodDecl(const MatchFinder::MatchResult &Result, CallableType Type,
471471

472472
if (Type == CT_Object) {
473473
const auto *BindCall = Result.Nodes.getNodeAs<CallExpr>("bind");
474-
size_t NumArgs = BindCall->getNumArgs() - 1;
474+
const size_t NumArgs = BindCall->getNumArgs() - 1;
475475
return getCallOperator(Callee->getType()->getAsCXXRecordDecl(), NumArgs);
476476
}
477477

@@ -488,7 +488,7 @@ getCallMethodDecl(const MatchFinder::MatchResult &Result, CallableType Type,
488488
static CallableType getCallableType(const MatchFinder::MatchResult &Result) {
489489
const auto *CallableExpr = Result.Nodes.getNodeAs<Expr>("ref");
490490

491-
QualType QT = CallableExpr->getType();
491+
const QualType QT = CallableExpr->getType();
492492
if (QT->isMemberFunctionPointerType())
493493
return CT_MemberFunction;
494494

@@ -614,7 +614,7 @@ static void emitCaptureList(const LambdaProperties &LP,
614614
if (B.CM == CM_None || !B.IsUsed)
615615
continue;
616616

617-
StringRef Delimiter = AnyCapturesEmitted ? ", " : "";
617+
const StringRef Delimiter = AnyCapturesEmitted ? ", " : "";
618618

619619
if (emitCapture(CaptureSet, Delimiter, B.CM, B.CE, B.CaptureIdentifier,
620620
B.SourceTokens, Stream))
@@ -669,7 +669,7 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult &Result) {
669669
emitCaptureList(LP, Result, Stream);
670670
Stream << "]";
671671

672-
ArrayRef<BindArgument> FunctionCallArgs = ArrayRef(LP.BindArguments);
672+
const ArrayRef<BindArgument> FunctionCallArgs = ArrayRef(LP.BindArguments);
673673

674674
addPlaceholderArgs(LP, Stream, PermissiveParameterList);
675675

clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ static bool locationsInSameFile(const SourceManager &Sources,
2525
static StringRef getRawStringRef(const SourceRange &Range,
2626
const SourceManager &Sources,
2727
const LangOptions &LangOpts) {
28-
CharSourceRange TextRange = Lexer::getAsCharRange(Range, Sources, LangOpts);
28+
const CharSourceRange TextRange =
29+
Lexer::getAsCharRange(Range, Sources, LangOpts);
2930
return Lexer::getSourceText(TextRange, Sources, LangOpts);
3031
}
3132

@@ -56,15 +57,16 @@ SourceRange NS::getDefaultNamespaceBackRange() const {
5657
SourceRange NS::getNamespaceBackRange(const SourceManager &SM,
5758
const LangOptions &LangOpts) const {
5859
// Back from '}' to conditional '// namespace xxx'
59-
SourceLocation Loc = front()->getRBraceLoc();
60+
const SourceLocation Loc = front()->getRBraceLoc();
6061
std::optional<Token> Tok =
6162
utils::lexer::findNextTokenIncludingComments(Loc, SM, LangOpts);
6263
if (!Tok)
6364
return getDefaultNamespaceBackRange();
6465
if (Tok->getKind() != tok::TokenKind::comment)
6566
return getDefaultNamespaceBackRange();
66-
SourceRange TokRange = SourceRange{Tok->getLocation(), Tok->getEndLoc()};
67-
StringRef TokText = getRawStringRef(TokRange, SM, LangOpts);
67+
const SourceRange TokRange =
68+
SourceRange{Tok->getLocation(), Tok->getEndLoc()};
69+
const StringRef TokText = getRawStringRef(TokRange, SM, LangOpts);
6870
NamespaceName CloseComment{"namespace "};
6971
appendCloseComment(CloseComment);
7072
// current fix hint in readability/NamespaceCommentCheck.cpp use single line
@@ -98,15 +100,15 @@ bool ConcatNestedNamespacesCheck::unsupportedNamespace(const NamespaceDecl &ND,
98100
return true;
99101
if (getLangOpts().CPlusPlus20) {
100102
// C++20 support inline nested namespace
101-
bool IsFirstNS = IsChild || !Namespaces.empty();
103+
const bool IsFirstNS = IsChild || !Namespaces.empty();
102104
return ND.isInlineNamespace() && !IsFirstNS;
103105
}
104106
return ND.isInlineNamespace();
105107
}
106108

107109
bool ConcatNestedNamespacesCheck::singleNamedNamespaceChild(
108110
const NamespaceDecl &ND) const {
109-
NamespaceDecl::decl_range Decls = ND.decls();
111+
const NamespaceDecl::decl_range Decls = ND.decls();
110112
if (std::distance(Decls.begin(), Decls.end()) != 1)
111113
return false;
112114

@@ -121,7 +123,7 @@ void ConcatNestedNamespacesCheck::registerMatchers(
121123

122124
void ConcatNestedNamespacesCheck::reportDiagnostic(
123125
const SourceManager &SM, const LangOptions &LangOpts) {
124-
DiagnosticBuilder DB =
126+
const DiagnosticBuilder DB =
125127
diag(Namespaces.front().front()->getBeginLoc(),
126128
"nested namespaces can be concatenated", DiagnosticIDs::Warning);
127129

@@ -143,7 +145,7 @@ void ConcatNestedNamespacesCheck::reportDiagnostic(
143145

144146
// the last one should be handled specially
145147
Fronts.pop_back();
146-
SourceRange LastRBrace = Backs.pop_back_val();
148+
const SourceRange LastRBrace = Backs.pop_back_val();
147149

148150
NamespaceName ConcatNameSpace{"namespace "};
149151
for (const NS &NS : Namespaces) {

clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ void IncludeModernizePPCallbacks::InclusionDirective(
184184
// 1. Insert std prefix for every such symbol occurrence.
185185
// 2. Insert `using namespace std;` to the beginning of TU.
186186
// 3. Do nothing and let the user deal with the migration himself.
187-
SourceLocation DiagLoc = FilenameRange.getBegin();
187+
const SourceLocation DiagLoc = FilenameRange.getBegin();
188188
if (auto It = CStyledHeaderToCxx.find(FileName);
189189
It != CStyledHeaderToCxx.end()) {
190190
IncludesToBeProcessed.emplace_back(IncludeMarker{

clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,10 @@ void DeprecatedIosBaseAliasesCheck::registerMatchers(MatchFinder *Finder) {
3636

3737
void DeprecatedIosBaseAliasesCheck::check(
3838
const MatchFinder::MatchResult &Result) {
39-
SourceManager &SM = *Result.SourceManager;
39+
const SourceManager &SM = *Result.SourceManager;
4040

4141
const auto *Typedef = Result.Nodes.getNodeAs<TypedefDecl>("TypeDecl");
42-
StringRef TypeName = Typedef->getName();
42+
const StringRef TypeName = Typedef->getName();
4343
auto Replacement = getReplacementType(TypeName);
4444

4545
TypeLoc TL = *Result.Nodes.getNodeAs<TypeLoc>("TypeLoc");
@@ -55,7 +55,8 @@ void DeprecatedIosBaseAliasesCheck::check(
5555
Fix = false;
5656
}
5757

58-
SourceLocation EndLoc = IoStateLoc.getLocWithOffset(TypeName.size() - 1);
58+
const SourceLocation EndLoc =
59+
IoStateLoc.getLocWithOffset(TypeName.size() - 1);
5960

6061
if (Replacement) {
6162
const char *FixName = *Replacement;

clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ bool IntegralLiteralExpressionMatcher::unaryOperator() {
9595
}
9696

9797
static LiteralSize literalTokenSize(const Token &Tok) {
98-
unsigned int Length = Tok.getLength();
98+
const unsigned int Length = Tok.getLength();
9999
if (Length <= 1)
100100
return LiteralSize::Int;
101101

clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ arrayConditionMatcher(internal::Matcher<Expr> LimitExpr) {
115115
/// - The index variable is only used as an array index.
116116
/// - All arrays indexed by the loop are the same.
117117
static StatementMatcher makeArrayLoopMatcher() {
118-
StatementMatcher ArrayBoundMatcher =
118+
const StatementMatcher ArrayBoundMatcher =
119119
expr(hasType(isInteger())).bind(ConditionBoundName);
120120

121121
return forStmt(unless(isInTemplateInstantiation()),
@@ -168,7 +168,7 @@ static StatementMatcher makeIteratorLoopMatcher(bool IsReverse) {
168168
auto EndNameMatcherStd = IsReverse ? hasAnyName("::std::rend", "::std::crend")
169169
: hasAnyName("::std::end", "::std::cend");
170170

171-
StatementMatcher BeginCallMatcher =
171+
const StatementMatcher BeginCallMatcher =
172172
expr(anyOf(cxxMemberCallExpr(argumentCountIs(0),
173173
callee(cxxMethodDecl(BeginNameMatcher))),
174174
callExpr(argumentCountIs(1),
@@ -177,37 +177,37 @@ static StatementMatcher makeIteratorLoopMatcher(bool IsReverse) {
177177
callee(functionDecl(BeginNameMatcherStd)))))
178178
.bind(BeginCallName);
179179

180-
DeclarationMatcher InitDeclMatcher =
180+
const DeclarationMatcher InitDeclMatcher =
181181
varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
182182
materializeTemporaryExpr(
183183
ignoringParenImpCasts(BeginCallMatcher)),
184184
hasDescendant(BeginCallMatcher))))
185185
.bind(InitVarName);
186186

187-
DeclarationMatcher EndDeclMatcher =
187+
const DeclarationMatcher EndDeclMatcher =
188188
varDecl(hasInitializer(anything())).bind(EndVarName);
189189

190-
StatementMatcher EndCallMatcher = expr(anyOf(
190+
const StatementMatcher EndCallMatcher = expr(anyOf(
191191
cxxMemberCallExpr(argumentCountIs(0),
192192
callee(cxxMethodDecl(EndNameMatcher))),
193193
callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcher)),
194194
usesADL()),
195195
callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcherStd)))));
196196

197-
StatementMatcher IteratorBoundMatcher =
197+
const StatementMatcher IteratorBoundMatcher =
198198
expr(anyOf(ignoringParenImpCasts(
199199
declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))),
200200
ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)),
201201
materializeTemporaryExpr(ignoringParenImpCasts(
202202
expr(EndCallMatcher).bind(EndCallName)))));
203203

204-
StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
204+
const StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
205205
declRefExpr(to(varDecl(equalsBoundNode(InitVarName))))));
206206

207207
// This matcher tests that a declaration is a CXXRecordDecl that has an
208208
// overloaded operator*(). If the operator*() returns by value instead of by
209209
// reference then the return type is tagged with DerefByValueResultName.
210-
internal::Matcher<VarDecl> TestDerefReturnsByValue =
210+
const internal::Matcher<VarDecl> TestDerefReturnsByValue =
211211
hasType(hasUnqualifiedDesugaredType(
212212
recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl(
213213
hasOverloadedOperatorName("*"),
@@ -280,7 +280,7 @@ static StatementMatcher makePseudoArrayLoopMatcher() {
280280
// FIXME: Also, a record doesn't necessarily need begin() and end(). Free
281281
// functions called begin() and end() taking the container as an argument
282282
// are also allowed.
283-
TypeMatcher RecordWithBeginEnd = qualType(anyOf(
283+
const TypeMatcher RecordWithBeginEnd = qualType(anyOf(
284284
qualType(isConstQualified(),
285285
hasUnqualifiedDesugaredType(recordType(hasDeclaration(
286286
cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
@@ -295,7 +295,7 @@ static StatementMatcher makePseudoArrayLoopMatcher() {
295295
hasMethod(hasName("end"))))))))) // qualType
296296
));
297297

298-
StatementMatcher SizeCallMatcher = expr(anyOf(
298+
const StatementMatcher SizeCallMatcher = expr(anyOf(
299299
cxxMemberCallExpr(argumentCountIs(0),
300300
callee(cxxMethodDecl(hasAnyName("size", "length"))),
301301
on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
@@ -310,10 +310,10 @@ static StatementMatcher makePseudoArrayLoopMatcher() {
310310
explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
311311
expr(SizeCallMatcher).bind(EndCallName))))));
312312

313-
DeclarationMatcher EndDeclMatcher =
313+
const DeclarationMatcher EndDeclMatcher =
314314
varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName);
315315

316-
StatementMatcher IndexBoundMatcher =
316+
const StatementMatcher IndexBoundMatcher =
317317
expr(anyOf(ignoringParenImpCasts(
318318
declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))),
319319
EndInitMatcher));
@@ -620,7 +620,7 @@ void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
620620
SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
621621
if (Invalid)
622622
return;
623-
unsigned Offset = std::strspn(TextAfter, " \t\r\n");
623+
const unsigned Offset = std::strspn(TextAfter, " \t\r\n");
624624
Range =
625625
SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
626626
}
@@ -633,7 +633,7 @@ void LoopConvertCheck::doConversion(
633633
const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit,
634634
const ForStmt *Loop, RangeDescriptor Descriptor) {
635635
std::string VarNameOrStructuredBinding;
636-
bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
636+
const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
637637
bool AliasVarIsRef = false;
638638
bool CanCopy = true;
639639
std::vector<FixItHint> FixIts;
@@ -743,7 +743,7 @@ void LoopConvertCheck::doConversion(
743743
}
744744

745745
// Now, we need to construct the new range expression.
746-
SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
746+
const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
747747

748748
QualType Type = Context->getAutoDeductType();
749749
if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
@@ -753,14 +753,15 @@ void LoopConvertCheck::doConversion(
753753
// If the new variable name is from the aliased variable, then the reference
754754
// type for the new variable should only be used if the aliased variable was
755755
// declared as a reference.
756-
bool IsCheapToCopy =
756+
const bool IsCheapToCopy =
757757
!Descriptor.ElemType.isNull() &&
758758
Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
759759
!Descriptor.ElemType->isDependentSizedArrayType() &&
760760
// TypeInfo::Width is in bits.
761761
Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
762-
bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
763-
(Descriptor.DerefByConstRef && IsCheapToCopy));
762+
const bool UseCopy =
763+
CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
764+
(Descriptor.DerefByConstRef && IsCheapToCopy));
764765

765766
if (!UseCopy) {
766767
if (Descriptor.DerefByConstRef) {
@@ -866,7 +867,7 @@ void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
866867
// The matchers for iterator loops provide bound nodes to obtain this
867868
// information.
868869
const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
869-
QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
870+
const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
870871
const auto *DerefByValueType =
871872
Nodes.getNodeAs<QualType>(DerefByValueResultName);
872873
Descriptor.DerefByValue = DerefByValueType;
@@ -934,12 +935,12 @@ bool LoopConvertCheck::isConvertible(ASTContext *Context,
934935

935936
// FIXME: Try to put most of this logic inside a matcher.
936937
if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
937-
QualType InitVarType = InitVar->getType();
938-
QualType CanonicalInitVarType = InitVarType.getCanonicalType();
938+
const QualType InitVarType = InitVar->getType();
939+
const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
939940

940941
const auto *BeginCall = Nodes.getNodeAs<CallExpr>(BeginCallName);
941942
assert(BeginCall && "Bad Callback. No begin call expression");
942-
QualType CanonicalBeginType =
943+
const QualType CanonicalBeginType =
943944
BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
944945
if (CanonicalBeginType->isPointerType() &&
945946
CanonicalInitVarType->isPointerType()) {
@@ -1054,7 +1055,7 @@ void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) {
10541055
}
10551056

10561057
// Find out which qualifiers we have to use in the loop range.
1057-
TraversalKindScope RAII(*Context, TK_AsIs);
1058+
const TraversalKindScope RAII(*Context, TK_AsIs);
10581059
const UsageResult &Usages = Finder.getUsages();
10591060
determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
10601061
Usages, Descriptor);

0 commit comments

Comments
 (0)