-
Notifications
You must be signed in to change notification settings - Fork 15.2k
[clang-tidy] Add new check 'bugprone-inconsistent-ifelse-braces' #162361
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
capitan-davide
wants to merge
7
commits into
llvm:main
Choose a base branch
from
capitan-davide:bugprone-inconsistent-ifelse-braces
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5f61932
[clang-tidy] Add new check 'bugprone-inconsistent-ifelse-braces'
capitan-davide 18e6ae8
[clang-tidy] Add some tests to 'bugprone-inconsistent-ifelse-braces'
capitan-davide 117eb01
[clang-tidy] Update documentation for 'bugprone-inconsistent-ifelse-b…
capitan-davide 40570f9
[clang-tidy] Apply suggestions from code review
capitan-davide 6a652cd
[clang-tidy] Apply suggestions from code review
capitan-davide 540a43c
[clang-tidy] Add some test for constexpr if
capitan-davide 02aa926
[clang-tidy] Add some suggestions from code review
capitan-davide File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
89 changes: 89 additions & 0 deletions
89
clang-tools-extra/clang-tidy/readability/InconsistentIfElseBracesCheck.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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::readability { | ||
|
|
||
| /// 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( | ||
| 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)) | ||
| return; | ||
| checkIfStmt(Result, MatchedIf); | ||
| } | ||
|
|
||
| void InconsistentIfElseBracesCheck::checkIfStmt( | ||
| const MatchFinder::MatchResult &Result, const IfStmt *If) { | ||
| const Stmt *Then = If->getThen(); | ||
| if (const auto *NestedIf = dyn_cast<const IfStmt>(Then)) { | ||
| // If the then-branch is a nested IfStmt, first we need to add braces to | ||
| // it, then we need to check the inner IfStmt. | ||
| emitDiagnostic(Result, If->getThen(), If->getRParenLoc(), If->getElseLoc()); | ||
| if (shouldHaveBraces(NestedIf)) | ||
| checkIfStmt(Result, NestedIf); | ||
| } else if (!isa<CompoundStmt>(Then)) { | ||
| emitDiagnostic(Result, If->getThen(), If->getRParenLoc(), If->getElseLoc()); | ||
| } | ||
|
|
||
| if (const Stmt *const Else = If->getElse()) { | ||
| if (const auto *NestedIf = dyn_cast<const IfStmt>(Else)) | ||
| checkIfStmt(Result, NestedIf); | ||
| else if (!isa<CompoundStmt>(Else)) | ||
| emitDiagnostic(Result, If->getElse(), If->getElseLoc()); | ||
| } | ||
| } | ||
|
|
||
| void InconsistentIfElseBracesCheck::emitDiagnostic( | ||
| const MatchFinder::MatchResult &Result, const Stmt *S, | ||
| SourceLocation StartLoc, SourceLocation EndLocHint) { | ||
| const SourceManager &SM = *Result.SourceManager; | ||
| const LangOptions &LangOpts = Result.Context->getLangOpts(); | ||
|
|
||
| if (!StartLoc.isMacroID()) { | ||
| const utils::BraceInsertionHints Hints = | ||
| utils::getBraceInsertionsHints(S, LangOpts, SM, StartLoc, EndLocHint); | ||
| assert(Hints && Hints.offersFixIts() && "Expected hints or fix-its"); | ||
| diag(Hints.DiagnosticPos, "<message>") | ||
| << Hints.openingBraceFixIt() << Hints.closingBraceFixIt(); | ||
| } else { | ||
| diag(StartLoc, "<message-for-macro-expansions>") << StartLoc.isMacroID(); | ||
| } | ||
| } | ||
|
|
||
| } // namespace clang::tidy::readability | ||
43 changes: 43 additions & 0 deletions
43
clang-tools-extra/clang-tidy/readability/InconsistentIfElseBracesCheck.h
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // 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 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_INCONSISTENTIFELSEBRACESCHECK_H | ||
| #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_INCONSISTENTIFELSEBRACESCHECK_H | ||
|
|
||
| #include "../ClangTidyCheck.h" | ||
| #include "clang/AST/ASTTypeTraits.h" | ||
| #include <optional> | ||
|
|
||
| namespace clang::tidy::readability { | ||
|
|
||
| /// Detects `if`/`else` statements where one branch uses braces and the other | ||
| /// does not. | ||
| /// | ||
| /// For the user-facing documentation see: | ||
| /// https://clang.llvm.org/extra/clang-tidy/checks/readability/inconsistent-ifelse-braces.html | ||
| class InconsistentIfElseBracesCheck : public ClangTidyCheck { | ||
| public: | ||
| InconsistentIfElseBracesCheck(StringRef Name, ClangTidyContext *Context) | ||
| : ClangTidyCheck(Name, Context) {} | ||
| void registerMatchers(ast_matchers::MatchFinder *Finder) override; | ||
| void check(const ast_matchers::MatchFinder::MatchResult &Result) override; | ||
| std::optional<TraversalKind> getCheckTraversalKind() const override { | ||
| return TK_IgnoreUnlessSpelledInSource; | ||
| } | ||
|
|
||
| private: | ||
| void checkIfStmt(const ast_matchers::MatchFinder::MatchResult &Result, | ||
| const IfStmt *If); | ||
| void emitDiagnostic(const ast_matchers::MatchFinder::MatchResult &Result, | ||
| const Stmt *S, SourceLocation StartLoc, | ||
| SourceLocation EndLocHint = {}); | ||
| }; | ||
|
|
||
| } // namespace clang::tidy::readability | ||
|
|
||
| #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_INCONSISTENTIFELSEBRACESCHECK_H |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
...g-tools-extra/docs/clang-tidy/checks/readability/inconsistent-ifelse-braces.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| .. title:: clang-tidy - readability-inconsistent-ifelse-braces | ||
|
|
||
| readability-inconsistent-ifelse-braces | ||
| ====================================== | ||
|
|
||
| Detects ``if``/``else`` statements where one branch uses braces and the other | ||
| does not. | ||
|
|
||
| Before: | ||
|
|
||
| .. code-block:: c++ | ||
|
|
||
| if (condition) { | ||
| statement; | ||
| } else | ||
| statement; | ||
|
|
||
| if (condition) | ||
| statement; | ||
|
|
||
| if (condition) | ||
| statement; | ||
| else | ||
| statement; | ||
|
|
||
| After: | ||
|
|
||
| .. code-block:: c++ | ||
|
|
||
| if (condition) { | ||
| statement; | ||
| } else { | ||
| statement; | ||
| } | ||
|
|
||
| if (condition) | ||
| statement; | ||
|
|
||
| if (condition) | ||
| statement; | ||
| else | ||
| statement; |
54 changes: 54 additions & 0 deletions
54
...ls-extra/test/clang-tidy/checkers/readability/inconsistent-ifelse-braces-consteval-if.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| // RUN: %check_clang_tidy -std=c++23-or-later %s readability-inconsistent-ifelse-braces %t | ||
|
|
||
| bool cond(const char *) { return false; } | ||
| void do_something(const char *) {} | ||
|
|
||
| // Positive tests. | ||
| void f() { | ||
| if consteval { | ||
| if (cond("if1")) | ||
| do_something("if-single-line"); | ||
| else { | ||
| } | ||
| // CHECK-MESSAGES: :[[@LINE-4]]:21: warning: <message> [readability-inconsistent-ifelse-braces] | ||
| // CHECK-FIXES: if (cond("if1")) { | ||
| // CHECK-FIXES: } else { | ||
| } | ||
|
|
||
| if consteval { | ||
| if (cond("if2")) | ||
| do_something("if-single-line"); | ||
| else { | ||
| } | ||
| // CHECK-MESSAGES: :[[@LINE-4]]:21: warning: <message> [readability-inconsistent-ifelse-braces] | ||
| // CHECK-FIXES: if (cond("if2")) { | ||
| // CHECK-FIXES: } else { | ||
| } else { | ||
| if (cond("if2.1")) { | ||
| } else | ||
| do_something("else-single-line"); | ||
| // CHECK-MESSAGES: :[[@LINE-2]]:11: warning: <message> [readability-inconsistent-ifelse-braces] | ||
| // CHECK-FIXES: } else { | ||
| // CHECK-FIXES: } | ||
| } | ||
| } | ||
|
|
||
| // Negative tests. | ||
| void g() { | ||
| if consteval { | ||
| if (cond("if0")) { | ||
| do_something("if-single-line"); | ||
| } else if (cond("if0")) { | ||
| do_something("elseif-single-line"); | ||
| } else { | ||
| do_something("else-single-line"); | ||
| } | ||
| } else { | ||
| if (cond("if0.1")) | ||
| do_something("if-single-line"); | ||
| else if (cond("if0.1")) | ||
| do_something("elseif-single-line"); | ||
| else | ||
| do_something("else-single-line"); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of matching each
ifstatement, we should be able to checkshouldHaveBracesinsideaddMatcher.Create custom AST-matcher on
IfStmtand runshouldHaveBraceson it.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Uhm, I am not familiar with other matchers that tries to enforce some kind of "policy". What would be the benefits of this approach? IMHO it hurts readability a bit.