-
Notifications
You must be signed in to change notification settings - Fork 14.3k
[clang-tidy] add new check readability-enum-initial-value #86129
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
Merged
HerrCai0907
merged 9 commits into
llvm:main
from
HerrCai0907:new-clang-tidy-check/readability/enum-initial-value
Apr 1, 2024
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4e0845a
[clang-tidy] add new check readability-enum-initial-value
HerrCai0907 d149661
fix format
HerrCai0907 e2088f6
Merge branch 'main' into new-clang-tidy-check/readability/enum-initia…
HerrCai0907 089815c
fix msg
HerrCai0907 eaeb491
fix
HerrCai0907 02fd17b
extend check
HerrCai0907 0382207
fix according to comment
HerrCai0907 3654919
fix comments
HerrCai0907 617e15a
fix
HerrCai0907 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
200 changes: 200 additions & 0 deletions
200
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.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,200 @@ | ||
//===--- EnumInitialValueCheck.cpp - clang-tidy ---------------------------===// | ||
// | ||
// 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 "EnumInitialValueCheck.h" | ||
#include "../utils/LexerUtils.h" | ||
#include "clang/AST/Decl.h" | ||
#include "clang/ASTMatchers/ASTMatchFinder.h" | ||
#include "clang/ASTMatchers/ASTMatchers.h" | ||
#include "clang/Basic/Diagnostic.h" | ||
#include "clang/Basic/SourceLocation.h" | ||
#include "llvm/ADT/STLExtras.h" | ||
#include "llvm/ADT/SmallString.h" | ||
|
||
using namespace clang::ast_matchers; | ||
|
||
namespace clang::tidy::readability { | ||
|
||
static bool isNoneEnumeratorsInitialized(const EnumDecl &Node) { | ||
return llvm::all_of(Node.enumerators(), [](const EnumConstantDecl *ECD) { | ||
return ECD->getInitExpr() == nullptr; | ||
}); | ||
} | ||
|
||
static bool isOnlyFirstEnumeratorInitialized(const EnumDecl &Node) { | ||
bool IsFirst = true; | ||
for (const EnumConstantDecl *ECD : Node.enumerators()) { | ||
if ((IsFirst && ECD->getInitExpr() == nullptr) || | ||
(!IsFirst && ECD->getInitExpr() != nullptr)) | ||
return false; | ||
IsFirst = false; | ||
} | ||
return !IsFirst; | ||
} | ||
|
||
static bool areAllEnumeratorsInitialized(const EnumDecl &Node) { | ||
return llvm::all_of(Node.enumerators(), [](const EnumConstantDecl *ECD) { | ||
return ECD->getInitExpr() != nullptr; | ||
}); | ||
} | ||
|
||
/// Check if \p Enumerator is initialized with a (potentially negated) \c | ||
/// IntegerLiteral. | ||
static bool isInitializedByLiteral(const EnumConstantDecl *Enumerator) { | ||
const Expr *const Init = Enumerator->getInitExpr(); | ||
if (!Init) | ||
return false; | ||
return Init->isIntegerConstantExpr(Enumerator->getASTContext()); | ||
} | ||
|
||
static void cleanInitialValue(DiagnosticBuilder &Diag, | ||
const EnumConstantDecl *ECD, | ||
const SourceManager &SM, | ||
const LangOptions &LangOpts) { | ||
const SourceRange InitExprRange = ECD->getInitExpr()->getSourceRange(); | ||
if (InitExprRange.isInvalid() || InitExprRange.getBegin().isMacroID() || | ||
InitExprRange.getEnd().isMacroID()) | ||
return; | ||
std::optional<Token> EqualToken = utils::lexer::findNextTokenSkippingComments( | ||
ECD->getLocation(), SM, LangOpts); | ||
if (!EqualToken.has_value() || | ||
EqualToken.value().getKind() != tok::TokenKind::equal) | ||
return; | ||
const SourceLocation EqualLoc{EqualToken->getLocation()}; | ||
if (EqualLoc.isInvalid() || EqualLoc.isMacroID()) | ||
return; | ||
Diag << FixItHint::CreateRemoval(EqualLoc) | ||
<< FixItHint::CreateRemoval(InitExprRange); | ||
return; | ||
} | ||
|
||
namespace { | ||
|
||
AST_MATCHER(EnumDecl, isMacro) { | ||
SourceLocation Loc = Node.getBeginLoc(); | ||
return Loc.isMacroID(); | ||
} | ||
|
||
AST_MATCHER(EnumDecl, hasConsistentInitialValues) { | ||
return isNoneEnumeratorsInitialized(Node) || | ||
isOnlyFirstEnumeratorInitialized(Node) || | ||
areAllEnumeratorsInitialized(Node); | ||
} | ||
|
||
AST_MATCHER(EnumDecl, hasZeroInitialValueForFirstEnumerator) { | ||
const EnumDecl::enumerator_range Enumerators = Node.enumerators(); | ||
if (Enumerators.empty()) | ||
return false; | ||
const EnumConstantDecl *ECD = *Enumerators.begin(); | ||
return isOnlyFirstEnumeratorInitialized(Node) && | ||
isInitializedByLiteral(ECD) && ECD->getInitVal().isZero(); | ||
} | ||
|
||
/// Excludes bitfields because enumerators initialized with the result of a | ||
/// bitwise operator on enumeration values or any other expr that is not a | ||
/// potentially negative integer literal. | ||
/// Enumerations where it is not directly clear if they are used with | ||
/// bitmask, evident when enumerators are only initialized with (potentially | ||
/// negative) integer literals, are ignored. This is also the case when all | ||
/// enumerators are powers of two (e.g., 0, 1, 2). | ||
AST_MATCHER(EnumDecl, hasSequentialInitialValues) { | ||
const EnumDecl::enumerator_range Enumerators = Node.enumerators(); | ||
if (Enumerators.empty()) | ||
return false; | ||
const EnumConstantDecl *const FirstEnumerator = *Node.enumerator_begin(); | ||
llvm::APSInt PrevValue = FirstEnumerator->getInitVal(); | ||
if (!isInitializedByLiteral(FirstEnumerator)) | ||
return false; | ||
bool AllEnumeratorsArePowersOfTwo = true; | ||
for (const EnumConstantDecl *Enumerator : llvm::drop_begin(Enumerators)) { | ||
const llvm::APSInt NewValue = Enumerator->getInitVal(); | ||
if (NewValue != ++PrevValue) | ||
return false; | ||
if (!isInitializedByLiteral(Enumerator)) | ||
return false; | ||
PrevValue = NewValue; | ||
AllEnumeratorsArePowersOfTwo &= NewValue.isPowerOf2(); | ||
} | ||
return !AllEnumeratorsArePowersOfTwo; | ||
} | ||
|
||
} // namespace | ||
|
||
EnumInitialValueCheck::EnumInitialValueCheck(StringRef Name, | ||
ClangTidyContext *Context) | ||
: ClangTidyCheck(Name, Context), | ||
AllowExplicitZeroFirstInitialValue( | ||
Options.get("AllowExplicitZeroFirstInitialValue", true)), | ||
AllowExplicitSequentialInitialValues( | ||
Options.get("AllowExplicitSequentialInitialValues", true)) {} | ||
|
||
void EnumInitialValueCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { | ||
Options.store(Opts, "AllowExplicitZeroFirstInitialValue", | ||
AllowExplicitZeroFirstInitialValue); | ||
Options.store(Opts, "AllowExplicitSequentialInitialValues", | ||
AllowExplicitSequentialInitialValues); | ||
} | ||
|
||
void EnumInitialValueCheck::registerMatchers(MatchFinder *Finder) { | ||
Finder->addMatcher( | ||
enumDecl(unless(isMacro()), unless(hasConsistentInitialValues())) | ||
.bind("inconsistent"), | ||
this); | ||
if (!AllowExplicitZeroFirstInitialValue) | ||
Finder->addMatcher( | ||
enumDecl(hasZeroInitialValueForFirstEnumerator()).bind("zero_first"), | ||
PiotrZSL marked this conversation as resolved.
Show resolved
Hide resolved
|
||
this); | ||
if (!AllowExplicitSequentialInitialValues) | ||
Finder->addMatcher(enumDecl(unless(isMacro()), hasSequentialInitialValues()) | ||
.bind("sequential"), | ||
this); | ||
} | ||
|
||
void EnumInitialValueCheck::check(const MatchFinder::MatchResult &Result) { | ||
if (const auto *Enum = Result.Nodes.getNodeAs<EnumDecl>("inconsistent")) { | ||
DiagnosticBuilder Diag = | ||
diag(Enum->getBeginLoc(), | ||
"inital values in enum %0 are not consistent, consider explicit " | ||
"initialization of all, none or only the first enumerator") | ||
<< Enum; | ||
for (const EnumConstantDecl *ECD : Enum->enumerators()) | ||
if (ECD->getInitExpr() == nullptr) { | ||
const SourceLocation EndLoc = Lexer::getLocForEndOfToken( | ||
ECD->getLocation(), 0, *Result.SourceManager, getLangOpts()); | ||
if (EndLoc.isMacroID()) | ||
continue; | ||
llvm::SmallString<8> Str{" = "}; | ||
ECD->getInitVal().toString(Str); | ||
Diag << FixItHint::CreateInsertion(EndLoc, Str); | ||
} | ||
return; | ||
} | ||
|
||
if (const auto *Enum = Result.Nodes.getNodeAs<EnumDecl>("zero_first")) { | ||
const EnumConstantDecl *ECD = *Enum->enumerator_begin(); | ||
const SourceLocation Loc = ECD->getLocation(); | ||
if (Loc.isInvalid() || Loc.isMacroID()) | ||
return; | ||
DiagnosticBuilder Diag = diag(Loc, "zero initial value for the first " | ||
"enumerator in %0 can be disregarded") | ||
<< Enum; | ||
cleanInitialValue(Diag, ECD, *Result.SourceManager, getLangOpts()); | ||
return; | ||
} | ||
if (const auto *Enum = Result.Nodes.getNodeAs<EnumDecl>("sequential")) { | ||
DiagnosticBuilder Diag = | ||
diag(Enum->getBeginLoc(), | ||
"sequential initial value in %0 can be ignored") | ||
<< Enum; | ||
for (const EnumConstantDecl *ECD : llvm::drop_begin(Enum->enumerators())) | ||
cleanInitialValue(Diag, ECD, *Result.SourceManager, getLangOpts()); | ||
return; | ||
} | ||
} | ||
|
||
} // namespace clang::tidy::readability |
38 changes: 38 additions & 0 deletions
38
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.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,38 @@ | ||
//===--- EnumInitialValueCheck.h - clang-tidy -------------------*- C++ -*-===// | ||
// | ||
// 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_ENUMINITIALVALUECHECK_H | ||
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_ENUMINITIALVALUECHECK_H | ||
|
||
#include "../ClangTidyCheck.h" | ||
|
||
namespace clang::tidy::readability { | ||
|
||
/// Enforces consistent style for enumerators' initialization, covering three | ||
/// styles: none, first only, or all initialized explicitly. | ||
/// | ||
/// For the user-facing documentation see: | ||
/// http://clang.llvm.org/extra/clang-tidy/checks/readability/enum-initial-value.html | ||
class EnumInitialValueCheck : public ClangTidyCheck { | ||
public: | ||
EnumInitialValueCheck(StringRef Name, ClangTidyContext *Context); | ||
void storeOptions(ClangTidyOptions::OptionMap &Opts) override; | ||
void registerMatchers(ast_matchers::MatchFinder *Finder) override; | ||
void check(const ast_matchers::MatchFinder::MatchResult &Result) override; | ||
HerrCai0907 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
std::optional<TraversalKind> getCheckTraversalKind() const override { | ||
return TK_IgnoreUnlessSpelledInSource; | ||
} | ||
|
||
private: | ||
const bool AllowExplicitZeroFirstInitialValue; | ||
const bool AllowExplicitSequentialInitialValues; | ||
}; | ||
|
||
} // namespace clang::tidy::readability | ||
|
||
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_ENUMINITIALVALUECHECK_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
75 changes: 75 additions & 0 deletions
75
clang-tools-extra/docs/clang-tidy/checks/readability/enum-initial-value.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,75 @@ | ||
.. title:: clang-tidy - readability-enum-initial-value | ||
|
||
readability-enum-initial-value | ||
============================== | ||
|
||
Enforces consistent style for enumerators' initialization, covering three | ||
styles: none, first only, or all initialized explicitly. | ||
|
||
When adding new enumerations, inconsistent initial value will cause potential | ||
enumeration value conflicts. | ||
|
||
In an enumeration, the following three cases are accepted. | ||
1. none of enumerators are explicit initialized. | ||
2. the first enumerator is explicit initialized. | ||
3. all of enumerators are explicit initialized. | ||
|
||
.. code-block:: c++ | ||
|
||
// valid, none of enumerators are initialized. | ||
enum A { | ||
e0, | ||
e1, | ||
e2, | ||
}; | ||
|
||
// valid, the first enumerator is initialized. | ||
enum A { | ||
e0 = 0, | ||
e1, | ||
e2, | ||
}; | ||
|
||
// valid, all of enumerators are initialized. | ||
enum A { | ||
e0 = 0, | ||
e1 = 1, | ||
e2 = 2, | ||
}; | ||
|
||
// invalid, e1 is not explicit initialized. | ||
enum A { | ||
e0 = 0, | ||
e1, | ||
e2 = 2, | ||
}; | ||
|
||
Options | ||
------- | ||
|
||
.. option:: AllowExplicitZeroFirstInitialValue | ||
|
||
If set to `false`, the first enumerator must not be explicitly initialized. | ||
See examples below. Default is `true`. | ||
|
||
.. code-block:: c++ | ||
|
||
enum A { | ||
e0 = 0, // not allowed if AllowExplicitZeroFirstInitialValue is false | ||
e1, | ||
e2, | ||
}; | ||
|
||
|
||
.. option:: AllowExplicitSequentialInitialValues | ||
|
||
If set to `false`, sequential initializations are not allowed. | ||
See examples below. Default is `true`. | ||
|
||
.. code-block:: c++ | ||
|
||
enum A { | ||
e0 = 1, // not allowed if AllowExplicitSequentialInitialValues is false | ||
e1 = 2, | ||
e2 = 3, | ||
}; |
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.
Uh oh!
There was an error while loading. Please reload this page.