[clang-tidy][NFC] Fix misc-const-correctness warnings (9/N) (#167124)

This commit is contained in:
Baranov Victor 2025-11-08 19:27:21 +03:00 committed by GitHub
parent 5896a25ffe
commit ace77c25a4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
21 changed files with 130 additions and 123 deletions

View File

@ -79,7 +79,7 @@ void NamedParameterCheck::check(const MatchFinder::MatchResult &Result) {
// void foo(int /*unused*/)
const char *Begin = SM.getCharacterData(Parm->getBeginLoc());
const char *End = SM.getCharacterData(Parm->getLocation());
StringRef Data(Begin, End - Begin);
const StringRef Data(Begin, End - Begin);
if (Data.contains("/*"))
continue;
@ -104,7 +104,7 @@ void NamedParameterCheck::check(const MatchFinder::MatchResult &Result) {
if (M && M->size_overridden_methods() > 0) {
const ParmVarDecl *OtherParm =
(*M->begin_overridden_methods())->getParamDecl(P.second);
StringRef Name = OtherParm->getName();
const StringRef Name = OtherParm->getName();
if (!Name.empty())
NewName = Name;
}
@ -112,7 +112,7 @@ void NamedParameterCheck::check(const MatchFinder::MatchResult &Result) {
// If the definition has a named parameter use that name.
if (Definition) {
const ParmVarDecl *DefParm = Definition->getParamDecl(P.second);
StringRef Name = DefParm->getName();
const StringRef Name = DefParm->getName();
if (!Name.empty())
NewName = Name;
}

View File

@ -70,7 +70,7 @@ getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources,
--Nesting;
} else if (Nesting == 0) {
if (T->is(tok::raw_identifier)) {
StringRef ID = T->getRawIdentifier();
const StringRef ID = T->getRawIdentifier();
if (ID != "namespace")
Result.append(std::string(ID));
if (ID == "inline")
@ -96,13 +96,13 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
// Don't require closing comments for namespaces spanning less than certain
// number of lines.
unsigned StartLine = Sources.getSpellingLineNumber(ND->getBeginLoc());
unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc());
const unsigned StartLine = Sources.getSpellingLineNumber(ND->getBeginLoc());
const unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc());
if (EndLine - StartLine + 1 <= ShortNamespaceLines)
return;
// Find next token after the namespace closing brace.
SourceLocation AfterRBrace = Lexer::getLocForEndOfToken(
const SourceLocation AfterRBrace = Lexer::getLocForEndOfToken(
ND->getRBraceLoc(), /*Offset=*/0, Sources, getLangOpts());
SourceLocation Loc = AfterRBrace;
SourceLocation LBraceLoc = ND->getBeginLoc();
@ -137,7 +137,8 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
if (!locationsInSameFile(Sources, ND->getRBraceLoc(), Loc))
return;
bool NextTokenIsOnSameLine = Sources.getSpellingLineNumber(Loc) == EndLine;
const bool NextTokenIsOnSameLine =
Sources.getSpellingLineNumber(Loc) == EndLine;
// If we insert a line comment before the token in the same line, we need
// to insert a line break.
bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof);
@ -148,11 +149,12 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
// Try to find existing namespace closing comment on the same line.
if (Tok.is(tok::comment) && NextTokenIsOnSameLine) {
StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength());
const StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength());
SmallVector<StringRef, 7> Groups;
if (NamespaceCommentPattern.match(Comment, &Groups)) {
StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : "";
StringRef Anonymous = Groups.size() > 3 ? Groups[3] : "";
const StringRef NamespaceNameInComment =
Groups.size() > 5 ? Groups[5] : "";
const StringRef Anonymous = Groups.size() > 3 ? Groups[3] : "";
if ((ND->isAnonymousNamespace() && NamespaceNameInComment.empty()) ||
(*NamespaceNameAsWritten == NamespaceNameInComment &&
@ -186,7 +188,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
// multi-line or there may be other tokens behind it.
}
std::string NamespaceNameForDiag =
const std::string NamespaceNameForDiag =
ND->isAnonymousNamespace()
? "anonymous namespace"
: ("namespace '" + *NamespaceNameAsWritten + "'");
@ -203,7 +205,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
Fix.append("\n");
// Place diagnostic at an old comment, or closing brace if we did not have it.
SourceLocation DiagLoc =
const SourceLocation DiagLoc =
OldCommentRange.getBegin() != OldCommentRange.getEnd()
? OldCommentRange.getBegin()
: ND->getRBraceLoc();

View File

@ -155,7 +155,7 @@ void NonConstParameterCheck::diagnoseNonConstParameters() {
dyn_cast_or_null<const FunctionDecl>(Par->getParentFunctionOrMethod());
if (!Function)
continue;
unsigned Index = Par->getFunctionScopeIndex();
const unsigned Index = Par->getFunctionScopeIndex();
for (FunctionDecl *FnDecl : Function->redecls()) {
if (FnDecl->getNumParams() <= Index)
continue;

View File

@ -23,7 +23,7 @@ static StringRef getOperatorSpelling(SourceLocation Loc, ASTContext &Context) {
if (Loc.isInvalid())
return {};
SourceManager &SM = Context.getSourceManager();
const SourceManager &SM = Context.getSourceManager();
Loc = SM.getSpellingLoc(Loc);
if (Loc.isInvalid())
@ -41,7 +41,7 @@ AST_MATCHER_P2(BinaryOperator, hasInvalidBinaryOperatorRepresentation,
if (Node.getOpcode() != Kind || ExpectedRepresentation.empty())
return false;
StringRef Spelling =
const StringRef Spelling =
getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
return !Spelling.empty() && Spelling != ExpectedRepresentation;
}
@ -52,7 +52,7 @@ AST_MATCHER_P2(UnaryOperator, hasInvalidUnaryOperatorRepresentation,
if (Node.getOpcode() != Kind || ExpectedRepresentation.empty())
return false;
StringRef Spelling =
const StringRef Spelling =
getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
return !Spelling.empty() && Spelling != ExpectedRepresentation;
}
@ -63,7 +63,7 @@ AST_MATCHER_P2(CXXOperatorCallExpr, hasInvalidOverloadedOperatorRepresentation,
if (Node.getOperator() != Kind || ExpectedRepresentation.empty())
return false;
StringRef Spelling =
const StringRef Spelling =
getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
return !Spelling.empty() && Spelling != ExpectedRepresentation;
}
@ -297,9 +297,9 @@ void OperatorsRepresentationCheck::check(
if (TokenRange.isInvalid())
return;
StringRef Spelling = Lexer::getSourceText(TokenRange, *Result.SourceManager,
Result.Context->getLangOpts());
StringRef TranslatedSpelling = translate(Spelling);
const StringRef Spelling = Lexer::getSourceText(
TokenRange, *Result.SourceManager, Result.Context->getLangOpts());
const StringRef TranslatedSpelling = translate(Spelling);
if (TranslatedSpelling.empty())
return;
@ -312,7 +312,7 @@ void OperatorsRepresentationCheck::check(
SourceRepresentation = "a traditional";
TargetRepresentation = "an alternative";
StringRef SpellingEx = Lexer::getSourceText(
const StringRef SpellingEx = Lexer::getSourceText(
CharSourceRange::getCharRange(
TokenRange.getBegin().getLocWithOffset(-1),
TokenRange.getBegin().getLocWithOffset(Spelling.size() + 1U)),

View File

@ -44,18 +44,18 @@ findQualToken(const VarDecl *Decl, Qualifier Qual,
SourceLocation BeginLoc = Decl->getQualifierLoc().getBeginLoc();
if (BeginLoc.isInvalid())
BeginLoc = Decl->getBeginLoc();
SourceLocation EndLoc = Decl->getLocation();
const SourceLocation EndLoc = Decl->getLocation();
CharSourceRange FileRange = Lexer::makeFileCharRange(
const CharSourceRange FileRange = Lexer::makeFileCharRange(
CharSourceRange::getCharRange(BeginLoc, EndLoc), *Result.SourceManager,
Result.Context->getLangOpts());
if (FileRange.isInvalid())
return std::nullopt;
tok::TokenKind Tok = Qual == Qualifier::Const ? tok::kw_const
: Qual == Qualifier::Volatile ? tok::kw_volatile
: tok::kw_restrict;
const tok::TokenKind Tok = Qual == Qualifier::Const ? tok::kw_const
: Qual == Qualifier::Volatile ? tok::kw_volatile
: tok::kw_restrict;
return utils::lexer::getQualifyingToken(Tok, FileRange, *Result.Context,
*Result.SourceManager);
@ -90,13 +90,13 @@ mergeReplacementRange(SourceRange &TypeSpecifier, const Token &ConstToken) {
}
static bool isPointerConst(QualType QType) {
QualType Pointee = QType->getPointeeType();
const QualType Pointee = QType->getPointeeType();
assert(!Pointee.isNull() && "can't have a null Pointee");
return Pointee.isConstQualified();
}
static bool isAutoPointerConst(QualType QType) {
QualType Pointee =
const QualType Pointee =
cast<AutoType>(QType->getPointeeType().getTypePtr())->desugar();
assert(!Pointee.isNull() && "can't have a null Pointee");
return Pointee.isConstQualified();
@ -222,33 +222,34 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
if (Var->getLocation() == TypeSpecifier.getEnd().getLocWithOffset(1))
TypeSpecifier.setEnd(TypeSpecifier.getEnd().getLocWithOffset(1));
CharSourceRange FixItRange = CharSourceRange::getCharRange(TypeSpecifier);
const CharSourceRange FixItRange =
CharSourceRange::getCharRange(TypeSpecifier);
if (FixItRange.isInvalid())
return;
SourceLocation FixitLoc = FixItRange.getBegin();
for (SourceRange &Range : RemoveQualifiersRange) {
for (const SourceRange &Range : RemoveQualifiersRange) {
if (Range.getBegin() < FixitLoc)
FixitLoc = Range.getBegin();
}
std::string ReplStr = [&] {
llvm::StringRef PtrConst = isPointerConst(Var->getType()) ? "const " : "";
llvm::StringRef LocalConst = IsLocalConst ? "const " : "";
llvm::StringRef LocalVol = IsLocalVolatile ? "volatile " : "";
llvm::StringRef LocalRestrict = IsLocalRestrict ? "__restrict " : "";
const std::string ReplStr = [&] {
const StringRef PtrConst = isPointerConst(Var->getType()) ? "const " : "";
const StringRef LocalConst = IsLocalConst ? "const " : "";
const StringRef LocalVol = IsLocalVolatile ? "volatile " : "";
const StringRef LocalRestrict = IsLocalRestrict ? "__restrict " : "";
return (PtrConst + "auto *" + LocalConst + LocalVol + LocalRestrict)
.str();
}();
DiagnosticBuilder Diag =
const DiagnosticBuilder Diag =
diag(FixitLoc,
"'%select{|const }0%select{|volatile }1%select{|__restrict }2auto "
"%3' can be declared as '%4%3'")
<< IsLocalConst << IsLocalVolatile << IsLocalRestrict << Var->getName()
<< ReplStr;
for (SourceRange &Range : RemoveQualifiersRange) {
for (const SourceRange &Range : RemoveQualifiersRange) {
Diag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(Range));
}
@ -285,7 +286,7 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
TypeSpec->getEnd().isMacroID())
return;
SourceLocation InsertPos = TypeSpec->getBegin();
const SourceLocation InsertPos = TypeSpec->getBegin();
diag(InsertPos,
"'auto *%select{|const }0%select{|volatile }1%2' can be declared as "
"'const auto *%select{|const }0%select{|volatile }1%2'")
@ -307,7 +308,7 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
TypeSpec->getEnd().isMacroID())
return;
SourceLocation InsertPos = TypeSpec->getBegin();
const SourceLocation InsertPos = TypeSpec->getBegin();
diag(InsertPos, "'auto &%0' can be declared as 'const auto &%0'")
<< Var->getName() << FixItHint::CreateInsertion(InsertPos, "const ");
}

View File

@ -43,7 +43,7 @@ void RedundantAccessSpecifiersCheck::check(
LastASDecl = ASDecl;
if (CheckFirstDeclaration) {
AccessSpecifier DefaultSpecifier =
const AccessSpecifier DefaultSpecifier =
MatchedDecl->isClass() ? AS_private : AS_public;
if (ASDecl->getAccess() == DefaultSpecifier) {
diag(ASDecl->getLocation(),

View File

@ -25,8 +25,8 @@ static bool areTypesEqual(QualType S, QualType D) {
if (TS != TD)
return false;
QualType PtrS = S->getPointeeType();
QualType PtrD = D->getPointeeType();
const QualType PtrS = S->getPointeeType();
const QualType PtrD = D->getPointeeType();
if (!PtrS.isNull() && !PtrD.isNull())
return areTypesEqual(PtrS, PtrD);

View File

@ -50,7 +50,7 @@ void RedundantControlFlowCheck::check(const MatchFinder::MatchResult &Result) {
void RedundantControlFlowCheck::checkRedundantReturn(
const MatchFinder::MatchResult &Result, const CompoundStmt *Block) {
CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin();
const CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin();
if (const auto *Return = dyn_cast<ReturnStmt>(*Last))
issueDiagnostic(Result, Block, Return->getSourceRange(),
RedundantReturnDiag);
@ -58,7 +58,7 @@ void RedundantControlFlowCheck::checkRedundantReturn(
void RedundantControlFlowCheck::checkRedundantContinue(
const MatchFinder::MatchResult &Result, const CompoundStmt *Block) {
CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin();
const CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin();
if (const auto *Continue = dyn_cast<ContinueStmt>(*Last))
issueDiagnostic(Result, Block, Continue->getSourceRange(),
RedundantContinueDiag);
@ -67,11 +67,12 @@ void RedundantControlFlowCheck::checkRedundantContinue(
void RedundantControlFlowCheck::issueDiagnostic(
const MatchFinder::MatchResult &Result, const CompoundStmt *const Block,
const SourceRange &StmtRange, const char *const Diag) {
SourceManager &SM = *Result.SourceManager;
const SourceManager &SM = *Result.SourceManager;
if (isLocationInMacroExpansion(SM, StmtRange.getBegin()))
return;
CompoundStmt::const_reverse_body_iterator Previous = ++Block->body_rbegin();
const CompoundStmt::const_reverse_body_iterator Previous =
++Block->body_rbegin();
SourceLocation Start;
if (Previous != Block->body_rend())
Start = Lexer::findLocationAfterToken(

View File

@ -79,7 +79,7 @@ void RedundantDeclarationCheck::check(const MatchFinder::MatchResult &Result) {
}
}
SourceLocation EndLoc = Lexer::getLocForEndOfToken(
const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
D->getSourceRange().getEnd(), 0, SM, Result.Context->getLangOpts());
{
auto Diag = diag(D->getLocation(), "redundant %0 declaration") << D;

View File

@ -52,7 +52,7 @@ AST_POLYMORPHIC_MATCHER_P(isInternalLinkage,
static SourceLocation getInlineTokenLocation(SourceRange RangeLocation,
const SourceManager &Sources,
const LangOptions &LangOpts) {
SourceLocation Loc = RangeLocation.getBegin();
const SourceLocation Loc = RangeLocation.getBegin();
if (Loc.isMacroID())
return {};
@ -106,7 +106,7 @@ template <typename T>
void RedundantInlineSpecifierCheck::handleMatchedDecl(
const T *MatchedDecl, const SourceManager &Sources,
const MatchFinder::MatchResult &Result, StringRef Message) {
SourceLocation Loc = getInlineTokenLocation(
const SourceLocation Loc = getInlineTokenLocation(
MatchedDecl->getSourceRange(), Sources, Result.Context->getLangOpts());
if (Loc.isValid())
diag(Loc, Message) << MatchedDecl << FixItHint::CreateRemoval(Loc);

View File

@ -36,7 +36,7 @@ public:
void If(SourceLocation Loc, SourceRange ConditionRange,
ConditionValueKind ConditionValue) override {
StringRef Condition =
const StringRef Condition =
Lexer::getSourceText(CharSourceRange::getTokenRange(ConditionRange),
PP.getSourceManager(), PP.getLangOpts());
checkMacroRedundancy(Loc, Condition, IfStack, DK_If, DK_If, true);
@ -44,7 +44,7 @@ public:
void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
const MacroDefinition &MacroDefinition) override {
std::string MacroName = PP.getSpelling(MacroNameTok);
const std::string MacroName = PP.getSpelling(MacroNameTok);
checkMacroRedundancy(Loc, MacroName, IfdefStack, DK_Ifdef, DK_Ifdef, true);
checkMacroRedundancy(Loc, MacroName, IfndefStack, DK_Ifdef, DK_Ifndef,
false);
@ -52,7 +52,7 @@ public:
void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
const MacroDefinition &MacroDefinition) override {
std::string MacroName = PP.getSpelling(MacroNameTok);
const std::string MacroName = PP.getSpelling(MacroNameTok);
checkMacroRedundancy(Loc, MacroName, IfndefStack, DK_Ifndef, DK_Ifndef,
true);
checkMacroRedundancy(Loc, MacroName, IfdefStack, DK_Ifndef, DK_Ifdef,

View File

@ -149,8 +149,9 @@ void RedundantSmartptrGetCheck::check(const MatchFinder::MatchResult &Result) {
if (!allReturnTypesMatch(Result))
return;
bool IsPtrToPtr = Result.Nodes.getNodeAs<Decl>("ptr_to_ptr") != nullptr;
bool IsMemberExpr = Result.Nodes.getNodeAs<Expr>("memberExpr") != nullptr;
const bool IsPtrToPtr = Result.Nodes.getNodeAs<Decl>("ptr_to_ptr") != nullptr;
const bool IsMemberExpr =
Result.Nodes.getNodeAs<Expr>("memberExpr") != nullptr;
const auto *GetCall = Result.Nodes.getNodeAs<Expr>("redundant_get");
if (GetCall->getBeginLoc().isMacroID() && IgnoreMacros)
return;
@ -178,7 +179,8 @@ void RedundantSmartptrGetCheck::check(const MatchFinder::MatchResult &Result) {
SmartptrText = SmartptrText.drop_back(2);
}
// Replace foo->get() with *foo, and foo.get() with foo.
std::string Replacement = Twine(IsPtrToPtr ? "*" : "", SmartptrText).str();
const std::string Replacement =
Twine(IsPtrToPtr ? "*" : "", SmartptrText).str();
diag(GetCall->getBeginLoc(), "redundant get() call on smart pointer")
<< FixItHint::CreateReplacement(SR, Replacement);
}

View File

@ -171,10 +171,10 @@ void RedundantStringCStrCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg");
const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
bool Arrow = Member->isArrow();
const bool Arrow = Member->isArrow();
// Replace the "call" node with the "arg" node, prefixed with '*'
// if the call was using '->' rather than '.'.
std::string ArgText =
const std::string ArgText =
Arrow ? utils::fixit::formatDereference(*Arg, *Result.Context)
: tooling::fixit::getText(*Arg, *Result.Context).str();
if (ArgText.empty())

View File

@ -23,8 +23,8 @@ const char DefaultStringNames[] =
static std::vector<StringRef> removeNamespaces(ArrayRef<StringRef> Names) {
std::vector<StringRef> Result;
Result.reserve(Names.size());
for (StringRef Name : Names) {
StringRef::size_type ColonPos = Name.rfind(':');
for (const StringRef Name : Names) {
const StringRef::size_type ColonPos = Name.rfind(':');
Result.push_back(
Name.drop_front(ColonPos == StringRef::npos ? 0 : ColonPos + 1));
}
@ -125,14 +125,14 @@ void RedundantStringInitCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *VDecl = Result.Nodes.getNodeAs<VarDecl>("vardecl")) {
// VarDecl's getSourceRange() spans 'string foo = ""' or 'string bar("")'.
// So start at getLocation() to span just 'foo = ""' or 'bar("")'.
SourceRange ReplaceRange(VDecl->getLocation(), VDecl->getEndLoc());
const SourceRange ReplaceRange(VDecl->getLocation(), VDecl->getEndLoc());
diag(VDecl->getLocation(), "redundant string initialization")
<< FixItHint::CreateReplacement(ReplaceRange, VDecl->getName());
}
if (const auto *FDecl = Result.Nodes.getNodeAs<FieldDecl>("fieldDecl")) {
// FieldDecl's getSourceRange() spans 'string foo = ""'.
// So start at getLocation() to span just 'foo = ""'.
SourceRange ReplaceRange(FDecl->getLocation(), FDecl->getEndLoc());
const SourceRange ReplaceRange(FDecl->getLocation(), FDecl->getEndLoc());
diag(FDecl->getLocation(), "redundant string initialization")
<< FixItHint::CreateReplacement(ReplaceRange, FDecl->getName());
}

View File

@ -37,7 +37,7 @@ struct NotExtendedByDeclBoundToPredicate {
AST_MATCHER_P(MaterializeTemporaryExpr, isExtendedByDeclBoundTo, StringRef,
ID) {
NotExtendedByDeclBoundToPredicate Predicate{
const NotExtendedByDeclBoundToPredicate Predicate{
ID, ::clang::DynTypedNode::create(Node)};
return Builder->removeBindings(Predicate);
}

View File

@ -203,7 +203,7 @@ static std::string replacementExpression(const ASTContext &Context,
.str(),
NeedsStaticCast));
StringRef Text = getText(Context, *E);
const StringRef Text = getText(Context, *E);
if (!NeedsStaticCast && needsParensAfterUnaryNegation(E))
return ("!(" + Text + ")").str();
@ -366,7 +366,7 @@ public:
* if (false) ThenStmt(); -> <Empty>;
* if (false) ThenStmt(); else ElseStmt() -> ElseStmt();
*/
Expr *Cond = If->getCond()->IgnoreImplicit();
const Expr *Cond = If->getCond()->IgnoreImplicit();
if (std::optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
if (*Bool)
Check->replaceWithThenStatement(Context, If, Cond);
@ -379,9 +379,9 @@ public:
* if (Cond) return true; else return false; -> return Cond;
* if (Cond) return false; else return true; -> return !Cond;
*/
if (ExprAndBool ThenReturnBool =
if (const ExprAndBool ThenReturnBool =
checkSingleStatement(If->getThen(), parseReturnLiteralBool)) {
ExprAndBool ElseReturnBool =
const ExprAndBool ElseReturnBool =
checkSingleStatement(If->getElse(), parseReturnLiteralBool);
if (ElseReturnBool && ThenReturnBool.Bool != ElseReturnBool.Bool) {
if (Check->ChainedConditionalReturn ||
@ -418,9 +418,9 @@ public:
return {ME->getMemberDecl(), *RightasBool};
return {};
};
if (DeclAndBool ThenAssignment =
if (const DeclAndBool ThenAssignment =
checkSingleStatement(If->getThen(), VarBoolAssignmentMatcher)) {
DeclAndBool ElseAssignment =
const DeclAndBool ElseAssignment =
checkSingleStatement(If->getElse(), VarBoolAssignmentMatcher);
if (ElseAssignment.Item == ThenAssignment.Item &&
ElseAssignment.Bool != ThenAssignment.Bool) {
@ -461,7 +461,7 @@ public:
Second != End; ++Second, ++First) {
PrevIf = CurIf;
CurIf = isa<IfStmt>(*First);
ExprAndBool TrailingReturnBool = parseReturnLiteralBool(*Second);
const ExprAndBool TrailingReturnBool = parseReturnLiteralBool(*Second);
if (!TrailingReturnBool)
continue;
@ -473,7 +473,7 @@ public:
auto *If = cast<IfStmt>(*First);
if (!If->hasInitStorage() && !If->hasVarStorage() &&
!If->isConsteval()) {
ExprAndBool ThenReturnBool =
const ExprAndBool ThenReturnBool =
checkSingleStatement(If->getThen(), parseReturnLiteralBool);
if (ThenReturnBool &&
ThenReturnBool.Bool != TrailingReturnBool.Bool) {
@ -497,7 +497,7 @@ public:
auto *SubIf = dyn_cast<IfStmt>(SubStmt);
if (SubIf && !SubIf->getElse() && !SubIf->hasInitStorage() &&
!SubIf->hasVarStorage() && !SubIf->isConsteval()) {
ExprAndBool ThenReturnBool =
const ExprAndBool ThenReturnBool =
checkSingleStatement(SubIf->getThen(), parseReturnLiteralBool);
if (ThenReturnBool &&
ThenReturnBool.Bool != TrailingReturnBool.Bool) {
@ -574,7 +574,7 @@ public:
if (Check->reportDeMorgan(Context, Op, BinaryOp, !IsProcessing, parent(),
Parens) &&
!Check->areDiagsSelfContained()) {
llvm::SaveAndRestore RAII(IsProcessing, true);
const llvm::SaveAndRestore RAII(IsProcessing, true);
return Base::TraverseUnaryOperator(Op);
}
}
@ -638,13 +638,13 @@ void SimplifyBooleanExprCheck::reportBinOp(const ASTContext &Context,
if (!isa<CXXBoolLiteralExpr>(Other) && containsBoolLiteral(Other))
return;
bool BoolValue = Bool->getValue();
const bool BoolValue = Bool->getValue();
auto ReplaceWithExpression = [this, &Context, LHS, RHS,
Bool](const Expr *ReplaceWith, bool Negated) {
std::string Replacement =
const std::string Replacement =
replacementExpression(Context, Negated, ReplaceWith);
SourceRange Range(LHS->getBeginLoc(), RHS->getEndLoc());
const SourceRange Range(LHS->getBeginLoc(), RHS->getEndLoc());
issueDiag(Context, Bool->getBeginLoc(), SimplifyOperatorDiagnostic, Range,
Replacement);
};
@ -706,11 +706,11 @@ bool SimplifyBooleanExprCheck::issueDiag(const ASTContext &Context,
StringRef Description,
SourceRange ReplacementRange,
StringRef Replacement) {
CharSourceRange CharRange =
const CharSourceRange CharRange =
Lexer::makeFileCharRange(CharSourceRange::getTokenRange(ReplacementRange),
Context.getSourceManager(), getLangOpts());
DiagnosticBuilder Diag = diag(Loc, Description);
const DiagnosticBuilder Diag = diag(Loc, Description);
const bool HasReplacement = !containsDiscardedTokens(Context, CharRange);
if (HasReplacement)
Diag << FixItHint::CreateReplacement(CharRange, Replacement);
@ -737,7 +737,7 @@ void SimplifyBooleanExprCheck::replaceWithElseStatement(
void SimplifyBooleanExprCheck::replaceWithCondition(
const ASTContext &Context, const ConditionalOperator *Ternary,
bool Negated) {
std::string Replacement =
const std::string Replacement =
replacementExpression(Context, Negated, Ternary->getCond());
issueDiag(Context, Ternary->getTrueExpr()->getBeginLoc(),
"redundant boolean literal in ternary expression result",
@ -747,11 +747,11 @@ void SimplifyBooleanExprCheck::replaceWithCondition(
void SimplifyBooleanExprCheck::replaceWithReturnCondition(
const ASTContext &Context, const IfStmt *If, const Expr *BoolLiteral,
bool Negated) {
StringRef Terminator = isa<CompoundStmt>(If->getElse()) ? ";" : "";
std::string Condition =
const StringRef Terminator = isa<CompoundStmt>(If->getElse()) ? ";" : "";
const std::string Condition =
replacementExpression(Context, Negated, If->getCond());
std::string Replacement = ("return " + Condition + Terminator).str();
SourceLocation Start = BoolLiteral->getBeginLoc();
const std::string Replacement = ("return " + Condition + Terminator).str();
const SourceLocation Start = BoolLiteral->getBeginLoc();
const bool HasReplacement =
issueDiag(Context, Start, SimplifyConditionalReturnDiagnostic,
@ -795,12 +795,13 @@ void SimplifyBooleanExprCheck::replaceWithAssignment(const ASTContext &Context,
const Expr *Var,
SourceLocation Loc,
bool Negated) {
SourceRange Range = IfAssign->getSourceRange();
StringRef VariableName = getText(Context, *Var);
StringRef Terminator = isa<CompoundStmt>(IfAssign->getElse()) ? ";" : "";
std::string Condition =
const SourceRange Range = IfAssign->getSourceRange();
const StringRef VariableName = getText(Context, *Var);
const StringRef Terminator =
isa<CompoundStmt>(IfAssign->getElse()) ? ";" : "";
const std::string Condition =
replacementExpression(Context, Negated, IfAssign->getCond());
std::string Replacement =
const std::string Replacement =
(VariableName + " = " + Condition + Terminator).str();
issueDiag(Context, Loc, "redundant boolean literal in conditional assignment",
Range, Replacement);

View File

@ -45,8 +45,8 @@ void StaticDefinitionInAnonymousNamespaceCheck::check(
while (Loc < Def->getSourceRange().getEnd() &&
!Lexer::getRawToken(Loc, Tok, *Result.SourceManager, getLangOpts(),
true)) {
SourceRange TokenRange(Tok.getLocation(), Tok.getEndLoc());
StringRef SourceText =
const SourceRange TokenRange(Tok.getLocation(), Tok.getEndLoc());
const StringRef SourceText =
Lexer::getSourceText(CharSourceRange::getTokenRange(TokenRange),
*Result.SourceManager, getLangOpts());
if (SourceText == "static") {

View File

@ -150,8 +150,8 @@ static bool applyAbbreviationHeuristic(
/// Check whether the shorter String is a prefix of the longer String.
static bool applyPrefixHeuristic(StringRef Arg, StringRef Param,
int8_t Threshold) {
StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
const StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
const StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
if (Longer.starts_with_insensitive(Shorter))
return percentage(Shorter.size(), Longer.size()) > Threshold;
@ -162,8 +162,8 @@ static bool applyPrefixHeuristic(StringRef Arg, StringRef Param,
/// Check whether the shorter String is a suffix of the longer String.
static bool applySuffixHeuristic(StringRef Arg, StringRef Param,
int8_t Threshold) {
StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
const StringRef Shorter = Arg.size() < Param.size() ? Arg : Param;
const StringRef Longer = Arg.size() >= Param.size() ? Arg : Param;
if (Longer.ends_with_insensitive(Shorter))
return percentage(Shorter.size(), Longer.size()) > Threshold;
@ -196,13 +196,13 @@ static bool applySubstringHeuristic(StringRef Arg, StringRef Param,
Current.swap(Previous);
}
size_t LongerLength = std::max(Arg.size(), Param.size());
const size_t LongerLength = std::max(Arg.size(), Param.size());
return percentage(MaxLength, LongerLength) > Threshold;
}
static bool applyLevenshteinHeuristic(StringRef Arg, StringRef Param,
int8_t Threshold) {
std::size_t LongerLength = std::max(Arg.size(), Param.size());
const std::size_t LongerLength = std::max(Arg.size(), Param.size());
double Dist = Arg.edit_distance(Param);
Dist = (1.0 - Dist / LongerLength) * 100.0;
return Dist > Threshold;
@ -212,11 +212,11 @@ static bool applyLevenshteinHeuristic(StringRef Arg, StringRef Param,
static bool applyJaroWinklerHeuristic(StringRef Arg, StringRef Param,
int8_t Threshold) {
std::size_t Match = 0, Transpos = 0;
std::ptrdiff_t ArgLen = Arg.size();
std::ptrdiff_t ParamLen = Param.size();
const std::ptrdiff_t ArgLen = Arg.size();
const std::ptrdiff_t ParamLen = Param.size();
SmallVector<int, SmallVectorSize> ArgFlags(ArgLen);
SmallVector<int, SmallVectorSize> ParamFlags(ParamLen);
std::ptrdiff_t Range =
const std::ptrdiff_t Range =
std::max(std::ptrdiff_t{0}, (std::max(ArgLen, ParamLen) / 2) - 1);
// Calculate matching characters.
@ -252,7 +252,7 @@ static bool applyJaroWinklerHeuristic(StringRef Arg, StringRef Param,
Transpos /= 2;
// Jaro distance.
double MatchD = Match;
const double MatchD = Match;
double Dist = ((MatchD / ArgLen) + (MatchD / ParamLen) +
((MatchD - Transpos) / Match)) /
3.0;
@ -347,7 +347,7 @@ static bool arePointersStillQualCompatible(QualType ArgType, QualType ParamType,
// The types are compatible, if the parameter is at least as qualified as the
// argument, and if it is more qualified, it has to be const on upper pointer
// levels.
bool AreTypesQualCompatible =
const bool AreTypesQualCompatible =
ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx) &&
(!ParamType.hasQualifiers() || IsParamContinuouslyConst);
// Check whether the parameter's constness continues at the current pointer
@ -401,7 +401,7 @@ static bool areTypesCompatible(QualType ArgType, QualType ParamType,
if (!areRefAndQualCompatible(ArgType, ParamType, Ctx))
return false;
bool IsParamReference = ParamType->isReferenceType();
const bool IsParamReference = ParamType->isReferenceType();
// Reference-ness has already been checked and should be removed
// before further checking.
@ -438,7 +438,7 @@ static bool areTypesCompatible(QualType ArgType, QualType ParamType,
if (IsParamReference && ParamType->isArrayType())
return isCompatibleWithArrayReference(ArgType, ParamType, Ctx);
bool IsParamContinuouslyConst =
const bool IsParamContinuouslyConst =
!IsParamReference || ParamType.getNonReferenceType().isConstQualified();
// Remove the first level of indirection.
@ -513,9 +513,9 @@ SuspiciousCallArgumentCheck::SuspiciousCallArgumentCheck(
SmallString<32> Key = HeuristicToString[Idx];
Key.append(BK == BoundKind::DissimilarBelow ? "DissimilarBelow"
: "SimilarAbove");
int8_t Default = BK == BoundKind::DissimilarBelow
? Defaults[Idx].DissimilarBelow
: Defaults[Idx].SimilarAbove;
const int8_t Default = BK == BoundKind::DissimilarBelow
? Defaults[Idx].DissimilarBelow
: Defaults[Idx].SimilarAbove;
return Options.get(Key, Default);
};
for (std::size_t Idx = 0; Idx < HeuristicCount; ++Idx) {
@ -527,7 +527,7 @@ SuspiciousCallArgumentCheck::SuspiciousCallArgumentCheck(
GetBoundOpt(H, BoundKind::SimilarAbove)));
}
for (StringRef Abbreviation : optutils::parseStringList(
for (const StringRef Abbreviation : optutils::parseStringList(
Options.get("Abbreviations", DefaultAbbreviations))) {
auto KeyAndValue = Abbreviation.split("=");
assert(!KeyAndValue.first.empty() && !KeyAndValue.second.empty());
@ -652,7 +652,7 @@ void SuspiciousCallArgumentCheck::check(
if (ArgNames.empty())
return;
std::size_t ParamCount = ParamNames.size();
const std::size_t ParamCount = ParamNames.size();
// Check similarity.
for (std::size_t I = 0; I < ParamCount; ++I) {
@ -673,9 +673,9 @@ void SuspiciousCallArgumentCheck::check(
<< MatchedCallExpr->getArg(J)->getSourceRange();
// Note at the functions declaration.
SourceLocation IParNameLoc =
const SourceLocation IParNameLoc =
CalleeFuncDecl->getParamDecl(I)->getLocation();
SourceLocation JParNameLoc =
const SourceLocation JParNameLoc =
CalleeFuncDecl->getParamDecl(J)->getLocation();
diag(CalleeFuncDecl->getLocation(), "in the call to %0, declared here",
@ -697,7 +697,7 @@ void SuspiciousCallArgumentCheck::setParamNamesAndTypes(
for (const ParmVarDecl *Param : CalleeFuncDecl->parameters()) {
ParamTypes.push_back(Param->getType());
if (IdentifierInfo *II = Param->getIdentifier())
if (const IdentifierInfo *II = Param->getIdentifier())
ParamNames.push_back(II->getName());
else
ParamNames.push_back(StringRef());
@ -759,16 +759,16 @@ bool SuspiciousCallArgumentCheck::areParamAndArgComparable(
bool SuspiciousCallArgumentCheck::areArgsSwapped(std::size_t Position1,
std::size_t Position2) const {
for (Heuristic H : AppliedHeuristics) {
bool A1ToP2Similar = areNamesSimilar(
for (const Heuristic H : AppliedHeuristics) {
const bool A1ToP2Similar = areNamesSimilar(
ArgNames[Position2], ParamNames[Position1], H, BoundKind::SimilarAbove);
bool A2ToP1Similar = areNamesSimilar(
const bool A2ToP1Similar = areNamesSimilar(
ArgNames[Position1], ParamNames[Position2], H, BoundKind::SimilarAbove);
bool A1ToP1Dissimilar =
const bool A1ToP1Dissimilar =
!areNamesSimilar(ArgNames[Position1], ParamNames[Position1], H,
BoundKind::DissimilarBelow);
bool A2ToP2Dissimilar =
const bool A2ToP2Dissimilar =
!areNamesSimilar(ArgNames[Position2], ParamNames[Position2], H,
BoundKind::DissimilarBelow);

View File

@ -110,7 +110,7 @@ shouldReplaceLiteralSuffix(const Expr &Literal,
ReplacementDsc.LiteralLocation = L.getSourceRange();
// Was this literal fully spelled or is it a product of macro expansion?
bool RangeCanBeFixed =
const bool RangeCanBeFixed =
utils::rangeCanBeFixed(ReplacementDsc.LiteralLocation, &SM);
// The literal may have macro expansion, we need the final expanded src range.

View File

@ -20,7 +20,7 @@ namespace {
/// followed by a Stmt matching the inner matcher.
AST_MATCHER_P(Stmt, nextStmt, ast_matchers::internal::Matcher<Stmt>,
InnerMatcher) {
DynTypedNodeList Parents = Finder->getASTContext().getParents(Node);
const DynTypedNodeList Parents = Finder->getASTContext().getParents(Node);
if (Parents.size() != 1)
return false;

View File

@ -77,11 +77,11 @@ static QualType getNonTemplateAlias(QualType QT) {
static QualType getReplacementCastType(const Expr *CondLhs, const Expr *CondRhs,
QualType ComparedType) {
QualType LhsType = CondLhs->getType();
QualType RhsType = CondRhs->getType();
QualType LhsCanonicalType =
const QualType LhsType = CondLhs->getType();
const QualType RhsType = CondRhs->getType();
const QualType LhsCanonicalType =
LhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType();
QualType RhsCanonicalType =
const QualType RhsCanonicalType =
RhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType();
QualType GlobalImplicitCastType;
if (LhsCanonicalType != RhsCanonicalType) {
@ -109,7 +109,7 @@ static std::string createReplacement(const Expr *CondLhs, const Expr *CondRhs,
const llvm::StringRef AssignLhsStr = Lexer::getSourceText(
Source.getExpansionRange(AssignLhs->getSourceRange()), Source, LO);
QualType GlobalImplicitCastType =
const QualType GlobalImplicitCastType =
getReplacementCastType(CondLhs, CondRhs, BO->getLHS()->getType());
return (AssignLhsStr + " = " + FunctionName +