clang-tools 24.0.0git
EnumInitialValueCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "../utils/LexerUtils.h"
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"
18
19using namespace clang::ast_matchers;
20
22
23/// Check if \p ECD is initialized by referencing another enumerator in the
24/// same enum (e.g., `last = first`). For unscoped enums, the reference may be
25/// wrapped in an implicit conversion to the enum's underlying type.
26static bool isSelfReference(const EnumConstantDecl *ECD) {
27 const Expr *Init = ECD->getInitExpr();
28 if (!Init)
29 return false;
30
31 const auto *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParenImpCasts());
32 const auto *RefECD =
33 dyn_cast_if_present<EnumConstantDecl>(DRE ? DRE->getDecl() : nullptr);
34 return RefECD && RefECD->getDeclContext() == ECD->getDeclContext();
35}
36
37static bool isAllowedSelfReference(const EnumConstantDecl *ECD,
38 bool AllowSelfRefs) {
39 return AllowSelfRefs && isSelfReference(ECD);
40}
41
42static bool isNoneEnumeratorsInitialized(const EnumDecl &Node,
43 bool AllowSelfRefs) {
44 return llvm::all_of(Node.enumerators(),
45 [AllowSelfRefs](const EnumConstantDecl *ECD) {
46 return isAllowedSelfReference(ECD, AllowSelfRefs) ||
47 ECD->getInitExpr() == nullptr;
48 });
49}
50
51static bool isOnlyFirstEnumeratorInitialized(const EnumDecl &Node,
52 bool AllowSelfRefs) {
53 bool IsFirst = true;
54 for (const EnumConstantDecl *ECD : Node.enumerators()) {
55 if (isAllowedSelfReference(ECD, AllowSelfRefs))
56 continue;
57 if ((IsFirst && ECD->getInitExpr() == nullptr) ||
58 (!IsFirst && ECD->getInitExpr() != nullptr))
59 return false;
60 IsFirst = false;
61 }
62 return !IsFirst;
63}
64
65static bool areAllEnumeratorsInitialized(const EnumDecl &Node) {
66 return llvm::all_of(Node.enumerators(), [](const EnumConstantDecl *ECD) {
67 return ECD->getInitExpr() != nullptr;
68 });
69}
70
71/// Check if \p Enumerator is initialized with a (potentially negated) \c
72/// IntegerLiteral.
73static bool isInitializedByLiteral(const EnumConstantDecl *Enumerator) {
74 const Expr *const Init = Enumerator->getInitExpr();
75 if (!Init)
76 return false;
77 return Init->isIntegerConstantExpr(Enumerator->getASTContext());
78}
79
80static void cleanInitialValue(const DiagnosticBuilder &Diag,
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())
87 return;
88 std::optional<Token> EqualToken = utils::lexer::findNextTokenSkippingComments(
89 ECD->getLocation(), SM, LangOpts);
90 if (!EqualToken.has_value() ||
91 EqualToken.value().getKind() != tok::TokenKind::equal)
92 return;
93 const SourceLocation EqualLoc{EqualToken->getLocation()};
94 if (EqualLoc.isInvalid() || EqualLoc.isMacroID())
95 return;
96 Diag << FixItHint::CreateRemoval(EqualLoc)
97 << FixItHint::CreateRemoval(InitExprRange);
98}
99
100namespace {
101
102AST_MATCHER(EnumDecl, isMacro) {
103 const SourceLocation Loc = Node.getBeginLoc();
104 return Loc.isMacroID();
105}
106
107AST_MATCHER_P(EnumDecl, hasConsistentInitialValues, bool, AllowSelfRefs) {
108 return isNoneEnumeratorsInitialized(Node, AllowSelfRefs) ||
109 isOnlyFirstEnumeratorInitialized(Node, AllowSelfRefs) ||
111}
112
113AST_MATCHER_P(EnumDecl, hasZeroInitialValueForFirstEnumerator, bool,
114 AllowSelfRefs) {
115 const EnumDecl::enumerator_range Enumerators = Node.enumerators();
116 if (Enumerators.empty())
117 return false;
118 const EnumConstantDecl *ECD = *Enumerators.begin();
119 return isOnlyFirstEnumeratorInitialized(Node, AllowSelfRefs) &&
120 isInitializedByLiteral(ECD) && ECD->getInitVal().isZero();
121}
122
123/// Excludes bitfields because enumerators initialized with the result of a
124/// bitwise operator on enumeration values or any other expr that is not a
125/// potentially negative integer literal.
126/// Enumerations where it is not directly clear if they are used with
127/// bitmask, evident when enumerators are only initialized with (potentially
128/// negative) integer literals, are ignored. This is also the case when all
129/// enumerators are powers of two (e.g., 0, 1, 2).
130AST_MATCHER_P(EnumDecl, hasSequentialInitialValues, bool, AllowSelfRefs) {
131 const EnumDecl::enumerator_range Enumerators = Node.enumerators();
132 if (Enumerators.empty())
133 return false;
134 const EnumConstantDecl *const FirstEnumerator = *Node.enumerator_begin();
135 llvm::APSInt PrevValue = FirstEnumerator->getInitVal();
136 if (!isInitializedByLiteral(FirstEnumerator))
137 return false;
138 bool AllEnumeratorsArePowersOfTwo = true;
139 for (const EnumConstantDecl *Enumerator : llvm::drop_begin(Enumerators)) {
140 if (isAllowedSelfReference(Enumerator, AllowSelfRefs))
141 continue;
142 const llvm::APSInt NewValue = Enumerator->getInitVal();
143 if (NewValue != ++PrevValue)
144 return false;
145 if (!isInitializedByLiteral(Enumerator))
146 return false;
147 PrevValue = NewValue;
148 AllEnumeratorsArePowersOfTwo &= NewValue.isPowerOf2();
149 }
150 return !AllEnumeratorsArePowersOfTwo;
151}
152
153} // namespace
154
155static std::string getName(const EnumDecl *Decl) {
156 if (!Decl->getDeclName())
157 return "<unnamed>";
158
159 return Decl->getQualifiedNameAsString();
160}
161
163 ClangTidyContext *Context)
164 : ClangTidyCheck(Name, Context),
165 AllowExplicitZeroFirstInitialValue(
166 Options.get("AllowExplicitZeroFirstInitialValue", true)),
167 AllowExplicitSequentialInitialValues(
168 Options.get("AllowExplicitSequentialInitialValues", true)),
169 AllowReferencedInitialValues(
170 Options.get("AllowReferencedInitialValues", false)) {}
171
173 Options.store(Opts, "AllowExplicitZeroFirstInitialValue",
174 AllowExplicitZeroFirstInitialValue);
175 Options.store(Opts, "AllowExplicitSequentialInitialValues",
176 AllowExplicitSequentialInitialValues);
177 Options.store(Opts, "AllowReferencedInitialValues",
178 AllowReferencedInitialValues);
179}
180
182 const bool AllowSelfRefs = AllowReferencedInitialValues;
183 Finder->addMatcher(enumDecl(isDefinition(), unless(isMacro()),
184 unless(hasConsistentInitialValues(AllowSelfRefs)))
185 .bind("inconsistent"),
186 this);
187 if (!AllowExplicitZeroFirstInitialValue)
188 Finder->addMatcher(
189 enumDecl(isDefinition(),
190 hasZeroInitialValueForFirstEnumerator(AllowSelfRefs))
191 .bind("zero_first"),
192 this);
193 if (!AllowExplicitSequentialInitialValues)
194 Finder->addMatcher(enumDecl(isDefinition(), unless(isMacro()),
195 hasSequentialInitialValues(AllowSelfRefs))
196 .bind("sequential"),
197 this);
198}
199
200void EnumInitialValueCheck::check(const MatchFinder::MatchResult &Result) {
201 if (const auto *Enum = Result.Nodes.getNodeAs<EnumDecl>("inconsistent")) {
202 // Emit warning first (DiagnosticBuilder emits on destruction), then notes.
203 // Notes must follow the primary diagnostic or they may be dropped.
204 {
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 "
209 "first enumerator")
210 << getName(Enum);
211
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())
217 continue;
218 SmallString<8> Str{" = "};
219 ECD->getInitVal().toString(Str);
220 Diag << FixItHint::CreateInsertion(EndLoc, Str);
221 }
222 }
223 }
224
225 for (const EnumConstantDecl *ECD : Enum->enumerators()) {
226 if (ECD->getInitExpr() == nullptr) {
227 diag(ECD->getLocation(), "uninitialized enumerator '%0' defined here",
228 DiagnosticIDs::Note)
229 << ECD->getName();
230 }
231 }
232 return;
233 }
234
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())
239 return;
240 const DiagnosticBuilder Diag =
241 diag(Loc, "zero initial value for the first "
242 "enumerator in '%0' can be disregarded")
243 << getName(Enum);
244 cleanInitialValue(Diag, ECD, *Result.SourceManager, getLangOpts());
245 return;
246 }
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")
251 << getName(Enum);
252 // Only remove the explicit value of an enumerator when the preceding
253 // declared enumerator equals `current - 1`, so the implicit value stays
254 // the same. An interleaved self-reference can break this, in which case
255 // the value must be kept.
256 const EnumConstantDecl *PrevECD = nullptr;
257 for (const EnumConstantDecl *ECD : Enum->enumerators()) {
258 if (PrevECD != nullptr &&
259 !isAllowedSelfReference(ECD, AllowReferencedInitialValues)) {
260 llvm::APSInt Expected = PrevECD->getInitVal();
261 ++Expected;
262 if (llvm::APSInt::isSameValue(Expected, ECD->getInitVal()))
263 cleanInitialValue(Diag, ECD, *Result.SourceManager, getLangOpts());
264 }
265 PrevECD = ECD;
266 }
267 return;
268 }
269}
270
271} // namespace clang::tidy::readability
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)
Definition LexerUtils.h:114
llvm::StringMap< ClangTidyValue > OptionMap