diff --git a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp index 0e1c389d0d80a..affcea441ada7 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp @@ -27,7 +27,7 @@ static std::optional findConstToRemove(const ParmVarDecl &Param, const MatchFinder::MatchResult &Result) { - CharSourceRange FileRange = Lexer::makeFileCharRange( + const CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(getTypeRange(Param)), *Result.SourceManager, Result.Context->getLangOpts()); diff --git a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp index 40a4fa114681e..2b31281bb4a63 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp @@ -47,9 +47,9 @@ void AvoidReturnWithVoidValueCheck::check( Result.Nodes.getNodeAs("compound_parent"); if (!StrictMode && !SurroundingBlock) return; - DiagnosticBuilder Diag = diag(VoidReturn->getBeginLoc(), - "return statement within a void function " - "should not have a specified return value"); + const DiagnosticBuilder Diag = diag( + VoidReturn->getBeginLoc(), "return statement within a void function " + "should not have a specified return value"); const SourceLocation SemicolonPos = utils::lexer::findNextTerminator( VoidReturn->getEndLoc(), *Result.SourceManager, getLangOpts()); if (SemicolonPos.isInvalid()) diff --git a/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp index c53c70667dbbc..631bb14753163 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp @@ -40,7 +40,7 @@ struct AvoidUnconditionalPreprocessorIfPPCallbacks : public PPCallbacks { bool isImmutable(SourceManager &SM, const LangOptions &LangOpts, SourceRange ConditionRange) { - SourceLocation Loc = ConditionRange.getBegin(); + const SourceLocation Loc = ConditionRange.getBegin(); if (Loc.isMacroID()) return false; diff --git a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp index 1952e14d1fc3d..2b55bb819da9c 100644 --- a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp @@ -20,7 +20,8 @@ namespace clang::tidy::readability { 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."); @@ -38,7 +39,7 @@ forwardSkipWhitespaceAndComments(SourceLocation Loc, const SourceManager &SM, while (isWhitespace(*SM.getCharacterData(Loc))) Loc = Loc.getLocWithOffset(1); - tok::TokenKind TokKind = getTokenKind(Loc, SM, LangOpts); + const tok::TokenKind TokKind = getTokenKind(Loc, SM, LangOpts); if (TokKind != tok::comment) return Loc; @@ -80,7 +81,8 @@ void BracesAroundStatementsCheck::check( } else if (const auto *S = Result.Nodes.getNodeAs("do")) { checkStmt(Result, S->getBody(), S->getDoLoc(), S->getWhileLoc()); } else if (const auto *S = Result.Nodes.getNodeAs("while")) { - SourceLocation StartLoc = findRParenLoc(S, SM, Context->getLangOpts()); + const SourceLocation StartLoc = + findRParenLoc(S, SM, Context->getLangOpts()); if (StartLoc.isInvalid()) return; checkStmt(Result, S->getBody(), StartLoc); @@ -89,12 +91,14 @@ void BracesAroundStatementsCheck::check( if (S->isConsteval()) return; - SourceLocation StartLoc = findRParenLoc(S, SM, Context->getLangOpts()); + const SourceLocation StartLoc = + findRParenLoc(S, SM, Context->getLangOpts()); if (StartLoc.isInvalid()) return; if (ForceBracesStmts.erase(S)) ForceBracesStmts.insert(S->getThen()); - bool BracedIf = checkStmt(Result, S->getThen(), StartLoc, S->getElseLoc()); + const bool BracedIf = + checkStmt(Result, S->getThen(), StartLoc, S->getElseLoc()); const Stmt *Else = S->getElse(); if (Else && BracedIf) ForceBracesStmts.insert(Else); @@ -125,7 +129,7 @@ BracesAroundStatementsCheck::findRParenLoc(const IfOrWhileStmt *S, return {}; } - SourceLocation PastCondEndLoc = + const SourceLocation PastCondEndLoc = Lexer::getLocForEndOfToken(CondEndLoc, 0, SM, LangOpts); if (PastCondEndLoc.isInvalid()) return {}; @@ -133,7 +137,7 @@ BracesAroundStatementsCheck::findRParenLoc(const IfOrWhileStmt *S, forwardSkipWhitespaceAndComments(PastCondEndLoc, SM, LangOpts); if (RParenLoc.isInvalid()) return {}; - tok::TokenKind TokKind = getTokenKind(RParenLoc, SM, LangOpts); + const tok::TokenKind TokKind = getTokenKind(RParenLoc, SM, LangOpts); if (TokKind != tok::r_paren) return {}; return RParenLoc; diff --git a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp index 6ccd933ff4c21..cfdf0e9c4a331 100644 --- a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp @@ -32,13 +32,13 @@ findConstToRemove(const FunctionDecl *Def, // written in the source (for out-of-line declarations). A FunctionDecl's // "location" is the start of its name, so, when the name is unqualified, we // use `getLocation()`. - SourceLocation NameBeginLoc = Def->getQualifier() - ? Def->getQualifierLoc().getBeginLoc() - : Def->getLocation(); + const SourceLocation NameBeginLoc = Def->getQualifier() + ? Def->getQualifierLoc().getBeginLoc() + : Def->getLocation(); // Since either of the locs can be in a macro, use `makeFileCharRange` to be // sure that we have a consistent `CharSourceRange`, located entirely in the // source file. - CharSourceRange FileRange = Lexer::makeFileCharRange( + const CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getCharRange(Def->getBeginLoc(), NameBeginLoc), *Result.SourceManager, Result.Context->getLangOpts()); @@ -118,12 +118,12 @@ void ConstReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { (Def->getBeginLoc().isMacroID() || Def->getEndLoc().isMacroID())) return; - CheckResult CR = checkDef(Def, Result); + const CheckResult CR = checkDef(Def, Result); { // Clang only supports one in-flight diagnostic at a time. So, delimit the // scope of `Diagnostic` to allow further diagnostics after the scope. We // use `getInnerLocStart` to get the start of the return type. - DiagnosticBuilder Diagnostic = + const DiagnosticBuilder Diagnostic = diag(Def->getInnerLocStart(), "return type %0 is 'const'-qualified at the top level, which may " "reduce code readability without improving const correctness") diff --git a/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp b/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp index 850ef86c85b17..a3405524553d4 100644 --- a/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp @@ -110,7 +110,7 @@ void ContainerContainsCheck::check(const MatchFinder::MatchResult &Result) { Result.Nodes.getNodeAs("negativeComparison"); assert((!PositiveComparison || !NegativeComparison) && "only one of PositiveComparison or NegativeComparison should be set"); - bool Negated = NegativeComparison != nullptr; + const bool Negated = NegativeComparison != nullptr; const auto *Comparison = Negated ? NegativeComparison : PositiveComparison; const StringRef ContainsFunName = Result.Nodes.getNodeAs("contains_fun")->getName(); @@ -121,7 +121,7 @@ void ContainerContainsCheck::check(const MatchFinder::MatchResult &Result) { << ContainsFunName; // Don't fix it if it's in a macro invocation. Leave fixing it to the user. - SourceLocation FuncCallLoc = Comparison->getEndLoc(); + const SourceLocation FuncCallLoc = Comparison->getEndLoc(); if (!FuncCallLoc.isValid() || FuncCallLoc.isMacroID()) return; diff --git a/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp b/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp index 11756d10a8221..a5a6e3ce7af01 100644 --- a/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp @@ -101,7 +101,7 @@ void ContainerDataPointerCheck::check(const MatchFinder::MatchResult &Result) { else if (ACE) CE = ACE; - SourceRange SrcRange = CE->getSourceRange(); + const SourceRange SrcRange = CE->getSourceRange(); std::string ReplacementText{ Lexer::getSourceText(CharSourceRange::getTokenRange(SrcRange), @@ -116,7 +116,7 @@ void ContainerDataPointerCheck::check(const MatchFinder::MatchResult &Result) { else ReplacementText += ".data()"; - FixItHint Hint = + const FixItHint Hint = FixItHint::CreateReplacement(UO->getSourceRange(), ReplacementText); diag(UO->getBeginLoc(), "'data' should be used for accessing the data pointer instead of taking " diff --git a/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp b/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp index 1383e3b0b77f6..e6276e317b3ff 100644 --- a/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp @@ -119,16 +119,16 @@ static SourceRange getLocationOfConst(const TypeSourceInfo *TSI, const auto FTL = TSI->getTypeLoc().IgnoreParens().getAs(); assert(FTL); - SourceRange Range{FTL.getRParenLoc().getLocWithOffset(1), - FTL.getLocalRangeEnd()}; + const SourceRange Range{FTL.getRParenLoc().getLocWithOffset(1), + FTL.getLocalRangeEnd()}; // Inside Range, there might be other keywords and trailing return types. // Find the exact position of "const". - StringRef Text = getStringFromRange(SourceMgr, LangOpts, Range); - size_t Offset = Text.find("const"); + const StringRef Text = getStringFromRange(SourceMgr, LangOpts, Range); + const size_t Offset = Text.find("const"); if (Offset == StringRef::npos) return {}; - SourceLocation Start = Range.getBegin().getLocWithOffset(Offset); + const SourceLocation Start = Range.getBegin().getLocWithOffset(Offset); return {Start, Start.getLocWithOffset(strlen("const") - 1)}; } @@ -138,7 +138,7 @@ void ConvertMemberFunctionsToStaticCheck::check( // TODO: For out-of-line declarations, don't modify the source if the header // is excluded by the -header-filter option. - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag(Definition->getLocation(), "method %0 can be made static") << Definition; @@ -153,15 +153,15 @@ void ConvertMemberFunctionsToStaticCheck::check( if (Definition->isConst()) { // Make sure that we either remove 'const' on both declaration and // definition or emit no fix-it at all. - SourceRange DefConst = getLocationOfConst(Definition->getTypeSourceInfo(), - *Result.SourceManager, - Result.Context->getLangOpts()); + const SourceRange DefConst = getLocationOfConst( + Definition->getTypeSourceInfo(), *Result.SourceManager, + Result.Context->getLangOpts()); if (DefConst.isInvalid()) return; if (Declaration != Definition) { - SourceRange DeclConst = getLocationOfConst( + const SourceRange DeclConst = getLocationOfConst( Declaration->getTypeSourceInfo(), *Result.SourceManager, Result.Context->getLangOpts()); diff --git a/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp b/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp index 0237c057afed5..cc9ae471a926d 100644 --- a/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp @@ -88,9 +88,9 @@ void DuplicateIncludeCallbacks::InclusionDirective( if (llvm::is_contained(Files.back(), FileName)) { // We want to delete the entire line, so make sure that [Start,End] covers // everything. - SourceLocation Start = + const SourceLocation Start = advanceBeyondCurrentLine(SM, HashLoc, -1).getLocWithOffset(-1); - SourceLocation End = + const SourceLocation End = advanceBeyondCurrentLine(SM, FilenameRange.getEnd(), 1); Check.diag(HashLoc, "duplicate include") << FixItHint::CreateRemoval(SourceRange{Start, End}); diff --git a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp index 6399e7d99a9c7..a420c5653cfe8 100644 --- a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp @@ -124,21 +124,21 @@ static void removeElseAndBrackets(DiagnosticBuilder &Diag, ASTContext &Context, if (const auto *CS = dyn_cast(Else)) { Diag << tooling::fixit::createRemoval(ElseLoc); - SourceLocation LBrace = CS->getLBracLoc(); - SourceLocation RBrace = CS->getRBracLoc(); - SourceLocation RangeStart = + const SourceLocation LBrace = CS->getLBracLoc(); + const SourceLocation RBrace = CS->getRBracLoc(); + const SourceLocation RangeStart = Remap(LBrace).getLocWithOffset(TokLen(LBrace) + 1); - SourceLocation RangeEnd = Remap(RBrace).getLocWithOffset(-1); + const SourceLocation RangeEnd = Remap(RBrace).getLocWithOffset(-1); - llvm::StringRef Repl = Lexer::getSourceText( + const llvm::StringRef Repl = Lexer::getSourceText( CharSourceRange::getTokenRange(RangeStart, RangeEnd), Context.getSourceManager(), Context.getLangOpts()); Diag << tooling::fixit::createReplacement(CS->getSourceRange(), Repl); } else { - SourceLocation ElseExpandedLoc = Remap(ElseLoc); - SourceLocation EndLoc = Remap(Else->getEndLoc()); + const SourceLocation ElseExpandedLoc = Remap(ElseLoc); + const SourceLocation EndLoc = Remap(Else->getEndLoc()); - llvm::StringRef Repl = Lexer::getSourceText( + const llvm::StringRef Repl = Lexer::getSourceText( CharSourceRange::getTokenRange( ElseExpandedLoc.getLocWithOffset(TokLen(ElseLoc) + 1), EndLoc), Context.getSourceManager(), Context.getLangOpts()); @@ -186,8 +186,8 @@ static bool hasPreprocessorBranchEndBetweenLocations( const ElseAfterReturnCheck::ConditionalBranchMap &ConditionalBranchMap, const SourceManager &SM, SourceLocation StartLoc, SourceLocation EndLoc) { - SourceLocation ExpandedStartLoc = SM.getExpansionLoc(StartLoc); - SourceLocation ExpandedEndLoc = SM.getExpansionLoc(EndLoc); + const SourceLocation ExpandedStartLoc = SM.getExpansionLoc(StartLoc); + const SourceLocation ExpandedEndLoc = SM.getExpansionLoc(EndLoc); if (!SM.isWrittenInSameFile(ExpandedStartLoc, ExpandedEndLoc)) return false; @@ -239,14 +239,14 @@ void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) { const auto *Else = Result.Nodes.getNodeAs("else"); const auto *OuterScope = Result.Nodes.getNodeAs("cs"); const auto *Interrupt = Result.Nodes.getNodeAs(InterruptingStr); - SourceLocation ElseLoc = If->getElseLoc(); + const SourceLocation ElseLoc = If->getElseLoc(); if (hasPreprocessorBranchEndBetweenLocations( PPConditionals, *Result.SourceManager, Interrupt->getBeginLoc(), ElseLoc)) return; - bool IsLastInScope = OuterScope->body_back() == If; + const bool IsLastInScope = OuterScope->body_back() == If; const StringRef ControlFlowInterrupter = getControlFlowString(*Interrupt); if (!IsLastInScope && containsDeclInScope(Else)) { @@ -276,7 +276,7 @@ void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) { } const DeclStmt *VDeclStmt = If->getConditionVariableDeclStmt(); const VarDecl *VDecl = If->getConditionVariable(); - std::string Repl = + const std::string Repl = (tooling::fixit::getText(*VDeclStmt, *Result.Context) + llvm::StringRef(";\n") + tooling::fixit::getText(If->getIfLoc(), *Result.Context)) diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp index a2a5c3e10ee07..049ad759b834c 100644 --- a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp @@ -75,7 +75,7 @@ static void cleanInitialValue(DiagnosticBuilder &Diag, namespace { AST_MATCHER(EnumDecl, isMacro) { - SourceLocation Loc = Node.getBeginLoc(); + const SourceLocation Loc = Node.getBeginLoc(); return Loc.isMacroID(); } @@ -165,7 +165,7 @@ void EnumInitialValueCheck::registerMatchers(MatchFinder *Finder) { void EnumInitialValueCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *Enum = Result.Nodes.getNodeAs("inconsistent")) { - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag( Enum->getBeginLoc(), "initial values in enum '%0' are not consistent, consider explicit " diff --git a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp index 4791df037d77d..ccac645892948 100644 --- a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp @@ -229,14 +229,14 @@ class FunctionASTVisitor final bool traverseStmtWithIncreasedNestingLevel(Stmt *Node) { ++CurrentNestingLevel; - bool ShouldContinue = Base::TraverseStmt(Node); + const bool ShouldContinue = Base::TraverseStmt(Node); --CurrentNestingLevel; return ShouldContinue; } bool traverseDeclWithIncreasedNestingLevel(Decl *Node) { ++CurrentNestingLevel; - bool ShouldContinue = Base::TraverseDecl(Node); + const bool ShouldContinue = Base::TraverseDecl(Node); --CurrentNestingLevel; return ShouldContinue; } @@ -336,7 +336,7 @@ class FunctionASTVisitor final // Record the operator that we are currently processing and traverse it. CurrentBinaryOperator = Op->getOpcode(); - bool ShouldContinue = Base::TraverseBinaryOperator(Op); + const bool ShouldContinue = Base::TraverseBinaryOperator(Op); // And restore the previous binary operator, which might be nonexistent. CurrentBinaryOperator = BinOpCopy; @@ -354,7 +354,7 @@ class FunctionASTVisitor final // Else, do add [uninitialized] frame to the stack, and traverse call. BinaryOperatorsStack.emplace(); - bool ShouldContinue = Base::TraverseCallExpr(Node); + const bool ShouldContinue = Base::TraverseCallExpr(Node); // And remove the top frame. BinaryOperatorsStack.pop(); diff --git a/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp b/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp index 8c58346ede3fa..2f0949c231844 100644 --- a/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp @@ -181,14 +181,14 @@ void FunctionSizeCheck::check(const MatchFinder::MatchResult &Result) { // Count the lines including whitespace and comments. Really simple. if (const Stmt *Body = Func->getBody()) { - SourceManager *SM = Result.SourceManager; + const SourceManager *SM = Result.SourceManager; if (SM->isWrittenInSameFile(Body->getBeginLoc(), Body->getEndLoc())) { FI.Lines = SM->getSpellingLineNumber(Body->getEndLoc()) - SM->getSpellingLineNumber(Body->getBeginLoc()); } } - unsigned ActualNumberParameters = Func->getNumParams(); + const unsigned ActualNumberParameters = Func->getNumParams(); if ((LineThreshold && FI.Lines > LineThreshold) || (StatementThreshold && FI.Statements > StatementThreshold) || diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp b/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp index 877f0a45f9ea7..a6204de16224d 100644 --- a/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp @@ -91,7 +91,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!StandaloneVar->getIdentifier()) return; - StringRef VarName = StandaloneVar->getName(); + const StringRef VarName = StandaloneVar->getName(); if (VarName.size() >= MinimumVariableNameLength || IgnoredVariableNames.match(VarName)) @@ -106,7 +106,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!ExceptionVarName->getIdentifier()) return; - StringRef VarName = ExceptionVarName->getName(); + const StringRef VarName = ExceptionVarName->getName(); if (VarName.size() >= MinimumExceptionNameLength || IgnoredExceptionVariableNames.match(VarName)) return; @@ -120,7 +120,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!LoopVar->getIdentifier()) return; - StringRef VarName = LoopVar->getName(); + const StringRef VarName = LoopVar->getName(); if (VarName.size() >= MinimumLoopCounterNameLength || IgnoredLoopCounterNames.match(VarName)) @@ -135,7 +135,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!ParamVar->getIdentifier()) return; - StringRef VarName = ParamVar->getName(); + const StringRef VarName = ParamVar->getName(); if (VarName.size() >= MinimumParameterNameLength || IgnoredParameterNames.match(VarName)) diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp index ef3eac80301d3..890ce4074345d 100644 --- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp @@ -261,7 +261,7 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions( Styles.resize(SK_Count); SmallString<64> StyleString; for (unsigned I = 0; I < SK_Count; ++I) { - size_t StyleSize = StyleNames[I].size(); + const size_t StyleSize = StyleNames[I].size(); StyleString.assign({StyleNames[I], "HungarianPrefix"}); auto HPTOpt = @@ -271,13 +271,13 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions( memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13); StyleString.truncate(StyleSize + 13); - std::optional IgnoredRegexpStr = Options.get(StyleString); + const std::optional IgnoredRegexpStr = Options.get(StyleString); memcpy(&StyleString[StyleSize], "Prefix", 6); StyleString.truncate(StyleSize + 6); - std::optional Prefix(Options.get(StyleString)); + const std::optional Prefix(Options.get(StyleString)); // Fast replacement of [Pre]fix -> [Suf]fix. memcpy(&StyleString[StyleSize], "Suf", 3); - std::optional Postfix(Options.get(StyleString)); + const std::optional Postfix(Options.get(StyleString)); memcpy(&StyleString[StyleSize], "Case", 4); StyleString.pop_back_n(2); std::optional CaseOptional = @@ -288,8 +288,9 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions( Postfix.value_or(""), IgnoredRegexpStr.value_or(""), HPTOpt.value_or(IdentifierNamingCheck::HPT_Off)); } - bool IgnoreMainLike = Options.get("IgnoreMainLikeFunctions", false); - bool CheckAnonFieldInParent = Options.get("CheckAnonFieldInParent", false); + const bool IgnoreMainLike = Options.get("IgnoreMainLikeFunctions", false); + const bool CheckAnonFieldInParent = + Options.get("CheckAnonFieldInParent", false); return {std::move(Styles), std::move(HNOption), IgnoreMainLike, CheckAnonFieldInParent}; } @@ -340,7 +341,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName( "virtual"}; // Remove keywords - for (StringRef Kw : Keywords) { + for (const StringRef Kw : Keywords) { for (size_t Pos = 0; (Pos = Type.find(Kw, Pos)) != std::string::npos;) { Type.replace(Pos, Kw.size(), ""); } @@ -376,7 +377,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName( " int", " char", " double", " long", " short"}; bool RedundantRemoved = false; for (auto Kw : TailsOfMultiWordType) { - size_t Pos = Type.rfind(Kw); + const size_t Pos = Type.rfind(Kw); if (Pos != std::string::npos) { const size_t PtrCount = getAsteriskCount(Type, ND); Type = Type.substr(0, Pos + Kw.size() + PtrCount); @@ -387,14 +388,14 @@ std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName( TypeName = Type.erase(0, Type.find_first_not_of(' ')); if (!RedundantRemoved) { - std::size_t FoundSpace = Type.find(' '); + const std::size_t FoundSpace = Type.find(' '); if (FoundSpace != std::string::npos) Type = Type.substr(0, FoundSpace); } TypeName = Type.erase(0, Type.find_first_not_of(' ')); - QualType QT = VD->getType(); + const QualType QT = VD->getType(); if (!QT.isNull() && QT->isArrayType()) TypeName.append("[]"); } @@ -451,14 +452,14 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( static constexpr StringRef HNDerivedTypes[] = {"Array", "Pointer", "FunctionPointer"}; - StringRef Section = "HungarianNotation."; + const StringRef Section = "HungarianNotation."; SmallString<128> Buffer = {Section, "General."}; size_t DefSize = Buffer.size(); for (const auto &Opt : HNOpts) { Buffer.truncate(DefSize); Buffer.append(Opt); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.General[Opt] = Val.str(); } @@ -468,7 +469,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &Type : HNDerivedTypes) { Buffer.truncate(DefSize); Buffer.append(Type); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.DerivedType[Type] = Val.str(); } @@ -484,7 +485,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &CStr : HNCStrings) { Buffer.truncate(DefSize); Buffer.append(CStr.first); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.CString[CStr.second] = Val.str(); } @@ -494,7 +495,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &PrimType : HungarianNotationPrimitiveTypes) { Buffer.truncate(DefSize); Buffer.append(PrimType); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) { std::string Type = PrimType.str(); llvm::replace(Type, '-', ' '); @@ -507,7 +508,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &Type : HungarianNotationUserDefinedTypes) { Buffer.truncate(DefSize); Buffer.append(Type); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.UserDefinedType[Type] = Val.str(); } @@ -528,7 +529,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getPrefix( } else if (const auto *CRD = dyn_cast(ND)) { Prefix = getClassPrefix(CRD, HNOption); } else if (isa(ND)) { - std::string TypeName = getDeclTypeName(ND); + const std::string TypeName = getDeclTypeName(ND); if (!TypeName.empty()) Prefix = getDataTypePrefix(TypeName, ND, HNOption); } @@ -542,8 +543,8 @@ bool IdentifierNamingCheck::HungarianNotation::removeDuplicatedPrefix( if (Words.size() <= 1) return true; - std::string CorrectName = Words[0].str(); - std::vector> MapList = { + const std::string CorrectName = Words[0].str(); + const std::vector> MapList = { HNOption.CString, HNOption.DerivedType, HNOption.PrimitiveType, HNOption.UserDefinedType}; @@ -570,12 +571,12 @@ std::string IdentifierNamingCheck::HungarianNotation::getDataTypePrefix( // Derived types std::string PrefixStr; if (const auto *TD = dyn_cast(ND)) { - QualType QT = TD->getType(); + const QualType QT = TD->getType(); if (QT->isFunctionPointerType()) { PrefixStr = HNOption.DerivedType.lookup("FunctionPointer"); } else if (QT->isPointerType()) { for (const auto &CStr : HNOption.CString) { - std::string Key = CStr.getKey().str(); + const std::string Key = CStr.getKey().str(); if (ModifiedTypeName.find(Key) == 0) { PrefixStr = CStr.getValue(); ModifiedTypeName = ModifiedTypeName.substr( @@ -585,7 +586,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getDataTypePrefix( } } else if (QT->isArrayType()) { for (const auto &CStr : HNOption.CString) { - std::string Key = CStr.getKey().str(); + const std::string Key = CStr.getKey().str(); if (ModifiedTypeName.find(Key) == 0) { PrefixStr = CStr.getValue(); break; @@ -594,14 +595,14 @@ std::string IdentifierNamingCheck::HungarianNotation::getDataTypePrefix( if (PrefixStr.empty()) PrefixStr = HNOption.DerivedType.lookup("Array"); } else if (QT->isReferenceType()) { - size_t Pos = ModifiedTypeName.find_last_of('&'); + const size_t Pos = ModifiedTypeName.find_last_of('&'); if (Pos != std::string::npos) ModifiedTypeName = ModifiedTypeName.substr(0, Pos); } } // Pointers - size_t PtrCount = getAsteriskCount(ModifiedTypeName); + const size_t PtrCount = getAsteriskCount(ModifiedTypeName); if (PtrCount > 0) { ModifiedTypeName = [&](std::string Str, StringRef From, StringRef To) { size_t StartPos = 0; @@ -663,10 +664,10 @@ std::string IdentifierNamingCheck::HungarianNotation::getEnumPrefix( Name = Name.erase(0, Name.find_first_not_of(' ')); } - static llvm::Regex Splitter( + static const llvm::Regex Splitter( "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)"); - StringRef EnumName(Name); + const StringRef EnumName(Name); SmallVector Substrs; EnumName.split(Substrs, "_", -1, false); @@ -692,7 +693,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getEnumPrefix( } std::string Initial; - for (StringRef Word : Words) + for (const StringRef Word : Words) Initial += tolower(Word[0]); return Initial; @@ -713,7 +714,7 @@ size_t IdentifierNamingCheck::HungarianNotation::getAsteriskCount( const std::string &TypeName, const NamedDecl *ND) const { size_t PtrCount = 0; if (const auto *TD = dyn_cast(ND)) { - QualType QT = TD->getType(); + const QualType QT = TD->getType(); if (QT->isPointerType()) PtrCount = getAsteriskCount(TypeName); } @@ -834,11 +835,12 @@ void IdentifierNamingCheck::HungarianNotation::loadDefaultConfig( void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { RenamerClangTidyCheck::storeOptions(Opts); SmallString<64> StyleString; - ArrayRef> Styles = MainFileStyle->getStyles(); + const ArrayRef> Styles = + MainFileStyle->getStyles(); for (size_t I = 0; I < SK_Count; ++I) { if (!Styles[I]) continue; - size_t StyleSize = StyleNames[I].size(); + const size_t StyleSize = StyleNames[I].size(); StyleString.assign({StyleNames[I], "HungarianPrefix"}); Options.store(Opts, StyleString, Styles[I]->HPType); @@ -871,7 +873,7 @@ bool IdentifierNamingCheck::matchesStyle( const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, const NamedDecl *Decl) const { - static llvm::Regex Matchers[] = { + static const llvm::Regex Matchers[] = { llvm::Regex("^.*$"), llvm::Regex("^[a-z][a-z0-9_]*$"), llvm::Regex("^[a-z][a-zA-Z0-9]*$"), @@ -887,7 +889,7 @@ bool IdentifierNamingCheck::matchesStyle( if (!Name.consume_back(Style.Suffix)) return false; if (IdentifierNamingCheck::HungarianPrefixType::HPT_Off != Style.HPType) { - std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption); + const std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption); if (!HNPrefix.empty()) { if (!Name.consume_front(HNPrefix)) return false; @@ -914,7 +916,7 @@ std::string IdentifierNamingCheck::fixupWithCase( const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, IdentifierNamingCheck::CaseType Case) const { - static llvm::Regex Splitter( + static const llvm::Regex Splitter( "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)"); SmallVector Substrs; @@ -1070,7 +1072,7 @@ bool IdentifierNamingCheck::isParamInMainLikeFunction( return false; if (!IsIntType(FDecl->parameters()[0]->getType())) return false; - MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType()); + const MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType()); if (Type == None) return false; if (FDecl->getNumParams() == 3 && @@ -1078,13 +1080,14 @@ bool IdentifierNamingCheck::isParamInMainLikeFunction( return false; if (Type == Main) { - static llvm::Regex Matcher( + static const llvm::Regex Matcher( "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))"); assert(Matcher.isValid() && "Invalid Matcher for main like functions."); return Matcher.match(FDecl->getName()); } - static llvm::Regex Matcher("(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]" - "ain([_A-Z]|$))|(_wmain(_|$))"); + static const llvm::Regex Matcher( + "(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]" + "ain([_A-Z]|$))|(_wmain(_|$))"); assert(Matcher.isValid() && "Invalid Matcher for wmain like functions."); return Matcher.match(FDecl->getName()); } @@ -1212,7 +1215,7 @@ StyleKind IdentifierNamingCheck::findStyleKind( if (const auto *Decl = dyn_cast(D)) { if (isParamInMainLikeFunction(*Decl, IgnoreMainLikeFunctions)) return SK_Invalid; - QualType Type = Decl->getType(); + const QualType Type = Decl->getType(); if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable]) return SK_ConstexprVariable; @@ -1381,7 +1384,7 @@ IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl, if (Decl->isImplicit()) return std::nullopt; - SourceLocation Loc = Decl->getLocation(); + const SourceLocation Loc = Decl->getLocation(); const FileStyle &FileStyle = getStyleForFile(SM.getFilename(Loc)); if (!FileStyle.isActive()) return std::nullopt; @@ -1398,7 +1401,7 @@ IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl, std::optional IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &SM) const { - SourceLocation Loc = MacroNameTok.getLocation(); + const SourceLocation Loc = MacroNameTok.getLocation(); const FileStyle &Style = getStyleForFile(SM.getFilename(Loc)); if (!Style.isActive()) return std::nullopt; @@ -1431,13 +1434,13 @@ IdentifierNamingCheck::getStyleForFile(StringRef FileName) const { if (!GetConfigPerFile) return *MainFileStyle; - StringRef RealFileName = getRealFileName(FileName); - StringRef Parent = llvm::sys::path::parent_path(RealFileName); + const StringRef RealFileName = getRealFileName(FileName); + const StringRef Parent = llvm::sys::path::parent_path(RealFileName); auto Iter = NamingStylesCache.find(Parent); if (Iter != NamingStylesCache.end()) return Iter->getValue(); - llvm::StringRef CheckName = getID(); + const llvm::StringRef CheckName = getID(); ClangTidyOptions Options = Context->getOptionsForFile(RealFileName); if (Options.Checks && GlobList(*Options.Checks).contains(CheckName)) { auto It = NamingStylesCache.try_emplace( @@ -1459,7 +1462,7 @@ StyleKind IdentifierNamingCheck::findStyleKindForAnonField( utils::findOutermostIndirectFieldDeclForField(AnonField); assert(IFD && "Found an anonymous record field without an IndirectFieldDecl"); - QualType Type = AnonField->getType(); + const QualType Type = AnonField->getType(); if (const auto *F = dyn_cast(IFD->chain().front())) { return findStyleKindForField(F, Type, NamingStyles); diff --git a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp index 4cf8574e56c5e..77150fd3ac9b4 100644 --- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp @@ -22,8 +22,8 @@ namespace clang::tidy::readability { namespace { AST_MATCHER(Stmt, isMacroExpansion) { - SourceManager &SM = Finder->getASTContext().getSourceManager(); - SourceLocation Loc = Node.getBeginLoc(); + const SourceManager &SM = Finder->getASTContext().getSourceManager(); + const SourceLocation Loc = Node.getBeginLoc(); return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc); } @@ -32,9 +32,9 @@ AST_MATCHER(Stmt, isC23) { return Finder->getASTContext().getLangOpts().C23; } // Preserve same name as AST_MATCHER(isNULLMacroExpansion) // NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) { - SourceManager &SM = Context.getSourceManager(); + const SourceManager &SM = Context.getSourceManager(); const LangOptions &LO = Context.getLangOpts(); - SourceLocation Loc = Statement->getBeginLoc(); + const SourceLocation Loc = Statement->getBeginLoc(); return SM.isMacroBodyExpansion(Loc) && Lexer::getImmediateMacroName(Loc, SM, LO) == "NULL"; } @@ -77,11 +77,11 @@ static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, bool UseUpperCaseLiteralSuffix) { // In case of expressions like (! integer), we should remove the redundant not // operator and use inverted comparison (integer == 0). - bool InvertComparison = + const bool InvertComparison = Parent != nullptr && isUnaryLogicalNotOperator(Parent); if (InvertComparison) { - SourceLocation ParentStartLoc = Parent->getBeginLoc(); - SourceLocation ParentEndLoc = + const SourceLocation ParentStartLoc = Parent->getBeginLoc(); + const SourceLocation ParentEndLoc = cast(Parent)->getSubExpr()->getBeginLoc(); Diag << FixItHint::CreateRemoval( CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc)); @@ -91,9 +91,9 @@ static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, const Expr *SubExpr = Cast->getSubExpr(); - bool NeedInnerParens = + const bool NeedInnerParens = utils::fixit::areParensNeededForStatement(*SubExpr->IgnoreImpCasts()); - bool NeedOuterParens = + const bool NeedOuterParens = Parent != nullptr && utils::fixit::areParensNeededForStatement(*Parent); std::string StartLocInsertion; @@ -133,7 +133,7 @@ static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, EndLocInsertion += ")"; } - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts()); Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion); } @@ -167,8 +167,8 @@ static StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression, } static bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) { - SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc); - StringRef SpaceBeforeStmtStr = Lexer::getSourceText( + const SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc); + const StringRef SpaceBeforeStmtStr = Lexer::getSourceText( CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(), Context.getLangOpts(), nullptr); if (SpaceBeforeStmtStr.empty()) @@ -198,7 +198,7 @@ static void fixGenericExprCastFromBool(DiagnosticBuilder &Diag, .str()); if (NeedParens) { - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts()); @@ -234,7 +234,7 @@ static bool isCastAllowedInCondition(const ImplicitCastExpr *Cast, std::queue Q; Q.push(Cast); - TraversalKindScope RAII(Context, TK_AsIs); + const TraversalKindScope RAII(Context, TK_AsIs); while (!Q.empty()) { for (const auto &N : Context.getParents(*Q.front())) { @@ -396,7 +396,7 @@ void ImplicitBoolConversionCheck::handleCastToBool(const ImplicitCastExpr *Cast, auto Diag = diag(Cast->getBeginLoc(), "implicit conversion %0 -> 'bool'") << Cast->getSubExpr()->getType(); - StringRef EquivalentLiteral = + const StringRef EquivalentLiteral = getEquivalentBoolLiteralForExpr(Cast->getSubExpr(), Context); if (!EquivalentLiteral.empty()) { Diag << tooling::fixit::createReplacement(*Cast, EquivalentLiteral); @@ -409,7 +409,7 @@ void ImplicitBoolConversionCheck::handleCastToBool(const ImplicitCastExpr *Cast, void ImplicitBoolConversionCheck::handleCastFromBool( const ImplicitCastExpr *Cast, const ImplicitCastExpr *NextImplicitCast, ASTContext &Context) { - QualType DestType = + const QualType DestType = NextImplicitCast ? NextImplicitCast->getType() : Cast->getType(); auto Diag = diag(Cast->getBeginLoc(), "implicit conversion 'bool' -> %0") << DestType; diff --git a/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp b/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp index 93580a7e67c4a..c49684112a5d4 100644 --- a/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp @@ -113,12 +113,12 @@ findDifferingParamsInDeclaration(const FunctionDecl *ParameterSourceDeclaration, // FIXME: Provide a way to extract commented out parameter name from comment // next to it. if (!nameMatch(SourceParamName, OtherParamName, Strict)) { - SourceRange OtherParamNameRange = + const SourceRange OtherParamNameRange = DeclarationNameInfo((*OtherParamIt)->getDeclName(), (*OtherParamIt)->getLocation()) .getSourceRange(); - bool GenerateFixItHint = checkIfFixItHintIsApplicable( + const bool GenerateFixItHint = checkIfFixItHintIsApplicable( ParameterSourceDeclaration, *SourceParamIt, OriginalDeclaration); DifferingParams.emplace_back(SourceParamName, OtherParamName, @@ -137,11 +137,11 @@ findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration, const FunctionDecl *ParameterSourceDeclaration, SourceManager &SM, bool Strict) { InconsistentDeclarationsContainer InconsistentDeclarations; - SourceLocation ParameterSourceLocation = + const SourceLocation ParameterSourceLocation = ParameterSourceDeclaration->getLocation(); for (const FunctionDecl *OtherDeclaration : OriginalDeclaration->redecls()) { - SourceLocation OtherLocation = OtherDeclaration->getLocation(); + const SourceLocation OtherLocation = OtherDeclaration->getLocation(); if (OtherLocation != ParameterSourceLocation) { // Skip self. DifferingParamsContainer DifferingParams = findDifferingParamsInDeclaration(ParameterSourceDeclaration, @@ -305,7 +305,7 @@ void InconsistentDeclarationParameterNameCheck::check( const FunctionDecl *ParameterSourceDeclaration = getParameterSourceDeclaration(OriginalDeclaration); - InconsistentDeclarationsContainer InconsistentDeclarations = + const InconsistentDeclarationsContainer InconsistentDeclarations = findInconsistentDeclarations(OriginalDeclaration, ParameterSourceDeclaration, *Result.SourceManager, Strict); @@ -315,7 +315,7 @@ void InconsistentDeclarationParameterNameCheck::check( return; } - SourceLocation StartLoc = OriginalDeclaration->getBeginLoc(); + const SourceLocation StartLoc = OriginalDeclaration->getBeginLoc(); if (StartLoc.isMacroID() && IgnoreMacros) { markRedeclarationsAsVisited(OriginalDeclaration); return; diff --git a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp index bc5edecb8a65b..fa5a0b7cd3647 100644 --- a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp @@ -107,7 +107,7 @@ static bool typeIsMemberPointer(const Type *T) { static std::optional> declRanges(const DeclStmt *DS, const SourceManager &SM, const LangOptions &LangOpts) { - std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end()); + const std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end()); if (DeclCount < 2) return std::nullopt; @@ -157,7 +157,7 @@ declRanges(const DeclStmt *DS, const SourceManager &SM, if (Start.isInvalid() || Start.isMacroID()) break; - Token T = getPreviousToken(Start, SM, LangOpts); + const Token T = getPreviousToken(Start, SM, LangOpts); if (T.is(tok::l_paren)) { Start = findPreviousTokenStart(Start, SM, LangOpts); continue; @@ -165,7 +165,7 @@ declRanges(const DeclStmt *DS, const SourceManager &SM, break; } - SourceRange DeclRange(DS->getBeginLoc(), Start); + const SourceRange DeclRange(DS->getBeginLoc(), Start); if (DeclRange.isInvalid() || isMacroID(DeclRange)) return std::nullopt; @@ -183,13 +183,13 @@ declRanges(const DeclStmt *DS, const SourceManager &SM, if (typeIsMemberPointer(CurrentDecl->getType().IgnoreParens().getTypePtr())) return std::nullopt; - SourceLocation DeclEnd = + const SourceLocation DeclEnd = CurrentDecl->hasInit() ? findNextTerminator(CurrentDecl->getInit()->getEndLoc(), SM, LangOpts) : findNextTerminator(CurrentDecl->getEndLoc(), SM, LangOpts); - SourceRange VarNameRange(DeclBegin, DeclEnd); + const SourceRange VarNameRange(DeclBegin, DeclEnd); if (VarNameRange.isInvalid() || isMacroID(VarNameRange)) return std::nullopt; @@ -206,7 +206,7 @@ collectSourceRanges(llvm::ArrayRef Ranges, const SourceManager &SM, Snippets.reserve(Ranges.size()); for (const auto &Range : Ranges) { - CharSourceRange CharRange = Lexer::getAsCharRange( + const CharSourceRange CharRange = Lexer::getAsCharRange( CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()), SM, LangOpts); @@ -214,7 +214,7 @@ collectSourceRanges(llvm::ArrayRef Ranges, const SourceManager &SM, return std::nullopt; bool InvalidText = false; - StringRef Snippet = + const StringRef Snippet = Lexer::getSourceText(CharRange, SM, LangOpts, &InvalidText); if (InvalidText) @@ -262,7 +262,7 @@ void IsolateDeclarationCheck::check(const MatchFinder::MatchResult &Result) { return; std::vector NewDecls = createIsolatedDecls(*PotentialSnippets); - std::string Replacement = llvm::join( + const std::string Replacement = llvm::join( NewDecls, (Twine("\n") + Lexer::getIndentationForLine(WholeDecl->getBeginLoc(), *Result.SourceManager)) diff --git a/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp b/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp index a38f7bc029e8b..01abf513ce9b9 100644 --- a/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp @@ -145,7 +145,7 @@ void MagicNumbersCheck::registerMatchers(MatchFinder *Finder) { void MagicNumbersCheck::check(const MatchFinder::MatchResult &Result) { - TraversalKindScope RAII(*Result.Context, TK_AsIs); + const TraversalKindScope RAII(*Result.Context, TK_AsIs); checkBoundMatch(Result, "integer"); checkBoundMatch(Result, "float"); @@ -248,7 +248,7 @@ bool MagicNumbersCheck::isBitFieldWidth( bool MagicNumbersCheck::isUserDefinedLiteral( const clang::ast_matchers::MatchFinder::MatchResult &Result, const clang::Expr &Literal) const { - DynTypedNodeList Parents = Result.Context->getParents(Literal); + const DynTypedNodeList Parents = Result.Context->getParents(Literal); if (Parents.empty()) return false; return Parents[0].get() != nullptr; diff --git a/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp b/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp index bea68884e3bda..ddc92ef312446 100644 --- a/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp @@ -59,7 +59,7 @@ class FindUsageOfThis : public RecursiveASTVisitor { UsageKind Usage = Unused; template const T *getParent(const Expr *E) { - DynTypedNodeList Parents = Ctxt.getParents(*E); + const DynTypedNodeList Parents = Ctxt.getParents(*E); if (Parents.size() != 1) return nullptr; @@ -241,7 +241,7 @@ void MakeMemberFunctionConstCheck::registerMatchers(MatchFinder *Finder) { } static SourceLocation getConstInsertionPoint(const CXXMethodDecl *M) { - TypeSourceInfo *TSI = M->getTypeSourceInfo(); + const TypeSourceInfo *TSI = M->getTypeSourceInfo(); if (!TSI) return {}; diff --git a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp index e15b2ecd8f5c0..69bc554778379 100644 --- a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp @@ -56,8 +56,8 @@ static void addParentheses(const BinaryOperator *BinOp, if (!BinOp) return; - int Precedence1 = getPrecedence(BinOp); - int Precedence2 = getPrecedence(ParentBinOp); + const int Precedence1 = getPrecedence(BinOp); + const int Precedence2 = getPrecedence(ParentBinOp); if (ParentBinOp != nullptr && Precedence1 != Precedence2 && Precedence1 > 0 && Precedence2 > 0) { diff --git a/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp b/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp index 0765d8d82ee04..450961c8b4fee 100644 --- a/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp @@ -21,7 +21,7 @@ static const IfStmt *getPrecedingIf(const SourceManager &SM, if (Parents.size() != 1) return nullptr; if (const auto *PrecedingIf = Parents[0].get()) { - SourceLocation PreviousElseLoc = PrecedingIf->getElseLoc(); + const SourceLocation PreviousElseLoc = PrecedingIf->getElseLoc(); if (SM.getExpansionLineNumber(PreviousElseLoc) == SM.getExpansionLineNumber(If->getIfLoc())) return PrecedingIf; @@ -33,7 +33,7 @@ void MisleadingIndentationCheck::danglingElseCheck(const SourceManager &SM, ASTContext *Context, const IfStmt *If) { SourceLocation IfLoc = If->getIfLoc(); - SourceLocation ElseLoc = If->getElseLoc(); + const SourceLocation ElseLoc = If->getElseLoc(); if (IfLoc.isMacroID() || ElseLoc.isMacroID()) return; @@ -89,8 +89,8 @@ void MisleadingIndentationCheck::missingBracesCheck( if (isa(Inner)) continue; - SourceLocation InnerLoc = Inner->getBeginLoc(); - SourceLocation OuterLoc = CurrentStmt->getBeginLoc(); + const SourceLocation InnerLoc = Inner->getBeginLoc(); + const SourceLocation OuterLoc = CurrentStmt->getBeginLoc(); if (InnerLoc.isInvalid() || InnerLoc.isMacroID() || OuterLoc.isInvalid() || OuterLoc.isMacroID()) @@ -101,7 +101,7 @@ void MisleadingIndentationCheck::missingBracesCheck( continue; const Stmt *NextStmt = CStmt->body_begin()[I + 1]; - SourceLocation NextLoc = NextStmt->getBeginLoc(); + const SourceLocation NextLoc = NextStmt->getBeginLoc(); if (NextLoc.isInvalid() || NextLoc.isMacroID()) continue;