[clang-tools-extra] [clang-tidy][NFC] Fix misc-const-correctness warnings (1/N) (PR #167030)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Nov 7 14:36:13 PST 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tools-extra
Author: Baranov Victor (vbvictor)
<details>
<summary>Changes</summary>
Start fixing `misc-const-correctness` warning to enable the check in config
---
Patch is 25.07 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/167030.diff
8 Files Affected:
- (modified) clang-tools-extra/clang-tidy/ClangTidy.cpp (+22-17)
- (modified) clang-tools-extra/clang-tidy/ClangTidyCheck.cpp (+2-2)
- (modified) clang-tools-extra/clang-tidy/ClangTidyCheck.h (+1-1)
- (modified) clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp (+30-28)
- (modified) clang-tools-extra/clang-tidy/ClangTidyOptions.cpp (+6-6)
- (modified) clang-tools-extra/clang-tidy/ClangTidyProfiling.cpp (+2-1)
- (modified) clang-tools-extra/clang-tidy/GlobList.cpp (+5-4)
- (modified) clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp (+5-5)
``````````diff
diff --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index 7e18f3806a143..76243e9ac50bf 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -117,7 +117,8 @@ class ErrorReporter {
void reportDiagnostic(const ClangTidyError &Error) {
const tooling::DiagnosticMessage &Message = Error.Message;
- SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
+ const SourceLocation Loc =
+ getLocation(Message.FilePath, Message.FileOffset);
// Contains a pair for each attempted fix: location and whether the fix was
// applied successfully.
SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
@@ -157,11 +158,11 @@ class ErrorReporter {
// FIXME: Implement better conflict handling.
llvm::errs() << "Trying to resolve conflict: "
<< llvm::toString(std::move(Err)) << "\n";
- unsigned NewOffset =
+ const unsigned NewOffset =
Replacements.getShiftedCodePosition(R.getOffset());
- unsigned NewLength = Replacements.getShiftedCodePosition(
- R.getOffset() + R.getLength()) -
- NewOffset;
+ const unsigned NewLength = Replacements.getShiftedCodePosition(
+ R.getOffset() + R.getLength()) -
+ NewOffset;
if (NewLength == R.getLength()) {
R = Replacement(R.getFilePath(), NewOffset, NewLength,
R.getReplacementText());
@@ -200,7 +201,7 @@ class ErrorReporter {
for (const auto &FileAndReplacements : FileReplacements) {
Rewriter Rewrite(SourceMgr, LangOpts);
- StringRef File = FileAndReplacements.first();
+ const StringRef File = FileAndReplacements.first();
VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
SourceMgr.getFileManager().getBufferForFile(File);
@@ -210,7 +211,7 @@ class ErrorReporter {
// FIXME: Maybe don't apply fixes for other files as well.
continue;
}
- StringRef Code = Buffer.get()->getBuffer();
+ const StringRef Code = Buffer.get()->getBuffer();
auto Style = format::getStyle(
*Context.getOptionsForFile(File).FormatStyle, File, "none");
if (!Style) {
@@ -262,7 +263,7 @@ class ErrorReporter {
if (!File)
return {};
- FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
+ const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
}
@@ -284,7 +285,8 @@ class ErrorReporter {
}
void reportNote(const tooling::DiagnosticMessage &Message) {
- SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
+ const SourceLocation Loc =
+ getLocation(Message.FilePath, Message.FileOffset);
auto Diag =
Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note, "%0"))
<< Message.Message;
@@ -296,8 +298,9 @@ class ErrorReporter {
CharSourceRange getRange(const FileByteRange &Range) {
SmallString<128> AbsoluteFilePath{Range.FilePath};
Files.makeAbsolutePath(AbsoluteFilePath);
- SourceLocation BeginLoc = getLocation(AbsoluteFilePath, Range.FileOffset);
- SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
+ const SourceLocation BeginLoc =
+ getLocation(AbsoluteFilePath, Range.FileOffset);
+ const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
// Retrieve the source range for applicable highlights and fixes. Macro
// definition on the command line have locations in a virtual buffer and
// don't have valid file paths and are therefore not applicable.
@@ -353,7 +356,8 @@ ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
if (Context.canExperimentalCustomChecks() && custom::RegisterCustomChecks)
custom::RegisterCustomChecks(Context.getOptions(), *CheckFactories);
#endif
- for (ClangTidyModuleRegistry::entry E : ClangTidyModuleRegistry::entries()) {
+ for (ClangTidyModuleRegistry::entry const E :
+ ClangTidyModuleRegistry::entries()) {
std::unique_ptr<ClangTidyModule> Module = E.instantiate();
Module->addCheckFactories(*CheckFactories);
}
@@ -394,8 +398,9 @@ static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
// Always add all core checkers if any other static analyzer check is enabled.
// This is currently necessary, as other path sensitive checks rely on the
// core checkers.
- for (StringRef CheckName : RegisteredCheckers) {
- std::string ClangTidyCheckName((AnalyzerCheckNamePrefix + CheckName).str());
+ for (const StringRef CheckName : RegisteredCheckers) {
+ const std::string ClangTidyCheckName(
+ (AnalyzerCheckNamePrefix + CheckName).str());
if (CheckName.starts_with("core") ||
Context.isCheckEnabled(ClangTidyCheckName)) {
@@ -504,7 +509,7 @@ std::vector<std::string> ClangTidyASTConsumerFactory::getCheckNames() {
ClangTidyOptions::OptionMap ClangTidyASTConsumerFactory::getCheckOptions() {
ClangTidyOptions::OptionMap Options;
- std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
+ const std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
CheckFactories->createChecks(&Context);
for (const auto &Check : Checks)
Check->storeOptions(Options);
@@ -564,7 +569,7 @@ runClangTidy(clang::tidy::ClangTidyContext &Context,
std::make_shared<PCHContainerOperations>(), BaseFS);
// Add extra arguments passed by the clang-tidy command-line.
- ArgumentsAdjuster PerFileExtraArgumentsInserter =
+ const ArgumentsAdjuster PerFileExtraArgumentsInserter =
[&Context](const CommandLineArguments &Args, StringRef Filename) {
ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
CommandLineArguments AdjustedArgs = Args;
@@ -703,7 +708,7 @@ ChecksAndOptions getAllChecksAndOptions(bool AllowEnablingAnalyzerAlphaCheckers,
#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
SmallString<64> Buffer(AnalyzerCheckNamePrefix);
- size_t DefSize = Buffer.size();
+ const size_t DefSize = Buffer.size();
for (const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
AllowEnablingAnalyzerAlphaCheckers)) {
Buffer.truncate(DefSize);
diff --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 6e0c252a80bf8..b747657594ac0 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -161,7 +161,7 @@ ClangTidyCheck::OptionsView::getEnumInt(StringRef LocalName,
if (Iter == CheckOptions.end())
return std::nullopt;
- StringRef Value = Iter->getValue().Value;
+ const StringRef Value = Iter->getValue().Value;
StringRef Closest;
unsigned EditDistance = 3;
for (const auto &NameAndEnum : Mapping) {
@@ -173,7 +173,7 @@ ClangTidyCheck::OptionsView::getEnumInt(StringRef LocalName,
EditDistance = 0;
continue;
}
- unsigned Distance =
+ const unsigned Distance =
Value.edit_distance(NameAndEnum.second, true, EditDistance);
if (Distance < EditDistance) {
EditDistance = Distance;
diff --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index e53ae532d7e5f..905e419cdf0ca 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -458,7 +458,7 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
template <typename T>
std::enable_if_t<std::is_enum_v<T>, std::vector<NameAndValue>>
typeEraseMapping() const {
- ArrayRef<std::pair<T, StringRef>> Mapping =
+ const ArrayRef<std::pair<T, StringRef>> Mapping =
OptionEnumMapping<T>::getEnumMapping();
std::vector<NameAndValue> Result;
Result.reserve(Mapping.size());
diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 65fd09f99ef0f..81a9f932e547d 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -61,7 +61,7 @@ class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
// FIXME: Remove this once there's a better way to pass check names than
// appending the check name to the message in ClangTidyContext::diag and
// using getCustomDiagID.
- std::string CheckNameInMessage = " [" + Error.DiagnosticName + "]";
+ const std::string CheckNameInMessage = " [" + Error.DiagnosticName + "]";
Message.consume_back(CheckNameInMessage);
auto TidyMessage =
@@ -77,7 +77,7 @@ class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
if (SourceRange.isCharRange())
return SourceRange;
assert(SourceRange.isTokenRange());
- SourceLocation End = Lexer::getLocForEndOfToken(
+ const SourceLocation End = Lexer::getLocForEndOfToken(
SourceRange.getEnd(), 0, Loc.getManager(), LangOpts);
return CharSourceRange::getCharRange(SourceRange.getBegin(), End);
};
@@ -114,14 +114,14 @@ class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
Level == DiagnosticsEngine::Note ? &Error.Notes.back() : &Error.Message;
for (const auto &FixIt : Hints) {
- CharSourceRange Range = FixIt.RemoveRange;
+ const CharSourceRange Range = FixIt.RemoveRange;
assert(Range.getBegin().isValid() && Range.getEnd().isValid() &&
"Invalid range in the fix-it hint.");
assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
"Only file locations supported in fix-it hints.");
- tooling::Replacement Replacement(Loc.getManager(), Range,
- FixIt.CodeToInsert);
+ const tooling::Replacement Replacement(Loc.getManager(), Range,
+ FixIt.CodeToInsert);
llvm::Error Err =
DiagWithFix->Fix[Replacement.getFilePath()].add(Replacement);
// FIXME: better error handling (at least, don't let other replacements be
@@ -177,7 +177,7 @@ DiagnosticBuilder ClangTidyContext::diag(
StringRef CheckName, SourceLocation Loc, StringRef Description,
DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
assert(Loc.isValid());
- unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
+ const unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
Level, (Description + " [" + CheckName + "]").str());
CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
return DiagEngine->Report(Loc, ID);
@@ -186,7 +186,7 @@ DiagnosticBuilder ClangTidyContext::diag(
DiagnosticBuilder ClangTidyContext::diag(
StringRef CheckName, StringRef Description,
DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
- unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
+ const unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
Level, (Description + " [" + CheckName + "]").str());
CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
return DiagEngine->Report(ID);
@@ -195,10 +195,11 @@ DiagnosticBuilder ClangTidyContext::diag(
DiagnosticBuilder ClangTidyContext::diag(const tooling::Diagnostic &Error) {
SourceManager &SM = DiagEngine->getSourceManager();
FileManager &FM = SM.getFileManager();
- FileEntryRef File = llvm::cantFail(FM.getFileRef(Error.Message.FilePath));
- FileID ID = SM.getOrCreateFileID(File, SrcMgr::C_User);
- SourceLocation FileStartLoc = SM.getLocForStartOfFile(ID);
- SourceLocation Loc = FileStartLoc.getLocWithOffset(
+ const FileEntryRef File =
+ llvm::cantFail(FM.getFileRef(Error.Message.FilePath));
+ const FileID ID = SM.getOrCreateFileID(File, SrcMgr::C_User);
+ const SourceLocation FileStartLoc = SM.getLocForStartOfFile(ID);
+ const SourceLocation Loc = FileStartLoc.getLocWithOffset(
static_cast<SourceLocation::IntTy>(Error.Message.FileOffset));
return diag(Error.DiagnosticName, Loc, Error.Message.Message,
static_cast<DiagnosticIDs::Level>(Error.DiagLevel));
@@ -214,7 +215,7 @@ bool ClangTidyContext::shouldSuppressDiagnostic(
DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info,
SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, bool AllowIO,
bool EnableNoLintBlocks) {
- std::string CheckName = getCheckName(Info.getID());
+ const std::string CheckName = getCheckName(Info.getID());
return NoLintHandler.shouldSuppress(DiagLevel, Info, CheckName, NoLintErrors,
AllowIO, EnableNoLintBlocks);
}
@@ -226,7 +227,7 @@ void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
static bool parseFileExtensions(llvm::ArrayRef<std::string> AllFileExtensions,
FileExtensionsSet &FileExtensions) {
FileExtensions.clear();
- for (StringRef Suffix : AllFileExtensions) {
+ for (const StringRef Suffix : AllFileExtensions) {
StringRef Extension = Suffix.trim();
if (!llvm::all_of(Extension, isAlphanumeric))
return false;
@@ -294,11 +295,11 @@ bool ClangTidyContext::treatAsError(StringRef CheckName) const {
}
std::string ClangTidyContext::getCheckName(unsigned DiagnosticID) const {
- std::string ClangWarningOption = std::string(
+ const std::string ClangWarningOption = std::string(
DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(DiagnosticID));
if (!ClangWarningOption.empty())
return "clang-diagnostic-" + ClangWarningOption;
- llvm::DenseMap<unsigned, std::string>::const_iterator I =
+ const llvm::DenseMap<unsigned, std::string>::const_iterator I =
CheckNamesByDiagnosticID.find(DiagnosticID);
if (I != CheckNamesByDiagnosticID.end())
return I->second;
@@ -316,7 +317,7 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
void ClangTidyDiagnosticConsumer::finalizeLastError() {
if (!Errors.empty()) {
- ClangTidyError &Error = Errors.back();
+ const ClangTidyError &Error = Errors.back();
if (Error.DiagnosticName == "clang-tidy-config") {
// Never ignore these.
} else if (!Context.isCheckEnabled(Error.DiagnosticName) &&
@@ -436,8 +437,8 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic(
Level = ClangTidyError::Remark;
}
- bool IsWarningAsError = DiagLevel == DiagnosticsEngine::Warning &&
- Context.treatAsError(CheckName);
+ const bool IsWarningAsError = DiagLevel == DiagnosticsEngine::Warning &&
+ Context.treatAsError(CheckName);
Errors.emplace_back(CheckName, Level, Context.getCurrentBuildDirectory(),
IsWarningAsError);
}
@@ -491,8 +492,9 @@ void ClangTidyDiagnosticConsumer::forwardDiagnostic(const Diagnostic &Info) {
// Acquire a diagnostic ID also in the external diagnostics engine.
auto DiagLevelAndFormatString =
Context.getDiagLevelAndFormatString(Info.getID(), Info.getLocation());
- unsigned ExternalID = ExternalDiagEngine->getDiagnosticIDs()->getCustomDiagID(
- DiagLevelAndFormatString.first, DiagLevelAndFormatString.second);
+ const unsigned ExternalID =
+ ExternalDiagEngine->getDiagnosticIDs()->getCustomDiagID(
+ DiagLevelAndFormatString.first, DiagLevelAndFormatString.second);
// Forward the details.
auto Builder = ExternalDiagEngine->Report(Info.getLocation(), ExternalID);
@@ -501,7 +503,7 @@ void ClangTidyDiagnosticConsumer::forwardDiagnostic(const Diagnostic &Info) {
for (auto Range : Info.getRanges())
Builder << Range;
for (unsigned Index = 0; Index < Info.getNumArgs(); ++Index) {
- DiagnosticsEngine::ArgumentKind Kind = Info.getArgKind(Index);
+ const DiagnosticsEngine::ArgumentKind Kind = Info.getArgKind(Index);
switch (Kind) {
case clang::DiagnosticsEngine::ak_std_string:
Builder << Info.getArgStdStr(Index);
@@ -574,7 +576,7 @@ void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
// FIXME: We start with a conservative approach here, but the actual type of
// location needed depends on the check (in particular, where this check wants
// to apply fixes).
- FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
+ const FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
OptionalFileEntryRef File = Sources.getFileEntryRefForID(FID);
// -DMACRO definitions on the command line have locations in a virtual buffer
@@ -585,13 +587,13 @@ void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
return;
}
- StringRef FileName(File->getName());
+ const StringRef FileName(File->getName());
LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
Sources.isInMainFile(Location) ||
(getHeaderFilter()->match(FileName) &&
!getExcludeHeaderFilter()->match(FileName));
- unsigned LineNumber = Sources.getExpansionLineNumber(Location);
+ const unsigned LineNumber = Sources.getExpansionLineNumber(Location);
LastErrorPassesLineFilter =
LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
}
@@ -707,8 +709,8 @@ void ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
for (const auto &FileAndReplace : *ErrorFixes[I].second) {
for (const auto &Replace : FileAndReplace.second) {
- unsigned Begin = Replace.getOffset();
- unsigned End = Begin + Replace.getLength();
+ const unsigned Begin = Replace.getOffset();
+ const unsigned End = Begin + Replace.getLength();
auto &Events = FileEvents[Replace.getFilePath()];
if (Begin == End) {
Events.emplace_back(Begin, End, Event::ET_Insert, I, Sizes[I]);
@@ -767,7 +769,7 @@ struct LessClangTidyError {
};
struct EqualClangTidyError {
bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
- LessClangTidyError Less;
+ const LessClangTidyError Less;
return !Less(LHS, RHS) && !Less(RHS, LHS);
}
};
@@ -803,7 +805,7 @@ void ClangTidyDiagnosticConsumer::removeDuplicatedDiagnosticsOfAliasCheckers() {
auto IT = Errors.begin();
while (IT != Errors.end()) {
ClangTidyError &Error = *IT;
- std::pair<UniqueErrorSet::iterator, bool> Inserted =
+ const std::pair<UniqueErrorSet::iterator, bool> Inserted =
UniqueErrors.insert(&Error);
// Unique error, we keep it and move along.
diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index c4b47a440e44b..550f7809d75f9 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -119,7 +119,7 @@ void yamlize(IO &IO, ClangTidyOptions::OptionMap &Val, bool,
yamlize(IO, NOpts->Options, true, Ctx);
} else if (isa<MappingNode>(I.getCurrentNode())) {
IO.beginMapping();
- for (StringRef Key : IO.keys()) {
+ for (const StringRef Key : IO.keys()) {
// Requires 'llvm::yaml::IO' to accept 'StringRef'
// NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage)
IO.mapRequired(Key.data(), Val[Key].Value);
@@ -392,7 +392,7 @@ llvm::ErrorOr<llvm::SmallString<128>>
FileOptionsBaseProvider::getNormalizedAbsolutePath(llvm::StringRef Path) {
assert(FS && "FS must be set.");
llvm::SmallString<128> NormalizedAbsolutePath = {Path};
- std::error_code Err = FS->makeAbsolute(NormalizedAbsolutePath);
+ const std::error_code Err = FS->makeAbsolute(NormalizedAbsolutePath);
if (Err)
return Err;
llvm::sys::path::remove_dots(NormalizedAbsolutePath, /*remove_dot_dot=*/true);
@@ -463,7 +463,7 @@ FileOptionsProvider::getRawOptions(StringRef FileName) {
LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
<< "...\n");
- llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFi...
[truncated]
``````````
</details>
https://github.com/llvm/llvm-project/pull/167030
More information about the cfe-commits
mailing list