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

This commit is contained in:
Baranov Victor 2025-11-08 02:15:16 +03:00 committed by GitHub
parent 74e34eff3f
commit c3740802b6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
21 changed files with 137 additions and 121 deletions

View File

@ -67,7 +67,7 @@ bool rangeIsEntirelyWithinMacroArgument(SourceRange Range,
// Check if the range is entirely contained within a macro argument.
SourceLocation MacroArgExpansionStartForRangeBegin;
SourceLocation MacroArgExpansionStartForRangeEnd;
bool RangeIsEntirelyWithinMacroArgument =
const bool RangeIsEntirelyWithinMacroArgument =
SM &&
SM->isMacroArgExpansion(Range.getBegin(),
&MacroArgExpansionStartForRangeBegin) &&

View File

@ -48,7 +48,8 @@ FixItHint BraceInsertionHints::closingBraceFixIt() const {
static tok::TokenKind getTokenKind(SourceLocation Loc, const SourceManager &SM,
const LangOptions &LangOpts) {
Token Tok;
SourceLocation Beginning = Lexer::GetBeginningOfToken(Loc, SM, LangOpts);
const SourceLocation Beginning =
Lexer::GetBeginningOfToken(Loc, SM, LangOpts);
const bool Invalid = Lexer::getRawToken(Beginning, Tok, SM, LangOpts);
assert(!Invalid && "Expected a valid token.");
@ -77,15 +78,16 @@ static SourceLocation findEndLocation(const Stmt &S, const SourceManager &SM,
// EOL, insert brace before.
break;
}
tok::TokenKind TokKind = getTokenKind(Loc, SM, LangOpts);
const tok::TokenKind TokKind = getTokenKind(Loc, SM, LangOpts);
if (TokKind != tok::comment) {
// Non-comment token, insert brace before.
break;
}
SourceLocation TokEndLoc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
SourceRange TokRange(Loc, TokEndLoc);
StringRef Comment = Lexer::getSourceText(
const SourceLocation TokEndLoc =
Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
const SourceRange TokRange(Loc, TokEndLoc);
const StringRef Comment = Lexer::getSourceText(
CharSourceRange::getTokenRange(TokRange), SM, LangOpts);
if (Comment.starts_with("/*") && Comment.contains('\n')) {
// Multi-line block comment, insert brace before.

View File

@ -63,7 +63,7 @@ static bool hasSameParameterTypes(const CXXMethodDecl &D,
static const CXXMethodDecl *findConstOverload(const CXXMethodDecl &D) {
assert(!D.isConst());
DeclContext::lookup_result LookupResult =
const DeclContext::lookup_result LookupResult =
D.getParent()->lookup(D.getNameInfo().getName());
if (LookupResult.isSingleResult()) {
// No overload.

View File

@ -360,8 +360,9 @@ ExceptionAnalyzer::ExceptionInfo::filterByCatch(const Type *HandlerTy,
llvm::SmallVector<const Type *, 8> TypesToDelete;
for (const auto &ThrownException : ThrownExceptions) {
const Type *ExceptionTy = ThrownException.getFirst();
CanQualType ExceptionCanTy = ExceptionTy->getCanonicalTypeUnqualified();
CanQualType HandlerCanTy = HandlerTy->getCanonicalTypeUnqualified();
const CanQualType ExceptionCanTy =
ExceptionTy->getCanonicalTypeUnqualified();
const CanQualType HandlerCanTy = HandlerTy->getCanonicalTypeUnqualified();
// The handler is of type cv T or cv T& and E and T are the same type
// (ignoring the top-level cv-qualifiers) ...
@ -476,7 +477,7 @@ ExceptionAnalyzer::ExceptionInfo ExceptionAnalyzer::throwsException(
// For a constructor, we also have to check the initializers.
if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Func)) {
for (const CXXCtorInitializer *Init : Ctor->inits()) {
ExceptionInfo Excs =
const ExceptionInfo Excs =
throwsException(Init->getInit(), Caught, CallStack);
Result.merge(Excs);
}
@ -533,7 +534,7 @@ ExceptionAnalyzer::throwsException(const Stmt *St,
// Everything is caught through 'catch(...)'.
if (!Catch->getExceptionDecl()) {
ExceptionInfo Rethrown = throwsException(
const ExceptionInfo Rethrown = throwsException(
Catch->getHandlerBlock(), Uncaught.getExceptions(), CallStack);
Results.merge(Rethrown);
Uncaught.clear();
@ -554,7 +555,7 @@ ExceptionAnalyzer::throwsException(const Stmt *St,
Uncaught.filterByCatch(CaughtType,
Catch->getExceptionDecl()->getASTContext());
if (!FilteredExceptions.empty()) {
ExceptionInfo Rethrown = throwsException(
const ExceptionInfo Rethrown = throwsException(
Catch->getHandlerBlock(), FilteredExceptions, CallStack);
Results.merge(Rethrown);
}
@ -563,44 +564,46 @@ ExceptionAnalyzer::throwsException(const Stmt *St,
Results.merge(Uncaught);
} else if (const auto *Call = dyn_cast<CallExpr>(St)) {
if (const FunctionDecl *Func = Call->getDirectCallee()) {
ExceptionInfo Excs =
const ExceptionInfo Excs =
throwsException(Func, Caught, CallStack, Call->getBeginLoc());
Results.merge(Excs);
}
} else if (const auto *Construct = dyn_cast<CXXConstructExpr>(St)) {
ExceptionInfo Excs = throwsException(Construct->getConstructor(), Caught,
CallStack, Construct->getBeginLoc());
const ExceptionInfo Excs =
throwsException(Construct->getConstructor(), Caught, CallStack,
Construct->getBeginLoc());
Results.merge(Excs);
} else if (const auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(St)) {
ExceptionInfo Excs =
const ExceptionInfo Excs =
throwsException(DefaultInit->getExpr(), Caught, CallStack);
Results.merge(Excs);
} else if (const auto *Coro = dyn_cast<CoroutineBodyStmt>(St)) {
for (const Stmt *Child : Coro->childrenExclBody()) {
if (Child != Coro->getExceptionHandler()) {
ExceptionInfo Excs = throwsException(Child, Caught, CallStack);
const ExceptionInfo Excs = throwsException(Child, Caught, CallStack);
Results.merge(Excs);
}
}
ExceptionInfo Excs = throwsException(Coro->getBody(), Caught, CallStack);
const ExceptionInfo Excs =
throwsException(Coro->getBody(), Caught, CallStack);
Results.merge(throwsException(Coro->getExceptionHandler(),
Excs.getExceptions(), CallStack));
for (const auto &Exception : Excs.getExceptions()) {
const Type *ExcType = Exception.getFirst();
if (const CXXRecordDecl *ThrowableRec = ExcType->getAsCXXRecordDecl()) {
ExceptionInfo DestructorExcs = throwsException(
const ExceptionInfo DestructorExcs = throwsException(
ThrowableRec->getDestructor(), Caught, CallStack, SourceLocation{});
Results.merge(DestructorExcs);
}
}
} else if (const auto *Lambda = dyn_cast<LambdaExpr>(St)) {
for (const Stmt *Init : Lambda->capture_inits()) {
ExceptionInfo Excs = throwsException(Init, Caught, CallStack);
const ExceptionInfo Excs = throwsException(Init, Caught, CallStack);
Results.merge(Excs);
}
} else {
for (const Stmt *Child : St->children()) {
ExceptionInfo Excs = throwsException(Child, Caught, CallStack);
const ExceptionInfo Excs = throwsException(Child, Caught, CallStack);
Results.merge(Excs);
}
}

View File

@ -20,7 +20,7 @@ ExceptionSpecAnalyzer::analyze(const FunctionDecl *FuncDecl) {
const auto [CacheEntry, NotFound] =
FunctionCache.try_emplace(FuncDecl, State::NotThrowing);
if (NotFound) {
ExceptionSpecAnalyzer::State State = analyzeImpl(FuncDecl);
const ExceptionSpecAnalyzer::State State = analyzeImpl(FuncDecl);
// Update result with calculated value
FunctionCache[FuncDecl] = State;
return State;
@ -87,20 +87,20 @@ ExceptionSpecAnalyzer::analyzeRecord(const CXXRecordDecl *RecordDecl,
return analyze(MethodDecl);
for (const auto &BaseSpec : RecordDecl->bases()) {
State Result = analyzeBase(BaseSpec, Kind);
const State Result = analyzeBase(BaseSpec, Kind);
if (Result == State::Throwing || Result == State::Unknown)
return Result;
}
for (const auto &BaseSpec : RecordDecl->vbases()) {
State Result = analyzeBase(BaseSpec, Kind);
const State Result = analyzeBase(BaseSpec, Kind);
if (Result == State::Throwing || Result == State::Unknown)
return Result;
}
for (const auto *FDecl : RecordDecl->fields())
if (!FDecl->isInvalidDecl() && !FDecl->isUnnamedBitField()) {
State Result = analyzeFieldDecl(FDecl, Kind);
const State Result = analyzeFieldDecl(FDecl, Kind);
if (Result == State::Throwing || Result == State::Unknown)
return Result;
}

View File

@ -29,13 +29,13 @@ static SmallVector<const Stmt *, 1> getParentStmts(const Stmt *S,
ASTContext *Context) {
SmallVector<const Stmt *, 1> Result;
TraversalKindScope RAII(*Context, TK_AsIs);
const TraversalKindScope RAII(*Context, TK_AsIs);
DynTypedNodeList Parents = Context->getParents(*S);
SmallVector<DynTypedNode, 1> NodesToProcess(Parents.begin(), Parents.end());
while (!NodesToProcess.empty()) {
DynTypedNode Node = NodesToProcess.back();
const DynTypedNode Node = NodesToProcess.back();
NodesToProcess.pop_back();
if (const auto *S = Node.get<Stmt>()) {
@ -95,7 +95,8 @@ bool ExprSequence::inSequence(const Stmt *Before, const Stmt *After) const {
return true;
}
SmallVector<const Stmt *, 1> BeforeParents = getParentStmts(Before, Context);
const SmallVector<const Stmt *, 1> BeforeParents =
getParentStmts(Before, Context);
// Since C++17, the callee of a call expression is guaranteed to be sequenced
// before all of the arguments.

View File

@ -15,19 +15,19 @@ namespace clang::tidy::utils {
bool isExpansionLocInHeaderFile(SourceLocation Loc, const SourceManager &SM,
const FileExtensionsSet &HeaderFileExtensions) {
SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
const SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
return isFileExtension(SM.getFilename(ExpansionLoc), HeaderFileExtensions);
}
bool isPresumedLocInHeaderFile(SourceLocation Loc, SourceManager &SM,
const FileExtensionsSet &HeaderFileExtensions) {
PresumedLoc PresumedLocation = SM.getPresumedLoc(Loc);
const PresumedLoc PresumedLocation = SM.getPresumedLoc(Loc);
return isFileExtension(PresumedLocation.getFilename(), HeaderFileExtensions);
}
bool isSpellingLocInHeaderFile(SourceLocation Loc, SourceManager &SM,
const FileExtensionsSet &HeaderFileExtensions) {
SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
const SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
return isFileExtension(SM.getFilename(SpellingLoc), HeaderFileExtensions);
}
@ -35,7 +35,7 @@ bool parseFileExtensions(StringRef AllFileExtensions,
FileExtensionsSet &FileExtensions,
StringRef Delimiters) {
SmallVector<StringRef, 5> Suffixes;
for (char Delimiter : Delimiters) {
for (const char Delimiter : Delimiters) {
if (AllFileExtensions.contains(Delimiter)) {
AllFileExtensions.split(Suffixes, Delimiter);
break;
@ -43,7 +43,7 @@ bool parseFileExtensions(StringRef AllFileExtensions,
}
FileExtensions.clear();
for (StringRef Suffix : Suffixes) {
for (const StringRef Suffix : Suffixes) {
StringRef Extension = Suffix.trim();
if (!llvm::all_of(Extension, isAlphanumeric))
return false;

View File

@ -140,7 +140,7 @@ changePointer(const VarDecl &Var, Qualifiers::TQ Qualifier, const Type *Pointee,
// the `*` token and placing the `const` left of it.
// (`int const* p = nullptr;`)
if (QualPolicy == QualifierPolicy::Right) {
SourceLocation BeforeStar = lexer::findPreviousTokenKind(
const SourceLocation BeforeStar = lexer::findPreviousTokenKind(
Var.getLocation(), Context.getSourceManager(), Context.getLangOpts(),
tok::star);
if (locDangerous(BeforeStar))
@ -161,7 +161,7 @@ changePointer(const VarDecl &Var, Qualifiers::TQ Qualifier, const Type *Pointee,
// is the same as 'QualPolicy == Right && isValueType(Pointee)'.
// The `const` must be left of the last `*` token.
// (`int * const* p = nullptr;`)
SourceLocation BeforeStar = lexer::findPreviousTokenKind(
const SourceLocation BeforeStar = lexer::findPreviousTokenKind(
Var.getLocation(), Context.getSourceManager(), Context.getLangOpts(),
tok::star);
return fixIfNotDangerous(BeforeStar, buildQualifier(Qualifier, true));
@ -178,7 +178,7 @@ changeReferencee(const VarDecl &Var, Qualifiers::TQ Qualifier, QualType Pointee,
return fixIfNotDangerous(Var.getTypeSpecStartLoc(),
buildQualifier(Qualifier));
SourceLocation BeforeRef = lexer::findPreviousAnyTokenKind(
const SourceLocation BeforeRef = lexer::findPreviousAnyTokenKind(
Var.getLocation(), Context.getSourceManager(), Context.getLangOpts(),
tok::amp, tok::ampamp);
std::optional<SourceLocation> IgnoredParens =
@ -201,7 +201,7 @@ std::optional<FixItHint> addQualifierToVarDecl(const VarDecl &Var,
QualTarget == QualifierTarget::Value) &&
"Unexpected Target");
QualType ParenStrippedType = Var.getType().IgnoreParens();
const QualType ParenStrippedType = Var.getType().IgnoreParens();
if (isValueType(ParenStrippedType))
return changeValue(Var, Qualifier, QualTarget, QualPolicy, Context);

View File

@ -245,7 +245,7 @@ FormatStringConverter::formatStringContainsUnreplaceableMacro(
// inhibit conversion. The whole format string will appear to come from that
// macro, as will the function call.
std::optional<StringRef> MaybeSurroundingMacroName;
if (SourceLocation BeginCallLoc = Call->getBeginLoc();
if (const SourceLocation BeginCallLoc = Call->getBeginLoc();
BeginCallLoc.isMacroID())
MaybeSurroundingMacroName =
Lexer::getImmediateMacroName(BeginCallLoc, SM, PP.getLangOpts());
@ -283,7 +283,8 @@ FormatStringConverter::formatStringContainsUnreplaceableMacro(
void FormatStringConverter::emitAlignment(const PrintfSpecifier &FS,
std::string &FormatSpec) {
ConversionSpecifier::Kind ArgKind = FS.getConversionSpecifier().getKind();
const ConversionSpecifier::Kind ArgKind =
FS.getConversionSpecifier().getKind();
// We only care about alignment if a field width is specified
if (FS.getFieldWidth().getHowSpecified() != OptionalAmount::NotSpecified) {
@ -499,7 +500,8 @@ bool FormatStringConverter::emitIntegerArgument(
/// @returns true on success, false on failure
bool FormatStringConverter::emitType(const PrintfSpecifier &FS, const Expr *Arg,
std::string &FormatSpec) {
ConversionSpecifier::Kind ArgKind = FS.getConversionSpecifier().getKind();
const ConversionSpecifier::Kind ArgKind =
FS.getConversionSpecifier().getKind();
switch (ArgKind) {
case ConversionSpecifier::Kind::sArg:
emitStringArgument(FS.getArgIndex() + ArgsOffset, Arg);
@ -798,7 +800,7 @@ void FormatStringConverter::applyFixes(DiagnosticBuilder &Diag,
}
for (const auto &[ArgIndex, Replacement] : ArgFixes) {
SourceLocation AfterOtherSide =
const SourceLocation AfterOtherSide =
Lexer::findNextToken(Args[ArgIndex]->getEndLoc(), SM, LangOpts)
->getLocation();

View File

@ -32,11 +32,11 @@ public:
FileID PrevFID) override {
// Record all files we enter. We'll need them to diagnose headers without
// guards.
SourceManager &SM = PP->getSourceManager();
const SourceManager &SM = PP->getSourceManager();
if (Reason == EnterFile && FileType == SrcMgr::C_User) {
if (OptionalFileEntryRef FE =
SM.getFileEntryRefForID(SM.getFileID(Loc))) {
std::string FileName = cleanPath(FE->getName());
const std::string FileName = cleanPath(FE->getName());
Files[FileName] = *FE;
}
}
@ -66,7 +66,7 @@ public:
void EndOfMainFile() override {
// Now that we have all this information from the preprocessor, use it!
SourceManager &SM = PP->getSourceManager();
const SourceManager &SM = PP->getSourceManager();
for (const auto &MacroEntry : Macros) {
const MacroInfo *MI = MacroEntry.second;
@ -79,7 +79,7 @@ public:
OptionalFileEntryRef FE =
SM.getFileEntryRefForID(SM.getFileID(MI->getDefinitionLoc()));
std::string FileName = cleanPath(FE->getName());
const std::string FileName = cleanPath(FE->getName());
Files.erase(FileName);
// See if we should check and fix this header guard.
@ -88,16 +88,16 @@ public:
// Look up Locations for this guard.
const auto &Locs = Ifndefs[MacroEntry.first.getIdentifierInfo()];
SourceLocation Ifndef = Locs.second;
SourceLocation Define = MacroEntry.first.getLocation();
SourceLocation EndIf = EndIfs[Locs.first];
const SourceLocation Ifndef = Locs.second;
const SourceLocation Define = MacroEntry.first.getLocation();
const SourceLocation EndIf = EndIfs[Locs.first];
// If the macro Name is not equal to what we can compute, correct it in
// the #ifndef and #define.
StringRef CurHeaderGuard =
const StringRef CurHeaderGuard =
MacroEntry.first.getIdentifierInfo()->getName();
std::vector<FixItHint> FixIts;
std::string NewGuard = checkHeaderGuardDefinition(
const std::string NewGuard = checkHeaderGuardDefinition(
Ifndef, Define, EndIf, FileName, CurHeaderGuard, FixIts);
// Now look at the #endif. We want a comment with the header guard. Fix it
@ -129,7 +129,7 @@ public:
if (!EndIf.isValid())
return false;
const char *EndIfData = PP->getSourceManager().getCharacterData(EndIf);
size_t EndIfLen = std::strcspn(EndIfData, "\r\n");
const size_t EndIfLen = std::strcspn(EndIfData, "\r\n");
if (EndIfLenPtr)
*EndIfLenPtr = EndIfLen;
@ -137,12 +137,12 @@ public:
EndIfStr = EndIfStr.substr(EndIfStr.find_first_not_of("#endif \t"));
// Give up if there's an escaped newline.
size_t FindEscapedNewline = EndIfStr.find_last_not_of(' ');
const size_t FindEscapedNewline = EndIfStr.find_last_not_of(' ');
if (FindEscapedNewline != StringRef::npos &&
EndIfStr[FindEscapedNewline] == '\\')
return false;
bool IsLineComment =
const bool IsLineComment =
EndIfStr.consume_front("//") ||
(EndIfStr.consume_front("/*") && EndIfStr.consume_back("*/"));
if (!IsLineComment)
@ -162,7 +162,7 @@ public:
std::vector<FixItHint> &FixIts) {
std::string CPPVar = Check->getHeaderGuard(FileName, CurHeaderGuard);
CPPVar = Check->sanitizeHeaderGuard(CPPVar);
std::string CPPVarUnder = CPPVar + '_';
const std::string CPPVarUnder = CPPVar + '_';
// Allow a trailing underscore if and only if we don't have to change the
// endif comment too.
@ -203,19 +203,20 @@ public:
// fix-its to add the guard.
// TODO: Insert the guard after top comments.
for (const auto &FE : Files) {
StringRef FileName = FE.getKey();
const StringRef FileName = FE.getKey();
if (!Check->shouldSuggestToAddHeaderGuard(FileName))
continue;
SourceManager &SM = PP->getSourceManager();
FileID FID = SM.translateFile(FE.getValue());
SourceLocation StartLoc = SM.getLocForStartOfFile(FID);
const SourceManager &SM = PP->getSourceManager();
const FileID FID = SM.translateFile(FE.getValue());
const SourceLocation StartLoc = SM.getLocForStartOfFile(FID);
if (StartLoc.isInvalid())
continue;
std::string CPPVar = Check->getHeaderGuard(FileName);
CPPVar = Check->sanitizeHeaderGuard(CPPVar);
std::string CPPVarUnder = CPPVar + '_'; // Allow a trailing underscore.
const std::string CPPVarUnder =
CPPVar + '_'; // Allow a trailing underscore.
// If there's a macro with a name that follows the header guard convention
// but was not recognized by the preprocessor as a header guard there must
// be code outside of the guarded area. Emit a plain warning without
@ -223,8 +224,8 @@ public:
// FIXME: Can we move it into the right spot?
bool SeenMacro = false;
for (const auto &MacroEntry : Macros) {
StringRef Name = MacroEntry.first.getIdentifierInfo()->getName();
SourceLocation DefineLoc = MacroEntry.first.getLocation();
const StringRef Name = MacroEntry.first.getIdentifierInfo()->getName();
const SourceLocation DefineLoc = MacroEntry.first.getLocation();
if ((Name == CPPVar || Name == CPPVarUnder) &&
SM.isWrittenInSameFile(StartLoc, DefineLoc)) {
Check->diag(DefineLoc, "code/includes outside of area guarded by "

View File

@ -69,7 +69,7 @@ IncludeSorter &IncludeInserter::getOrCreate(FileID FileID) {
std::optional<FixItHint>
IncludeInserter::createIncludeInsertion(FileID FileID, llvm::StringRef Header) {
bool IsAngled = Header.consume_front("<");
const bool IsAngled = Header.consume_front("<");
if (IsAngled != Header.consume_back(">"))
return std::nullopt;
// We assume the same Header will never be included both angled and not
@ -94,7 +94,7 @@ void IncludeInserter::addInclude(StringRef FileName, bool IsAngled,
SourceLocation EndLocation) {
assert(SourceMgr && "SourceMgr shouldn't be null; did you remember to call "
"registerPreprocessor()?");
FileID FileID = SourceMgr->getFileID(HashLocation);
const FileID FileID = SourceMgr->getFileID(HashLocation);
getOrCreate(FileID).addInclude(FileName, IsAngled, HashLocation, EndLocation);
}

View File

@ -17,7 +17,7 @@ namespace utils {
static StringRef removeFirstSuffix(StringRef Str,
ArrayRef<const char *> Suffixes) {
for (StringRef Suffix : Suffixes) {
for (const StringRef Suffix : Suffixes) {
if (Str.consume_back(Suffix))
return Str;
}
@ -37,7 +37,7 @@ static StringRef makeCanonicalName(StringRef Str,
removeFirstSuffix(Str, {".cc", ".cpp", ".c", ".h", ".hpp"}), {"Test"});
}
if (Style == IncludeSorter::IS_Google_ObjC) {
StringRef Canonical =
const StringRef Canonical =
removeFirstSuffix(removeFirstSuffix(Str, {".cc", ".cpp", ".c", ".h",
".hpp", ".mm", ".m"}),
{"_unittest", "_regtest", "_test", "Test"});
@ -57,7 +57,7 @@ static StringRef makeCanonicalName(StringRef Str,
// Scan to the end of the line and return the offset of the next line.
static size_t findNextLine(const char *Text) {
size_t EOLIndex = std::strcspn(Text, "\n");
const size_t EOLIndex = std::strcspn(Text, "\n");
return Text[EOLIndex] == '\0' ? EOLIndex : EOLIndex + 1;
}
@ -74,14 +74,15 @@ determineIncludeKind(StringRef CanonicalFile, StringRef IncludeFile,
return IncludeFile.ends_with(".h") ? IncludeSorter::IK_CSystemInclude
: IncludeSorter::IK_CXXSystemInclude;
}
StringRef CanonicalInclude = makeCanonicalName(IncludeFile, Style);
const StringRef CanonicalInclude = makeCanonicalName(IncludeFile, Style);
if (CanonicalFile.ends_with(CanonicalInclude) ||
CanonicalInclude.ends_with(CanonicalFile)) {
return IncludeSorter::IK_MainTUInclude;
}
if ((Style == IncludeSorter::IS_Google) ||
(Style == IncludeSorter::IS_Google_ObjC)) {
std::pair<StringRef, StringRef> Parts = CanonicalInclude.split("/public/");
const std::pair<StringRef, StringRef> Parts =
CanonicalInclude.split("/public/");
StringRef FileCopy = CanonicalFile;
if (FileCopy.consume_front(Parts.first) &&
FileCopy.consume_back(Parts.second)) {
@ -126,7 +127,7 @@ IncludeSorter::IncludeSorter(const SourceManager *SourceMgr, FileID FileID,
void IncludeSorter::addInclude(StringRef FileName, bool IsAngled,
SourceLocation HashLocation,
SourceLocation EndLocation) {
int Offset = findNextLine(SourceMgr->getCharacterData(EndLocation));
const int Offset = findNextLine(SourceMgr->getCharacterData(EndLocation));
// Record the relevant location information for this inclusion directive.
auto &IncludeLocation = IncludeLocations[FileName];
@ -139,7 +140,7 @@ void IncludeSorter::addInclude(StringRef FileName, bool IsAngled,
return;
// Add the included file's name to the appropriate bucket.
IncludeKinds Kind =
const IncludeKinds Kind =
determineIncludeKind(CanonicalFile, FileName, IsAngled, Style);
if (Kind != IK_InvalidInclude)
IncludeBucket[Kind].push_back(FileName.str());
@ -181,7 +182,8 @@ IncludeSorter::createIncludeInsertion(StringRef FileName, bool IsAngled) {
// FileName comes after all include entries in bucket, insert it after
// last.
const std::string &LastInclude = IncludeBucket[IncludeKind].back();
SourceRange LastIncludeLocation = IncludeLocations[LastInclude].back();
const SourceRange LastIncludeLocation =
IncludeLocations[LastInclude].back();
return FixItHint::CreateInsertion(LastIncludeLocation.getEnd(),
IncludeStmt);
}
@ -205,14 +207,16 @@ IncludeSorter::createIncludeInsertion(StringRef FileName, bool IsAngled) {
if (NonEmptyKind < IncludeKind) {
// Create a block after.
const std::string &LastInclude = IncludeBucket[NonEmptyKind].back();
SourceRange LastIncludeLocation = IncludeLocations[LastInclude].back();
const SourceRange LastIncludeLocation =
IncludeLocations[LastInclude].back();
IncludeStmt = '\n' + IncludeStmt;
return FixItHint::CreateInsertion(LastIncludeLocation.getEnd(),
IncludeStmt);
}
// Create a block before.
const std::string &FirstInclude = IncludeBucket[NonEmptyKind][0];
SourceRange FirstIncludeLocation = IncludeLocations[FirstInclude].back();
const SourceRange FirstIncludeLocation =
IncludeLocations[FirstInclude].back();
IncludeStmt.append("\n");
return FixItHint::CreateInsertion(FirstIncludeLocation.getBegin(),
IncludeStmt);

View File

@ -42,7 +42,7 @@ SourceLocation findPreviousTokenStart(SourceLocation Start,
if (Start.isInvalid() || Start.isMacroID())
return {};
SourceLocation BeforeStart = Start.getLocWithOffset(-1);
const SourceLocation BeforeStart = Start.getLocWithOffset(-1);
if (BeforeStart.isInvalid() || BeforeStart.isMacroID())
return {};
@ -57,7 +57,7 @@ SourceLocation findPreviousTokenKind(SourceLocation Start,
return {};
while (true) {
SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
const SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
if (L.isInvalid() || L.isMacroID())
return {};
@ -123,8 +123,9 @@ std::optional<Token> getQualifyingToken(tok::TokenKind TK,
assert((TK == tok::kw_const || TK == tok::kw_volatile ||
TK == tok::kw_restrict) &&
"TK is not a qualifier keyword");
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Range.getBegin());
StringRef File = SM.getBufferData(LocInfo.first);
const std::pair<FileID, unsigned> LocInfo =
SM.getDecomposedLoc(Range.getBegin());
const StringRef File = SM.getBufferData(LocInfo.first);
Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), Context.getLangOpts(),
File.begin(), File.data() + LocInfo.second, File.end());
std::optional<Token> LastMatchBeforeTemplate;

View File

@ -48,7 +48,7 @@ SourceLocation findPreviousAnyTokenKind(SourceLocation Start,
if (Start.isInvalid() || Start.isMacroID())
return {};
while (true) {
SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
const SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
if (L.isInvalid() || L.isMacroID())
return {};
@ -76,7 +76,7 @@ SourceLocation findNextAnyTokenKind(SourceLocation Start,
if (!CurrentToken)
return {};
Token PotentialMatch = *CurrentToken;
const Token PotentialMatch = *CurrentToken;
if (PotentialMatch.isOneOf(TK, TKs...))
return PotentialMatch.getLocation();

View File

@ -162,7 +162,7 @@ struct NotIdenticalStatementsPredicate {
// Checks if statement is identical (utils::areStatementsIdentical) to one bound
// to ID node.
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID) {
NotIdenticalStatementsPredicate Predicate{
const NotIdenticalStatementsPredicate Predicate{
ID, ::clang::DynTypedNode::create(Node), &(Finder->getASTContext())};
return Builder->removeBindings(Predicate);
}

View File

@ -55,7 +55,7 @@ NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement,
}
for (const auto &Abbreviation : Abbreviations) {
DeclarationMatcher ConflictMatcher = namedDecl(hasName(Abbreviation));
const DeclarationMatcher ConflictMatcher = namedDecl(hasName(Abbreviation));
const auto HasConflictingChildren =
!match(findAll(ConflictMatcher), *Function, Context).empty();
const auto HasConflictingAncestors =
@ -65,10 +65,10 @@ NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement,
if (HasConflictingAncestors || HasConflictingChildren)
continue;
std::string Declaration =
const std::string Declaration =
(llvm::Twine("\nnamespace ") + Abbreviation + " = " + Namespace + ";")
.str();
SourceLocation Loc =
const SourceLocation Loc =
Lexer::getLocForEndOfToken(Function->getBody()->getBeginLoc(), 0,
SourceMgr, Context.getLangOpts());
AddedAliases[Function][Namespace.str()] = Abbreviation;

View File

@ -103,7 +103,7 @@ static const CXXMethodDecl *getOverrideMethod(const CXXMethodDecl *Method) {
while (true) {
Method = *Method->begin_overridden_methods();
assert(Method && "Overridden method shouldn't be null");
unsigned NumOverrides = Method->size_overridden_methods();
const unsigned NumOverrides = Method->size_overridden_methods();
if (NumOverrides == 0)
return Method;
if (NumOverrides > 1)
@ -148,7 +148,7 @@ static NameLookup findDeclInBases(const CXXRecordDecl &Parent,
return NameLookup(InClassRef);
const NamedDecl *Found = nullptr;
for (CXXBaseSpecifier Base : Parent.bases()) {
for (const CXXBaseSpecifier Base : Parent.bases()) {
const auto *Record = Base.getType()->getAsCXXRecordDecl();
if (!Record && AggressiveTemplateLookup) {
if (const auto *TST =
@ -269,7 +269,7 @@ public:
}
bool VisitNamedDecl(NamedDecl *Decl) {
SourceRange UsageRange =
const SourceRange UsageRange =
DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
.getSourceRange();
Check->addUsage(Decl, UsageRange, SM);
@ -277,13 +277,13 @@ public:
}
bool VisitDeclRefExpr(DeclRefExpr *DeclRef) {
SourceRange Range = DeclRef->getNameInfo().getSourceRange();
const SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Check->addUsage(DeclRef->getDecl(), Range, SM);
return true;
}
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc Loc) {
if (NestedNameSpecifier Spec = Loc.getNestedNameSpecifier();
if (const NestedNameSpecifier Spec = Loc.getNestedNameSpecifier();
Spec.getKind() == NestedNameSpecifier::Kind::Namespace) {
if (const auto *Decl =
dyn_cast<NamespaceDecl>(Spec.getAsNamespaceAndPrefix().Namespace))
@ -295,27 +295,28 @@ public:
}
bool VisitMemberExpr(MemberExpr *MemberRef) {
SourceRange Range = MemberRef->getMemberNameInfo().getSourceRange();
const SourceRange Range = MemberRef->getMemberNameInfo().getSourceRange();
Check->addUsage(MemberRef->getMemberDecl(), Range, SM);
return true;
}
bool
VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *DepMemberRef) {
QualType BaseType = DepMemberRef->isArrow()
? DepMemberRef->getBaseType()->getPointeeType()
: DepMemberRef->getBaseType();
const QualType BaseType =
DepMemberRef->isArrow() ? DepMemberRef->getBaseType()->getPointeeType()
: DepMemberRef->getBaseType();
if (BaseType.isNull())
return true;
const CXXRecordDecl *Base = BaseType.getTypePtr()->getAsCXXRecordDecl();
if (!Base)
return true;
DeclarationName DeclName = DepMemberRef->getMemberNameInfo().getName();
const DeclarationName DeclName =
DepMemberRef->getMemberNameInfo().getName();
if (!DeclName.isIdentifier())
return true;
StringRef DependentName = DeclName.getAsIdentifierInfo()->getName();
const StringRef DependentName = DeclName.getAsIdentifierInfo()->getName();
if (NameLookup Resolved = findDeclInBases(
if (const NameLookup Resolved = findDeclInBases(
*Base, DependentName, AggressiveDependentMemberLookup)) {
if (*Resolved)
Check->addUsage(*Resolved,
@ -370,7 +371,7 @@ public:
const IdentifierInfo *II = FD->getIdentifier();
if (!II)
continue;
SourceRange FixLocation{D.getFieldLoc(), D.getFieldLoc()};
const SourceRange FixLocation{D.getFieldLoc(), D.getFieldLoc()};
Check->addUsage(FD, FixLocation, SM);
}
@ -473,7 +474,8 @@ void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl,
if (!MaybeFailure)
return;
NamingCheckId FailureId(FailureDecl->getLocation(), FailureDecl->getName());
const NamingCheckId FailureId(FailureDecl->getLocation(),
FailureDecl->getName());
auto [FailureIter, NewFailure] = addUsage(FailureId, UsageRange, SourceMgr);
@ -527,10 +529,10 @@ void RenamerClangTidyCheck::checkMacro(const Token &MacroNameTok,
if (!MaybeFailure)
return;
FailureInfo &Info = *MaybeFailure;
StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
NamingCheckId ID(MI->getDefinitionLoc(), Name);
const StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
const NamingCheckId ID(MI->getDefinitionLoc(), Name);
NamingCheckFailure &Failure = NamingCheckFailures[ID];
SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
const SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
if (!isValidAsciiIdentifier(Info.Fixup))
Failure.FixStatus = ShouldFixStatus::FixInvalidIdentifier;
@ -542,14 +544,14 @@ void RenamerClangTidyCheck::checkMacro(const Token &MacroNameTok,
void RenamerClangTidyCheck::expandMacro(const Token &MacroNameTok,
const MacroInfo *MI,
const SourceManager &SourceMgr) {
StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
NamingCheckId ID(MI->getDefinitionLoc(), Name);
const StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
const NamingCheckId ID(MI->getDefinitionLoc(), Name);
auto Failure = NamingCheckFailures.find(ID);
if (Failure == NamingCheckFailures.end())
return;
SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
const SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
addUsage(ID, Range, SourceMgr);
}

View File

@ -105,7 +105,7 @@ void TransformerClangTidyCheck::check(
if (Result.Context->getDiagnostics().hasErrorOccurred())
return;
size_t I = transformer::detail::findSelectedCase(Result, Rule);
const size_t I = transformer::detail::findSelectedCase(Result, Rule);
Expected<SmallVector<transformer::Edit, 1>> Edits =
Rule.Cases[I].Edits(Result);
if (!Edits) {
@ -127,7 +127,7 @@ void TransformerClangTidyCheck::check(
// Associate the diagnostic with the location of the first change.
{
DiagnosticBuilder Diag =
const DiagnosticBuilder Diag =
diag((*Edits)[0].Range.getBegin(), escapeForDiagnostic(*Explanation));
for (const auto &T : *Edits) {
switch (T.Kind) {

View File

@ -111,7 +111,7 @@ bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context) {
}
}
QualType CanonicalType = Type.getCanonicalType();
const QualType CanonicalType = Type.getCanonicalType();
if (CanonicalType->isDependentType())
return false;

View File

@ -73,7 +73,7 @@ makeMatcherPair(StringRef State, const UseRangesCheck::Indexes &Indexes,
const std::optional<UseRangesCheck::ReverseIteratorDescriptor>
&ReverseDescriptor) {
std::string ArgBound = (ArgName + llvm::Twine(Indexes.BeginArg)).str();
SmallString<64> ID = {BoundCall, State};
const SmallString<64> ID = {BoundCall, State};
ast_matchers::internal::Matcher<CallExpr> ArgumentMatcher = allOf(
hasArgument(Indexes.BeginArg,
makeExprMatcher(expr(unless(hasSideEffects())).bind(ArgBound),
@ -84,9 +84,9 @@ makeMatcherPair(StringRef State, const UseRangesCheck::Indexes &Indexes,
{"end", "cend"}, EndFreeNames)));
if (ReverseDescriptor) {
ArgBound.push_back('R');
SmallVector<StringRef> RBegin{
const SmallVector<StringRef> RBegin{
llvm::make_first_range(ReverseDescriptor->FreeReverseNames)};
SmallVector<StringRef> REnd{
const SmallVector<StringRef> REnd{
llvm::make_second_range(ReverseDescriptor->FreeReverseNames)};
ArgumentMatcher = anyOf(
ArgumentMatcher,
@ -110,9 +110,9 @@ void UseRangesCheck::registerMatchers(MatchFinder *Finder) {
auto Replaces = getReplacerMap();
ReverseDescriptor = getReverseDescriptor();
auto BeginEndNames = getFreeBeginEndMethods();
llvm::SmallVector<StringRef, 4> BeginNames{
const llvm::SmallVector<StringRef, 4> BeginNames{
llvm::make_first_range(BeginEndNames)};
llvm::SmallVector<StringRef, 4> EndNames{
const llvm::SmallVector<StringRef, 4> EndNames{
llvm::make_second_range(BeginEndNames)};
Replacers.clear();
llvm::DenseSet<Replacer *> SeenRepl;
@ -169,7 +169,7 @@ static void removeFunctionArgs(DiagnosticBuilder &Diag, const CallExpr &Call,
llvm::SmallBitVector Commas(Call.getNumArgs());
// The first comma is actually the '(' which we can't remove
Commas[0] = true;
for (unsigned Index : Sorted) {
for (const unsigned Index : Sorted) {
const Expr *Arg = Call.getArg(Index);
if (Commas[Index]) {
if (Index >= Commas.size()) {
@ -192,7 +192,7 @@ static void removeFunctionArgs(DiagnosticBuilder &Diag, const CallExpr &Call,
}
void UseRangesCheck::check(const MatchFinder::MatchResult &Result) {
Replacer *Replacer = nullptr;
const Replacer *Replacer = nullptr;
const FunctionDecl *Function = nullptr;
for (const auto &[Node, Value] : Result.Nodes.getMap()) {
StringRef NodeStr(Node);
@ -254,7 +254,7 @@ void UseRangesCheck::check(const MatchFinder::MatchResult &Result) {
Diag << Inserter.createIncludeInsertion(
Result.SourceManager->getFileID(Call->getBeginLoc()),
*ReverseDescriptor->ReverseHeader);
StringRef ArgText = Lexer::getSourceText(
const StringRef ArgText = Lexer::getSourceText(
CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
Result.Context->getSourceManager(), Result.Context->getLangOpts());
SmallString<128> ReplaceText;

View File

@ -19,7 +19,7 @@ namespace clang::tidy::utils {
using namespace ast_matchers;
static StringRef getUnqualifiedName(StringRef QualifiedName) {
size_t LastSeparatorPos = QualifiedName.rfind("::");
const size_t LastSeparatorPos = QualifiedName.rfind("::");
if (LastSeparatorPos == StringRef::npos)
return QualifiedName;
return QualifiedName.drop_front(LastSeparatorPos + 2);
@ -30,7 +30,7 @@ UsingInserter::UsingInserter(const SourceManager &SourceMgr)
std::optional<FixItHint> UsingInserter::createUsingDeclaration(
ASTContext &Context, const Stmt &Statement, StringRef QualifiedName) {
StringRef UnqualifiedName = getUnqualifiedName(QualifiedName);
const StringRef UnqualifiedName = getUnqualifiedName(QualifiedName);
const FunctionDecl *Function = getSurroundingFunction(Context, Statement);
if (!Function)
return std::nullopt;
@ -38,7 +38,7 @@ std::optional<FixItHint> UsingInserter::createUsingDeclaration(
if (AddedUsing.count(std::make_pair(Function, QualifiedName.str())) != 0)
return std::nullopt;
SourceLocation InsertLoc = Lexer::getLocForEndOfToken(
const SourceLocation InsertLoc = Lexer::getLocForEndOfToken(
Function->getBody()->getBeginLoc(), 0, SourceMgr, Context.getLangOpts());
// Only use using declarations in the main file, not in includes.
@ -47,7 +47,7 @@ std::optional<FixItHint> UsingInserter::createUsingDeclaration(
// FIXME: This declaration could be masked. Investigate if
// there is a way to avoid using Sema.
bool AlreadyHasUsingDecl =
const bool AlreadyHasUsingDecl =
!match(stmt(hasAncestor(decl(has(usingDecl(hasAnyUsingShadowDecl(
hasTargetDecl(hasName(QualifiedName.str())))))))),
Statement, Context)
@ -58,15 +58,15 @@ std::optional<FixItHint> UsingInserter::createUsingDeclaration(
}
// Find conflicting declarations and references.
auto ConflictingDecl = namedDecl(hasName(UnqualifiedName));
bool HasConflictingDeclaration =
const bool HasConflictingDeclaration =
!match(findAll(ConflictingDecl), *Function, Context).empty();
bool HasConflictingDeclRef =
const bool HasConflictingDeclRef =
!match(findAll(declRefExpr(to(ConflictingDecl))), *Function, Context)
.empty();
if (HasConflictingDeclaration || HasConflictingDeclRef)
return std::nullopt;
std::string Declaration =
const std::string Declaration =
(llvm::Twine("\nusing ") + QualifiedName + ";").str();
AddedUsing.emplace(Function, QualifiedName.str());