[clang-tidy][NFC] Fix readability-inconsistent-ifelse-braces warnings (#182764)

This align with [LLVM coding
conventions](https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements):
Quote:
```cpp
// Use braces for the `if` block to keep it uniform with the `else` block.
if (isa<FunctionDecl>(D)) {
  handleFunctionDecl(D);
} else {
  // In this `else` case, it is necessary that we explain the situation with
  // this surprisingly long comment, so it would be unclear without the braces
  // whether the following statement is in the scope of the `if`.
  handleOtherDecl(D);
}
```
This commit is contained in:
Baranov Victor 2026-02-23 11:17:58 +03:00 committed by GitHub
parent 57f3f1470e
commit 404452b29e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 87 additions and 65 deletions

View File

@ -213,18 +213,19 @@ formNoLintBlocks(SmallVector<NoLintToken> NoLints, const SourceManager &SrcMgr,
// inner-most block first, then the next level up, and so on. This is
// essentially a last-in-first-out/stack system.
for (NoLintToken &NoLint : NoLints) {
if (NoLint.Type == NoLintType::NoLintBegin)
if (NoLint.Type == NoLintType::NoLintBegin) {
// A new block is being started. Add it to the stack.
Stack.emplace_back(std::move(NoLint));
else if (NoLint.Type == NoLintType::NoLintEnd) {
} else if (NoLint.Type == NoLintType::NoLintEnd) {
if (!Stack.empty() && Stack.back().checks() == NoLint.checks()) {
// The previous block is being closed. Pop one element off the stack.
CompletedBlocks.emplace_back(Stack.back().Pos, NoLint.Pos,
std::move(Stack.back().ChecksGlob));
Stack.pop_back();
} else
} else {
// Trying to close the wrong block.
NoLintErrors.emplace_back(makeNoLintError(SrcMgr, File, NoLint));
}
}
}

View File

@ -131,9 +131,9 @@ void ImplicitWideningOfMultiplicationResultCheck::handleImplicitCastExpr(
QualType WideExprTy;
// Get Ty of the same signedness as ExprTy, because we only want to suggest
// to widen the computation, but not change it's signedness domain.
if (Ty->isSignedIntegerType() == ETy->isSignedIntegerType())
if (Ty->isSignedIntegerType() == ETy->isSignedIntegerType()) {
WideExprTy = Ty;
else if (Ty->isSignedIntegerType()) {
} else if (Ty->isSignedIntegerType()) {
assert(ETy->isUnsignedIntegerType() &&
"Expected source type to be signed.");
WideExprTy = Context->getCorrespondingUnsignedType(Ty);
@ -179,8 +179,9 @@ void ImplicitWideningOfMultiplicationResultCheck::handlePointerOffsetting(
} else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
PointerExpr = ASE->getLHS();
IndexExpr = ASE->getRHS();
} else
} else {
return;
}
if (IndexExpr->getType()->isPointerType())
std::swap(PointerExpr, IndexExpr);

View File

@ -75,8 +75,9 @@ void IncDecInConditionsCheck::check(const MatchFinder::MatchResult &Result) {
Result.Nodes.getNodeAs<UnaryOperator>("operator")) {
ExprLoc = MatchedDecl->getExprLoc();
IsIncrementOp = MatchedDecl->isIncrementOp();
} else
} else {
return;
}
diag(ExprLoc,
"%select{decrementing|incrementing}0 and referencing a variable in a "

View File

@ -164,10 +164,11 @@ static bool isKnownToHaveValue(const Expr &Cond, const ASTContext &Ctx,
} else if (const auto *UnOp = dyn_cast<UnaryOperator>(&Cond)) {
if (UnOp->getOpcode() == UO_LNot)
return isKnownToHaveValue(*UnOp->getSubExpr(), Ctx, !ExpectedValue);
} else if (const auto *Paren = dyn_cast<ParenExpr>(&Cond))
} else if (const auto *Paren = dyn_cast<ParenExpr>(&Cond)) {
return isKnownToHaveValue(*Paren->getSubExpr(), Ctx, ExpectedValue);
else if (const auto *ImplCast = dyn_cast<ImplicitCastExpr>(&Cond))
} else if (const auto *ImplCast = dyn_cast<ImplicitCastExpr>(&Cond)) {
return isKnownToHaveValue(*ImplCast->getSubExpr(), Ctx, ExpectedValue);
}
return false;
}
bool Result = false;

View File

@ -86,13 +86,13 @@ void InitVariablesCheck::check(const MatchFinder::MatchResult &Result) {
std::optional<const char *> InitializationString;
bool AddMathInclude = false;
if (TypePtr->isEnumeralType())
if (TypePtr->isEnumeralType()) {
InitializationString = nullptr;
else if (TypePtr->isBooleanType())
} else if (TypePtr->isBooleanType()) {
InitializationString = " = false";
else if (TypePtr->isIntegerType())
} else if (TypePtr->isIntegerType()) {
InitializationString = " = 0";
else if (TypePtr->isFloatingType()) {
} else if (TypePtr->isFloatingType()) {
InitializationString = " = NAN";
AddMathInclude = true;
} else if (TypePtr->isAnyPointerType() || TypePtr->isMemberPointerType()) {

View File

@ -217,9 +217,9 @@ void PreferMemberInitializerCheck::check(
continue;
if (Init->getMember() == Field) {
HasInitAlready = true;
if (isa<ImplicitValueInitExpr>(Init->getInit()))
if (isa<ImplicitValueInitExpr>(Init->getInit())) {
InsertPos = Init->getRParenLoc();
else {
} else {
ReplaceRange = Init->getInit()->getSourceRange();
AddBrace = isa<InitListExpr>(Init->getInit());
}

View File

@ -71,8 +71,9 @@ removeFieldInitialized(const FieldDecl *M,
// Erase all members in a union if any member of it is initialized.
for (const auto *F : R->fields())
FieldDecls.erase(F);
} else
} else {
FieldDecls.erase(M);
}
}
static void

View File

@ -64,25 +64,26 @@ static bool containsMisleadingBidi(StringRef Buffer,
// Open a PDF context.
if (CodePoint == RLO || CodePoint == RLE || CodePoint == LRO ||
CodePoint == LRE)
CodePoint == LRE) {
BidiContexts.push_back(PDF);
// Close PDF Context.
else if (CodePoint == PDF) {
} else if (CodePoint == PDF) {
if (!BidiContexts.empty() && BidiContexts.back() == PDF)
BidiContexts.pop_back();
}
// Open a PDI Context.
else if (CodePoint == RLI || CodePoint == LRI || CodePoint == FSI)
else if (CodePoint == RLI || CodePoint == LRI || CodePoint == FSI) {
BidiContexts.push_back(PDI);
// Close a PDI Context.
else if (CodePoint == PDI) {
} else if (CodePoint == PDI) {
auto R = llvm::find(llvm::reverse(BidiContexts), PDI);
if (R != BidiContexts.rend())
BidiContexts.resize(BidiContexts.rend() - R - 1);
}
// Line break or equivalent
else if (CodePoint == PS)
else if (CodePoint == PS) {
BidiContexts.clear();
}
}
return !BidiContexts.empty();
}

View File

@ -679,11 +679,13 @@ static bool retrieveRelationalIntegerConstantExpr(
if (!Arg->isValueDependent() &&
!Arg->isIntegerConstantExpr(*Result.Context))
return false;
} else
} else {
return false;
}
}
} else
} else {
return false;
}
Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
OperandExpr = OverloadedOperatorExpr;

View File

@ -103,10 +103,10 @@ void ThrowByValueCatchByReferenceCheck::diagnoseThrowLocations(
// If we have a DeclRefExpr, we flag for emitting a diagnosis message in
// case the referenced variable is neither a function parameter nor a
// variable declared in the catch statement.
if (VariableReference)
if (VariableReference) {
Emit = !isFunctionOrCatchVar(VariableReference);
else if (ConstructorCall &&
ConstructorCall->getConstructor()->isCopyOrMoveConstructor()) {
} else if (ConstructorCall &&
ConstructorCall->getConstructor()->isCopyOrMoveConstructor()) {
// If we have a copy / move construction, we emit a diagnosis message if
// the object that we copy construct from is neither a function parameter
// nor a variable declared in a catch statement

View File

@ -185,8 +185,9 @@ static bool anyDescendantIsLocal(const Stmt *Statement) {
if (Var->isLocalVarDeclOrParm())
return true;
}
} else if (isa<CXXThisExpr>(Statement))
} else if (isa<CXXThisExpr>(Statement)) {
return true;
}
return any_of(Statement->children(), anyDescendantIsLocal);
}
@ -365,10 +366,11 @@ static void addFunctionCallArgs(ArrayRef<BindArgument> Args,
if (B.Kind == BK_Placeholder) {
Stream << "std::forward<decltype(" << B.UsageIdentifier << ")>";
Stream << "(" << B.UsageIdentifier << ")";
} else if (B.CM != CM_None)
} else if (B.CM != CM_None) {
Stream << B.UsageIdentifier;
else
} else {
Stream << B.SourceTokens;
}
Delimiter = ", ";
}

View File

@ -147,9 +147,9 @@ void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
} else if (ArrayTypeLoc.getTypePtr()->isIncompleteArrayType() && IsInParam) {
// in function parameter, we also don't know the size of
// IncompleteArrayType.
if (Result.Context->getLangOpts().CPlusPlus20)
if (Result.Context->getLangOpts().CPlusPlus20) {
RecommendTypes.push_back("'std::span'");
else {
} else {
RecommendTypes.push_back("'std::array'");
RecommendTypes.push_back("'std::vector'");
}

View File

@ -81,8 +81,9 @@ static StringRef getDestTypeString(const SourceManager &SM,
} else if (const auto *CastExpr = dyn_cast<CXXFunctionalCastExpr>(Expr)) {
BeginLoc = CastExpr->getBeginLoc();
EndLoc = CastExpr->getLParenLoc().getLocWithOffset(-1);
} else
} else {
llvm_unreachable("Unsupported CastExpr");
}
return Lexer::getSourceText(CharSourceRange::getTokenRange(BeginLoc, EndLoc),
SM, LangOpts);

View File

@ -67,8 +67,9 @@ void DeprecatedIosBaseAliasesCheck::check(
if (Fix)
Builder << FixItHint::CreateReplacement(SourceRange(IoStateLoc, EndLoc),
FixName);
} else
} else {
diag(IoStateLoc, "'std::ios_base::%0' is deprecated") << TypeName;
}
}
} // namespace clang::tidy::modernize

View File

@ -107,9 +107,9 @@ static LiteralSize literalTokenSize(const Token &Tok) {
if (std::isdigit(Text[End]))
break;
if (std::toupper(Text[End]) == 'U')
if (std::toupper(Text[End]) == 'U') {
SeenUnsigned = true;
else if (std::toupper(Text[End]) == 'L') {
} else if (std::toupper(Text[End]) == 'L') {
if (SeenLong)
SeenLongLong = true;
SeenLong = true;

View File

@ -795,9 +795,9 @@ bool ForLoopIndexUseVisitor::VisitDeclStmt(DeclStmt *S) {
AliasDecl = S;
if (CurrStmtParent) {
if (isa<IfStmt>(CurrStmtParent) || isa<WhileStmt>(CurrStmtParent) ||
isa<SwitchStmt>(CurrStmtParent))
isa<SwitchStmt>(CurrStmtParent)) {
ReplaceWithAliasUse = true;
else if (isa<ForStmt>(CurrStmtParent)) {
} else if (isa<ForStmt>(CurrStmtParent)) {
if (cast<ForStmt>(CurrStmtParent)->getConditionVariableDeclStmt() == S)
ReplaceWithAliasUse = true;
else

View File

@ -277,10 +277,11 @@ void ContainerSizeEmptyCheck::check(const MatchFinder::MatchResult &Result) {
ReplacementText += "empty()";
} else if (E->isImplicitCXXThis()) {
ReplacementText += "empty()";
} else if (E->getType()->isPointerType())
} else if (E->getType()->isPointerType()) {
ReplacementText += "->empty()";
else
} else {
ReplacementText += ".empty()";
}
if (BinCmp) {
if (BinCmp->getOperator() == OO_ExclaimEqual)

View File

@ -117,8 +117,9 @@ void DuplicateIncludeCallbacks::InclusionDirective(
advanceBeyondCurrentLine(SM, FilenameRange.getEnd(), 1);
Check.diag(HashLoc, "duplicate include")
<< FixItHint::CreateRemoval(SourceRange{Start, End});
} else
} else {
Files.back().push_back(FileName);
}
}
void DuplicateIncludeCallbacks::MacroDefined(const Token &MacroNameTok,

View File

@ -115,8 +115,9 @@ struct CognitiveComplexity final {
} else if (C == Criteria::IncrementNesting) {
Increment = 0; // Unused in this message.
MsgId = 3;
} else
} else {
llvm_unreachable("should not get to here.");
}
return {MsgId, Increment};
}

View File

@ -193,8 +193,9 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
if (std::optional<SourceRange> TypeSpec =
getTypeSpecifierLocation(Var, Result)) {
TypeSpecifier = *TypeSpec;
} else
} else {
return;
}
llvm::SmallVector<SourceRange, 4> RemoveQualifiersRange;
auto CheckQualifier = [&](bool IsPresent, Qualifier Qual) {

View File

@ -188,8 +188,9 @@ static bool applySubstringHeuristic(StringRef Arg, StringRef Param,
Current[J] = 1 + Previous[J - 1];
MaxLength = std::max(MaxLength, Current[J]);
} else
} else {
Current[J] = 0;
}
}
Current.swap(Previous);

View File

@ -524,11 +524,11 @@ static bool verifyChecks(const StringSet<> &AllChecks, StringRef CheckGlob,
if (llvm::none_of(AllChecks.keys(),
[&Item](StringRef S) { return Item.Regex.match(S); })) {
AnyInvalid = true;
if (Item.Text.contains('*'))
if (Item.Text.contains('*')) {
llvm::WithColor::warning(llvm::errs(), Source)
<< "check glob '" << Item.Text << "' doesn't match any known check"
<< VerifyConfigWarningEnd;
else {
} else {
llvm::raw_ostream &Output =
llvm::WithColor::warning(llvm::errs(), Source)
<< "unknown check '" << Item.Text << '\'';

View File

@ -534,11 +534,12 @@ ExceptionAnalyzer::throwsException(const Stmt *St,
Results.registerException(
ThrownExpr->getType()->getUnqualifiedDesugaredType(),
{Throw->getBeginLoc(), CallStack});
} else
} else {
// A rethrow of a caught exception happens which makes it possible
// to throw all exception that are caught in the 'catch' clause of
// the parent try-catch block.
Results.registerExceptions(Caught);
}
} else if (const auto *Try = dyn_cast<CXXTryStmt>(St)) {
ExceptionInfo Uncaught =
throwsException(Try->getTryBlock(), Caught, CallStack);
@ -644,8 +645,9 @@ ExceptionAnalyzer::analyzeImpl(const FunctionDecl *Func) {
// The results here might be relevant to different analysis passes
// with different needs as well.
FunctionCache.try_emplace(Func, ExceptionList);
} else
} else {
ExceptionList = CacheEntry->getSecond();
}
return ExceptionList;
}

View File

@ -436,9 +436,9 @@ void FormatStringConverter::emitStringArgument(unsigned ArgIndex,
}
auto CStrMatches = match(*StringCStrCallExprMatcher, *Arg, *Context);
if (CStrMatches.size() == 1)
if (CStrMatches.size() == 1) {
ArgCStrRemovals.push_back(CStrMatches.front());
else if (Arg->getType()->isPointerType()) {
} else if (Arg->getType()->isPointerType()) {
const QualType Pointee = Arg->getType()->getPointeeType();
// printf is happy to print signed char and unsigned char strings, but
// std::format only likes char strings.
@ -702,25 +702,25 @@ void FormatStringConverter::finalizeFormatText() {
void FormatStringConverter::appendFormatText(const StringRef Text) {
for (const char Ch : Text) {
const auto UCh = static_cast<unsigned char>(Ch);
if (Ch == '\a')
if (Ch == '\a') {
StandardFormatString += "\\a";
else if (Ch == '\b')
} else if (Ch == '\b') {
StandardFormatString += "\\b";
else if (Ch == '\f')
} else if (Ch == '\f') {
StandardFormatString += "\\f";
else if (Ch == '\n')
} else if (Ch == '\n') {
StandardFormatString += "\\n";
else if (Ch == '\r')
} else if (Ch == '\r') {
StandardFormatString += "\\r";
else if (Ch == '\t')
} else if (Ch == '\t') {
StandardFormatString += "\\t";
else if (Ch == '\v')
} else if (Ch == '\v') {
StandardFormatString += "\\v";
else if (Ch == '\"')
} else if (Ch == '\"') {
StandardFormatString += "\\\"";
else if (Ch == '\\')
} else if (Ch == '\\') {
StandardFormatString += "\\\\";
else if (Ch == '{') {
} else if (Ch == '{') {
StandardFormatString += "{{";
FormatStringNeededRewriting = true;
} else if (Ch == '}') {
@ -730,8 +730,9 @@ void FormatStringConverter::appendFormatText(const StringRef Text) {
StandardFormatString += "\\x";
StandardFormatString += llvm::hexdigit(UCh >> 4, true);
StandardFormatString += llvm::hexdigit(UCh & 0xf, true);
} else
} else {
StandardFormatString += Ch;
}
}
}
@ -780,9 +781,10 @@ void FormatStringConverter::applyFixes(DiagnosticBuilder &Diag,
// That c_str() removal is now dealt with, so we don't need to do it again
ArgCStrRemovals.erase(CStrRemovalMatch);
} else
} else {
Diag << tooling::fixit::createReplacement(*Args[ValueArgIndex - ArgCount],
*Args[ValueArgIndex], *Context);
}
// Now shift down the field width and precision (if either are present) to
// accommodate it.

View File

@ -185,11 +185,11 @@ std::optional<Token> getQualifyingToken(tok::TokenKind TK,
Tok.setIdentifierInfo(&Info);
Tok.setKind(Info.getTokenID());
}
if (Tok.is(tok::less))
if (Tok.is(tok::less)) {
SawTemplate = true;
else if (Tok.isOneOf(tok::greater, tok::greatergreater))
} else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
LastMatchAfterTemplate = std::nullopt;
else if (Tok.is(TK)) {
} else if (Tok.is(TK)) {
if (SawTemplate)
LastMatchAfterTemplate = Tok;
else

View File

@ -169,8 +169,9 @@ static NameLookup findDeclInBases(const CXXRecordDecl &Parent,
Found = *Search;
continue;
}
} else
} else {
return NameLookup(std::nullopt); // Propagate multiple resolution back up.
}
}
return NameLookup(Found); // If nullptr, decl wasn't found.
}