Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 22 additions & 17 deletions clang-tools-extra/clang-tidy/ClangTidy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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);
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
}

Expand All @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clang-tidy/ClangTidyCheck.h
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
58 changes: 30 additions & 28 deletions clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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);
};
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand All @@ -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));
Expand All @@ -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);
}
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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) &&
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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);
}
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -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);
}
};
Expand Down Expand Up @@ -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 =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Structural binding? But this could be left for dedicated pull request.

Copy link
Contributor Author

@vbvictor vbvictor Nov 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have the check in main for structured binding, but we sure will convert everything once it's landed.

I don't see much value now in fixing one by one by hand.

UniqueErrors.insert(&Error);

// Unique error, we keep it and move along.
Expand Down
12 changes: 6 additions & 6 deletions clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -463,16 +463,16 @@ FileOptionsProvider::getRawOptions(StringRef FileName) {
LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
<< "...\n");

llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
const llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
getNormalizedAbsolutePath(FileName);
if (!AbsoluteFilePath)
return {};

std::vector<OptionsSource> RawOptions =
DefaultOptionsProvider::getRawOptions(AbsoluteFilePath->str());
addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
OptionsSource CommandLineOptions(OverrideOptions,
OptionsSourceTypeCheckCommandLineOption);
const OptionsSource CommandLineOptions(
OverrideOptions, OptionsSourceTypeCheckCommandLineOption);

RawOptions.push_back(CommandLineOptions);
return RawOptions;
Expand Down Expand Up @@ -502,7 +502,7 @@ FileOptionsBaseProvider::tryReadConfigFile(StringRef Directory) {

llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
FS->getBufferForFile(ConfigFile);
if (std::error_code EC = Text.getError()) {
if (const std::error_code EC = Text.getError()) {
llvm::errs() << "Can't read " << ConfigFile << ": " << EC.message()
<< "\n";
continue;
Expand Down
Loading