diff --git a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp index d5deb99a8442d..26278139c04c3 100644 --- a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp @@ -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) && diff --git a/clang-tools-extra/clang-tidy/utils/BracesAroundStatement.cpp b/clang-tools-extra/clang-tidy/utils/BracesAroundStatement.cpp index 14770c49c2e25..aacb4e33ea570 100644 --- a/clang-tools-extra/clang-tidy/utils/BracesAroundStatement.cpp +++ b/clang-tools-extra/clang-tidy/utils/BracesAroundStatement.cpp @@ -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. diff --git a/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp b/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp index a5b08836db2c8..75a6dafed3c5e 100644 --- a/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp @@ -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. diff --git a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp index 706dd67c16776..5fd1b731707e7 100644 --- a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp +++ b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp @@ -360,8 +360,9 @@ ExceptionAnalyzer::ExceptionInfo::filterByCatch(const Type *HandlerTy, llvm::SmallVector 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(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(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(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(St)) { - ExceptionInfo Excs = + const ExceptionInfo Excs = throwsException(DefaultInit->getExpr(), Caught, CallStack); Results.merge(Excs); } else if (const auto *Coro = dyn_cast(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(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); } } diff --git a/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp b/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp index b1d6b195f9470..2da09669dd7f8 100644 --- a/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp +++ b/clang-tools-extra/clang-tidy/utils/ExceptionSpecAnalyzer.cpp @@ -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; } diff --git a/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp b/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp index 46eebf4e7a86e..0375d0f6c740f 100644 --- a/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp +++ b/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp @@ -29,13 +29,13 @@ static SmallVector getParentStmts(const Stmt *S, ASTContext *Context) { SmallVector Result; - TraversalKindScope RAII(*Context, TK_AsIs); + const TraversalKindScope RAII(*Context, TK_AsIs); DynTypedNodeList Parents = Context->getParents(*S); SmallVector 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()) { @@ -95,7 +95,8 @@ bool ExprSequence::inSequence(const Stmt *Before, const Stmt *After) const { return true; } - SmallVector BeforeParents = getParentStmts(Before, Context); + const SmallVector BeforeParents = + getParentStmts(Before, Context); // Since C++17, the callee of a call expression is guaranteed to be sequenced // before all of the arguments. diff --git a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp index 41d5131599ce6..97be36a06a89d 100644 --- a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp @@ -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 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; diff --git a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp index b30c83e3aeb35..c4cdf0d63af4c 100644 --- a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp @@ -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 IgnoredParens = @@ -201,7 +201,7 @@ std::optional 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); diff --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp index f4945b2113c69..127de30cf6e42 100644 --- a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp +++ b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp @@ -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 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(); diff --git a/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp b/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp index e1d13876d64a9..d36b187b1da14 100644 --- a/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp +++ b/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp @@ -32,11 +32,11 @@ class HeaderGuardPPCallbacks : public PPCallbacks { 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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { 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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { 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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { // 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 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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { 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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { 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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { std::vector &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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { // 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 @@ class HeaderGuardPPCallbacks : public PPCallbacks { // 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 " diff --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp index 0b67cba6ffb0a..81bb8dec57a74 100644 --- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp +++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp @@ -69,7 +69,7 @@ IncludeSorter &IncludeInserter::getOrCreate(FileID FileID) { std::optional 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); } diff --git a/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp index 7e2aad9a97c8e..f113f8cabea87 100644 --- a/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp +++ b/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp @@ -17,7 +17,7 @@ namespace utils { static StringRef removeFirstSuffix(StringRef Str, ArrayRef 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 Parts = CanonicalInclude.split("/public/"); + const std::pair 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); diff --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp index 7222f64804f63..0f20fdec6c29b 100644 --- a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp @@ -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 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 LocInfo = SM.getDecomposedLoc(Range.getBegin()); - StringRef File = SM.getBufferData(LocInfo.first); + const std::pair 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 LastMatchBeforeTemplate; diff --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.h b/clang-tools-extra/clang-tidy/utils/LexerUtils.h index c74d1e02b931c..c5fb646c0efd9 100644 --- a/clang-tools-extra/clang-tidy/utils/LexerUtils.h +++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.h @@ -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(); diff --git a/clang-tools-extra/clang-tidy/utils/Matchers.h b/clang-tools-extra/clang-tidy/utils/Matchers.h index 4eac0655e3922..a444ab623a56a 100644 --- a/clang-tools-extra/clang-tidy/utils/Matchers.h +++ b/clang-tools-extra/clang-tidy/utils/Matchers.h @@ -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); } diff --git a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp index 3af7f8dcf2ee5..c862364c886dd 100644 --- a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp +++ b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp @@ -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; diff --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp index 6bd6d981858cb..bc6de97b8b74e 100644 --- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp @@ -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 @@ class RenamerClangTidyVisitor } bool VisitNamedDecl(NamedDecl *Decl) { - SourceRange UsageRange = + const SourceRange UsageRange = DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation()) .getSourceRange(); Check->addUsage(Decl, UsageRange, SM); @@ -277,13 +277,13 @@ class RenamerClangTidyVisitor } 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(Spec.getAsNamespaceAndPrefix().Namespace)) @@ -295,27 +295,28 @@ class RenamerClangTidyVisitor } 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 @@ class RenamerClangTidyVisitor 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); } diff --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp index 87602d1187d59..d7dad624f5e7e 100644 --- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp @@ -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> 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) { diff --git a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp index d4e079f1cf4c2..98a5d40d49313 100644 --- a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp +++ b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp @@ -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; diff --git a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp index cb1495163a2f9..8b7019b56a50e 100644 --- a/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp @@ -73,7 +73,7 @@ makeMatcherPair(StringRef State, const UseRangesCheck::Indexes &Indexes, const std::optional &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 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 RBegin{ + const SmallVector RBegin{ llvm::make_first_range(ReverseDescriptor->FreeReverseNames)}; - SmallVector REnd{ + const SmallVector 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 BeginNames{ + const llvm::SmallVector BeginNames{ llvm::make_first_range(BeginEndNames)}; - llvm::SmallVector EndNames{ + const llvm::SmallVector EndNames{ llvm::make_second_range(BeginEndNames)}; Replacers.clear(); llvm::DenseSet 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; diff --git a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp index e4c71aa60a7a2..6a591c1a84a47 100644 --- a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp +++ b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp @@ -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 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 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 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 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());