11#include "clang/AST/Decl.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Basic/Diagnostic.h"
15#include "clang/Basic/SourceLocation.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallString.h"
27 const Expr *Init = ECD->getInitExpr();
31 const auto *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParenImpCasts());
33 dyn_cast_if_present<EnumConstantDecl>(DRE ? DRE->getDecl() :
nullptr);
34 return RefECD && RefECD->getDeclContext() == ECD->getDeclContext();
44 return llvm::all_of(Node.enumerators(),
45 [AllowSelfRefs](
const EnumConstantDecl *ECD) {
46 return isAllowedSelfReference(ECD, AllowSelfRefs) ||
47 ECD->getInitExpr() == nullptr;
54 for (
const EnumConstantDecl *ECD : Node.enumerators()) {
57 if ((IsFirst && ECD->getInitExpr() ==
nullptr) ||
58 (!IsFirst && ECD->getInitExpr() !=
nullptr))
66 return llvm::all_of(Node.enumerators(), [](
const EnumConstantDecl *ECD) {
67 return ECD->getInitExpr() != nullptr;
74 const Expr *
const Init = Enumerator->getInitExpr();
77 return Init->isIntegerConstantExpr(Enumerator->getASTContext());
81 const EnumConstantDecl *ECD,
82 const SourceManager &SM,
83 const LangOptions &LangOpts) {
84 const SourceRange InitExprRange = ECD->getInitExpr()->getSourceRange();
85 if (InitExprRange.isInvalid() || InitExprRange.getBegin().isMacroID() ||
86 InitExprRange.getEnd().isMacroID())
89 ECD->getLocation(), SM, LangOpts);
90 if (!EqualToken.has_value() ||
91 EqualToken.value().getKind() != tok::TokenKind::equal)
93 const SourceLocation EqualLoc{EqualToken->getLocation()};
94 if (EqualLoc.isInvalid() || EqualLoc.isMacroID())
96 Diag << FixItHint::CreateRemoval(EqualLoc)
97 << FixItHint::CreateRemoval(InitExprRange);
102AST_MATCHER(EnumDecl, isMacro) {
103 const SourceLocation Loc = Node.getBeginLoc();
104 return Loc.isMacroID();
107AST_MATCHER_P(EnumDecl, hasConsistentInitialValues,
bool, AllowSelfRefs) {
113AST_MATCHER_P(EnumDecl, hasZeroInitialValueForFirstEnumerator,
bool,
115 const EnumDecl::enumerator_range Enumerators = Node.enumerators();
116 if (Enumerators.empty())
118 const EnumConstantDecl *ECD = *Enumerators.begin();
130AST_MATCHER_P(EnumDecl, hasSequentialInitialValues,
bool, AllowSelfRefs) {
131 const EnumDecl::enumerator_range Enumerators = Node.enumerators();
132 if (Enumerators.empty())
134 const EnumConstantDecl *
const FirstEnumerator = *Node.enumerator_begin();
135 llvm::APSInt PrevValue = FirstEnumerator->getInitVal();
138 bool AllEnumeratorsArePowersOfTwo =
true;
139 for (
const EnumConstantDecl *Enumerator : llvm::drop_begin(Enumerators)) {
142 const llvm::APSInt NewValue = Enumerator->getInitVal();
143 if (NewValue != ++PrevValue)
147 PrevValue = NewValue;
148 AllEnumeratorsArePowersOfTwo &= NewValue.isPowerOf2();
150 return !AllEnumeratorsArePowersOfTwo;
155static std::string
getName(
const EnumDecl *Decl) {
156 if (!Decl->getDeclName())
159 return Decl->getQualifiedNameAsString();
165 AllowExplicitZeroFirstInitialValue(
166 Options.get(
"AllowExplicitZeroFirstInitialValue", true)),
167 AllowExplicitSequentialInitialValues(
168 Options.get(
"AllowExplicitSequentialInitialValues", true)),
169 AllowReferencedInitialValues(
170 Options.get(
"AllowReferencedInitialValues", false)) {}
173 Options.store(Opts,
"AllowExplicitZeroFirstInitialValue",
174 AllowExplicitZeroFirstInitialValue);
175 Options.store(Opts,
"AllowExplicitSequentialInitialValues",
176 AllowExplicitSequentialInitialValues);
177 Options.store(Opts,
"AllowReferencedInitialValues",
178 AllowReferencedInitialValues);
182 const bool AllowSelfRefs = AllowReferencedInitialValues;
183 Finder->addMatcher(enumDecl(isDefinition(), unless(isMacro()),
184 unless(hasConsistentInitialValues(AllowSelfRefs)))
185 .bind(
"inconsistent"),
187 if (!AllowExplicitZeroFirstInitialValue)
189 enumDecl(isDefinition(),
190 hasZeroInitialValueForFirstEnumerator(AllowSelfRefs))
193 if (!AllowExplicitSequentialInitialValues)
194 Finder->addMatcher(enumDecl(isDefinition(), unless(isMacro()),
195 hasSequentialInitialValues(AllowSelfRefs))
201 if (
const auto *Enum = Result.Nodes.getNodeAs<EnumDecl>(
"inconsistent")) {
205 const DiagnosticBuilder Diag =
206 diag(Enum->getBeginLoc(),
"initial values in enum '%0' are not "
207 "consistent, consider explicit "
208 "initialization of all, none or only the "
212 for (
const EnumConstantDecl *ECD : Enum->enumerators()) {
213 if (ECD->getInitExpr() ==
nullptr) {
214 const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
215 ECD->getLocation(), 0, *Result.SourceManager, getLangOpts());
216 if (EndLoc.isMacroID())
218 SmallString<8> Str{
" = "};
219 ECD->getInitVal().toString(Str);
220 Diag << FixItHint::CreateInsertion(EndLoc, Str);
225 for (
const EnumConstantDecl *ECD : Enum->enumerators()) {
226 if (ECD->getInitExpr() ==
nullptr) {
227 diag(ECD->getLocation(),
"uninitialized enumerator '%0' defined here",
235 if (
const auto *Enum = Result.Nodes.getNodeAs<EnumDecl>(
"zero_first")) {
236 const EnumConstantDecl *ECD = *Enum->enumerator_begin();
237 const SourceLocation Loc = ECD->getLocation();
238 if (Loc.isInvalid() || Loc.isMacroID())
240 const DiagnosticBuilder Diag =
241 diag(Loc,
"zero initial value for the first "
242 "enumerator in '%0' can be disregarded")
247 if (
const auto *Enum = Result.Nodes.getNodeAs<EnumDecl>(
"sequential")) {
248 const DiagnosticBuilder Diag =
249 diag(Enum->getBeginLoc(),
250 "sequential initial value in '%0' can be ignored")
256 const EnumConstantDecl *PrevECD =
nullptr;
257 for (
const EnumConstantDecl *ECD : Enum->enumerators()) {
258 if (PrevECD !=
nullptr &&
260 llvm::APSInt Expected = PrevECD->getInitVal();
262 if (llvm::APSInt::isSameValue(Expected, ECD->getInitVal()))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
EnumInitialValueCheck(StringRef Name, ClangTidyContext *Context)
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
static void cleanInitialValue(const DiagnosticBuilder &Diag, const EnumConstantDecl *ECD, const SourceManager &SM, const LangOptions &LangOpts)
static bool isInitializedByLiteral(const EnumConstantDecl *Enumerator)
Check if Enumerator is initialized with a (potentially negated) IntegerLiteral.
static std::string getName(const EnumDecl *Decl)
static bool areAllEnumeratorsInitialized(const EnumDecl &Node)
static bool isNoneEnumeratorsInitialized(const EnumDecl &Node, bool AllowSelfRefs)
static bool isOnlyFirstEnumeratorInitialized(const EnumDecl &Node, bool AllowSelfRefs)
static bool isAllowedSelfReference(const EnumConstantDecl *ECD, bool AllowSelfRefs)
static bool isSelfReference(const EnumConstantDecl *ECD)
Check if ECD is initialized by referencing another enumerator in the same enum (e....
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
llvm::StringMap< ClangTidyValue > OptionMap