================ @@ -0,0 +1,89 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "InconsistentIfelseBracesCheck.h" +#include "../utils/BracesAroundStatement.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +/// Check that at least one branch of the \p If statement is a \c CompoundStmt. +static bool shouldHaveBraces(const IfStmt *If) { + const Stmt *const Then = If->getThen(); + if (isa<CompoundStmt>(Then)) + return true; + + if (const Stmt *const Else = If->getElse()) { + if (const auto *NestedIf = dyn_cast<const IfStmt>(Else)) + return shouldHaveBraces(NestedIf); + + return isa<CompoundStmt>(Else); + } + + return false; +} + +void InconsistentIfelseBracesCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + traverse(TK_IgnoreUnlessSpelledInSource, + ifStmt(hasElse(anything()), + unless(isConsteval()), // 'if consteval' always has braces + unless(hasParent(ifStmt()))) + .bind("if_stmt")), + this); +} + +void InconsistentIfelseBracesCheck::check( + const MatchFinder::MatchResult &Result) { + const auto *MatchedIf = Result.Nodes.getNodeAs<IfStmt>("if_stmt"); + if (!shouldHaveBraces(MatchedIf)) ---------------- capitan-davide wrote:
Uhm, I am not familiar with other matchers that tries to enforce some "policy". What would be the benefits of this approach? IMHO it hurts readability a bit https://github.com/llvm/llvm-project/pull/162361 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
