clang-tools 24.0.0git
MacroToEnumCheck.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
9#include "MacroToEnumCheck.h"
10#include "../utils/LexerUtils.h"
12
13#include "clang/AST/ASTContext.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15#include "clang/Lex/Preprocessor.h"
16#include "llvm/ADT/STLExtras.h"
17#include <cassert>
18#include <cctype>
19#include <string>
20
21namespace clang::tidy::modernize {
22
24
25static bool hasOnlyComments(SourceLocation Loc, const LangOptions &Options,
26 StringRef Text) {
27 // Use a lexer to look for tokens; if we find something other than a single
28 // hash, then there were intervening tokens between macro definitions.
29 const std::string Buffer{Text};
30 Lexer Lex(Loc, Options, Buffer.c_str(), Buffer.c_str(),
31 Buffer.c_str() + Buffer.size());
32 Token Tok;
33 bool SeenHash = false;
34 while (!Lex.LexFromRawLexer(Tok)) {
35 if (Tok.getKind() == tok::hash && !SeenHash) {
36 SeenHash = true;
37 continue;
38 }
39 return false;
40 }
41
42 // Everything in between was whitespace, so now just look for two blank lines,
43 // consisting of two consecutive EOL sequences, either '\n', '\r' or '\r\n'.
44 enum class WhiteSpace {
45 Nothing,
46 CR,
47 LF,
48 CRLF,
49 CRLFCR,
50 };
51
52 WhiteSpace State = WhiteSpace::Nothing;
53 for (const char C : Text) {
54 switch (C) {
55 case '\r':
56 if (State == WhiteSpace::CR)
57 return false;
58
59 State = State == WhiteSpace::CRLF ? WhiteSpace::CRLFCR : WhiteSpace::CR;
60 break;
61
62 case '\n':
63 if (State == WhiteSpace::LF || State == WhiteSpace::CRLFCR)
64 return false;
65
66 State = State == WhiteSpace::CR ? WhiteSpace::CRLF : WhiteSpace::LF;
67 break;
68
69 default:
70 State = WhiteSpace::Nothing;
71 break;
72 }
73 }
74
75 return true;
76}
77
78namespace {
79
80struct EnumMacro {
81 EnumMacro(Token Name, const MacroDirective *Directive)
82 : Name(Name), Directive(Directive) {}
83
84 Token Name;
85 const MacroDirective *Directive;
86};
87
88using MacroList = SmallVector<EnumMacro>;
89
90enum class IncludeGuard { None, FileChanged, IfGuard, DefineGuard };
91
92struct FileState {
93 FileState() = default;
94
95 int ConditionScopes = 0;
96 unsigned int LastLine = 0;
97 IncludeGuard GuardScanner = IncludeGuard::None;
98 SourceLocation LastMacroLocation;
99};
100
101} // namespace
102
103class MacroToEnumCallbacks : public PPCallbacks {
104public:
105 MacroToEnumCallbacks(MacroToEnumCheck *Check, const LangOptions &LangOptions,
106 const SourceManager &SM)
107 : Check(Check), LangOpts(LangOptions), SM(SM) {}
108
109 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
110 SrcMgr::CharacteristicKind FileType,
111 FileID PrevFID) override;
112
113 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
114 StringRef FileName, bool IsAngled,
115 CharSourceRange FilenameRange,
116 OptionalFileEntryRef File, StringRef SearchPath,
117 StringRef RelativePath, const Module *SuggestedModule,
118 bool ModuleImported,
119 SrcMgr::CharacteristicKind FileType) override {
120 clearCurrentEnum(HashLoc);
121 }
122
123 // Keep track of macro definitions that look like enums.
124 void MacroDefined(const Token &MacroNameTok,
125 const MacroDirective *MD) override;
126
127 // Undefining an enum-like macro results in the enum set being dropped.
128 void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD,
129 const MacroDirective *Undef) override;
130
131 // Conditional compilation clears any adjacent enum-like macros.
132 // Macros used in conditional expressions clear any adjacent enum-like
133 // macros.
134 // Include guards are either
135 // #if !defined(GUARD)
136 // or
137 // #ifndef GUARD
138 void If(SourceLocation Loc, SourceRange ConditionRange,
139 ConditionValueKind ConditionValue) override {
140 conditionStart(Loc);
141 checkCondition(ConditionRange);
142 }
143 void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
144 const MacroDefinition &MD) override {
145 conditionStart(Loc);
146 checkName(MacroNameTok);
147 }
148 void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
149 const MacroDefinition &MD) override {
150 conditionStart(Loc);
151 checkName(MacroNameTok);
152 }
153 void Elif(SourceLocation Loc, SourceRange ConditionRange,
154 ConditionValueKind ConditionValue, SourceLocation IfLoc) override {
155 checkCondition(ConditionRange);
156 }
157 void Elifdef(SourceLocation Loc, const Token &MacroNameTok,
158 const MacroDefinition &MD) override {
159 checkName(MacroNameTok);
160 }
161 void Elifdef(SourceLocation Loc, SourceRange ConditionRange,
162 SourceLocation IfLoc) override {
163 PPCallbacks::Elifdef(Loc, ConditionRange, IfLoc);
164 }
165 void Elifndef(SourceLocation Loc, const Token &MacroNameTok,
166 const MacroDefinition &MD) override {
167 checkName(MacroNameTok);
168 }
169 void Elifndef(SourceLocation Loc, SourceRange ConditionRange,
170 SourceLocation IfLoc) override {
171 PPCallbacks::Elifndef(Loc, ConditionRange, IfLoc);
172 }
173 void Endif(SourceLocation Loc, SourceLocation IfLoc) override;
174 void PragmaDirective(SourceLocation Loc,
175 PragmaIntroducerKind Introducer) override;
176
177 // After we've seen everything, issue warnings and fix-its.
178 void EndOfMainFile() override;
179
180 void invalidateRange(SourceRange Range);
181
182private:
183 void newEnum() {
184 if (Enums.empty() || !Enums.back().empty())
185 Enums.emplace_back();
186 }
187 bool insideConditional() const {
188 return (CurrentFile->GuardScanner == IncludeGuard::DefineGuard &&
189 CurrentFile->ConditionScopes > 1) ||
190 (CurrentFile->GuardScanner != IncludeGuard::DefineGuard &&
191 CurrentFile->ConditionScopes > 0);
192 }
193 bool isConsecutiveMacro(const MacroDirective *MD) const;
194 void rememberLastMacroLocation(const MacroDirective *MD) {
195 CurrentFile->LastLine = SM.getSpellingLineNumber(MD->getLocation());
196 CurrentFile->LastMacroLocation = Lexer::getLocForEndOfToken(
197 MD->getMacroInfo()->getDefinitionEndLoc(), 0, SM, LangOpts);
198 }
199 void clearLastMacroLocation() {
200 CurrentFile->LastLine = 0;
201 CurrentFile->LastMacroLocation = SourceLocation{};
202 }
203 void clearCurrentEnum(SourceLocation Loc);
204 void conditionStart(const SourceLocation &Loc);
205 void checkCondition(SourceRange ConditionRange);
206 void checkName(const Token &MacroNameTok);
207 void rememberExpressionName(const Token &Tok);
208 void rememberExpressionTokens(ArrayRef<Token> MacroTokens);
209 void invalidateExpressionNames();
210 void issueDiagnostics();
211 void warnMacroEnum(const EnumMacro &Macro) const;
212 void fixEnumMacro(const MacroList &MacroList) const;
213 bool isInitializer(ArrayRef<Token> MacroTokens);
214
215 MacroToEnumCheck *Check;
216 const LangOptions &LangOpts;
217 const SourceManager &SM;
218 SmallVector<MacroList> Enums;
219 SmallVector<FileState> Files;
220 std::vector<std::string> ExpressionNames;
221 FileState *CurrentFile = nullptr;
222};
223
224bool MacroToEnumCallbacks::isConsecutiveMacro(const MacroDirective *MD) const {
225 if (CurrentFile->LastMacroLocation.isInvalid())
226 return false;
227
228 const SourceLocation Loc = MD->getLocation();
229 if (CurrentFile->LastLine + 1 == SM.getSpellingLineNumber(Loc))
230 return true;
231
232 const SourceLocation Define =
233 SM.translateLineCol(SM.getFileID(Loc), SM.getSpellingLineNumber(Loc), 1);
234 const CharSourceRange BetweenMacros{
235 SourceRange{CurrentFile->LastMacroLocation, Define}, true};
236 const CharSourceRange CharRange =
237 Lexer::makeFileCharRange(BetweenMacros, SM, LangOpts);
238 const StringRef BetweenText = Lexer::getSourceText(CharRange, SM, LangOpts);
239 return hasOnlyComments(Define, LangOpts, BetweenText);
240}
241
242void MacroToEnumCallbacks::clearCurrentEnum(SourceLocation Loc) {
243 // Only drop the most recent Enum set if the directive immediately follows.
244 if (!Enums.empty() && !Enums.back().empty() &&
245 SM.getSpellingLineNumber(Loc) == CurrentFile->LastLine + 1)
246 Enums.pop_back();
247
248 clearLastMacroLocation();
249}
250
251void MacroToEnumCallbacks::conditionStart(const SourceLocation &Loc) {
252 ++CurrentFile->ConditionScopes;
253 clearCurrentEnum(Loc);
254 if (CurrentFile->GuardScanner == IncludeGuard::FileChanged)
255 CurrentFile->GuardScanner = IncludeGuard::IfGuard;
256}
257
258void MacroToEnumCallbacks::checkCondition(SourceRange Range) {
259 for (const Token &Tok : utils::lexer::getRawTokens(
260 CharSourceRange::getTokenRange(Range), SM, LangOpts)) {
261 if (Tok.is(tok::raw_identifier) && getTokenName(Tok) != "defined")
262 checkName(Tok);
263 }
264}
265
266void MacroToEnumCallbacks::checkName(const Token &MacroNameTok) {
267 rememberExpressionName(MacroNameTok);
268
269 StringRef Id = getTokenName(MacroNameTok);
270 llvm::erase_if(Enums, [&Id](const MacroList &MacroList) {
271 return llvm::any_of(MacroList, [&Id](const EnumMacro &Macro) {
272 return getTokenName(Macro.Name) == Id;
273 });
274 });
275}
276
277void MacroToEnumCallbacks::rememberExpressionName(const Token &Tok) {
278 const std::string Id = getTokenName(Tok).str();
279 const auto Pos = llvm::lower_bound(ExpressionNames, Id);
280 if (Pos == ExpressionNames.end() || *Pos != Id)
281 ExpressionNames.insert(Pos, Id);
282}
283
284void MacroToEnumCallbacks::rememberExpressionTokens(
285 ArrayRef<Token> MacroTokens) {
286 for (const Token Tok : MacroTokens)
287 if (Tok.isAnyIdentifier())
288 rememberExpressionName(Tok);
289}
290
291void MacroToEnumCallbacks::FileChanged(SourceLocation Loc,
292 FileChangeReason Reason,
293 SrcMgr::CharacteristicKind FileType,
294 FileID PrevFID) {
295 newEnum();
296 if (Reason == EnterFile) {
297 Files.emplace_back();
298 if (!SM.isInMainFile(Loc))
299 Files.back().GuardScanner = IncludeGuard::FileChanged;
300 } else if (Reason == ExitFile) {
301 assert(CurrentFile->ConditionScopes == 0);
302 Files.pop_back();
303 }
304 CurrentFile = &Files.back();
305}
306
307bool MacroToEnumCallbacks::isInitializer(ArrayRef<Token> MacroTokens) {
308 IntegralLiteralExpressionMatcher Matcher(MacroTokens, LangOpts.C99 == 0);
309 const bool Matched = Matcher.match();
310 const bool IsC = !LangOpts.CPlusPlus;
311 if (IsC && (Matcher.largestLiteralSize() != LiteralSize::Int &&
312 Matcher.largestLiteralSize() != LiteralSize::UnsignedInt))
313 return false;
314
315 return Matched;
316}
317
318// Any defined but rejected macro is scanned for identifiers that
319// are to be excluded as enums.
320void MacroToEnumCallbacks::MacroDefined(const Token &MacroNameTok,
321 const MacroDirective *MD) {
322 // Include guards are never candidates for becoming an enum.
323 if (CurrentFile->GuardScanner == IncludeGuard::IfGuard) {
324 CurrentFile->GuardScanner = IncludeGuard::DefineGuard;
325 return;
326 }
327
328 if (insideConditional())
329 return;
330
331 if (SM.getFilename(MD->getLocation()).empty())
332 return;
333
334 const MacroInfo *Info = MD->getMacroInfo();
335 const ArrayRef<Token> MacroTokens = Info->tokens();
336 if (Info->isBuiltinMacro() || MacroTokens.empty())
337 return;
338 if (Info->isFunctionLike()) {
339 rememberExpressionTokens(MacroTokens);
340 return;
341 }
342
343 if (!isInitializer(MacroTokens))
344 return;
345
346 if (!isConsecutiveMacro(MD))
347 newEnum();
348 Enums.back().emplace_back(MacroNameTok, MD);
349 rememberLastMacroLocation(MD);
350}
351
352// Any macro that is undefined removes all adjacent macros from consideration as
353// an enum and starts a new enum scan.
354void MacroToEnumCallbacks::MacroUndefined(const Token &MacroNameTok,
355 const MacroDefinition &MD,
356 const MacroDirective *Undef) {
357 rememberExpressionName(MacroNameTok);
358
359 const auto MatchesToken = [&MacroNameTok](const EnumMacro &Macro) {
360 return getTokenName(Macro.Name) == getTokenName(MacroNameTok);
361 };
362
363 const auto *It =
364 llvm::find_if(Enums, [MatchesToken](const MacroList &MacroList) {
365 return llvm::any_of(MacroList, MatchesToken);
366 });
367 if (It != Enums.end())
368 Enums.erase(It);
369
370 clearLastMacroLocation();
371 CurrentFile->GuardScanner = IncludeGuard::None;
372}
373
374void MacroToEnumCallbacks::Endif(SourceLocation Loc, SourceLocation IfLoc) {
375 // The if directive for the include guard isn't counted in the
376 // ConditionScopes.
377 if (CurrentFile->ConditionScopes == 0 &&
378 CurrentFile->GuardScanner == IncludeGuard::DefineGuard)
379 return;
380
381 // We don't need to clear the current enum because the start of the
382 // conditional block already took care of that.
383 assert(CurrentFile->ConditionScopes > 0);
384 --CurrentFile->ConditionScopes;
385}
386
387template <size_t N>
388static bool textEquals(const char (&Needle)[N], const char *HayStack) {
389 return StringRef{HayStack, N - 1} == Needle;
390}
391
392template <size_t N> static size_t len(const char (&)[N]) { return N - 1; }
393
395 PragmaIntroducerKind Introducer) {
396 if (CurrentFile->GuardScanner != IncludeGuard::FileChanged)
397 return;
398
399 bool Invalid = false;
400 const char *Text = SM.getCharacterData(
401 Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts), &Invalid);
402 if (Invalid)
403 return;
404
405 while (*Text && std::isspace(*Text))
406 ++Text;
407
408 if (textEquals("pragma", Text))
409 return;
410
411 Text += len("pragma");
412 while (*Text && std::isspace(*Text))
413 ++Text;
414
415 if (textEquals("once", Text))
416 CurrentFile->GuardScanner = IncludeGuard::IfGuard;
417}
418
419void MacroToEnumCallbacks::invalidateExpressionNames() {
420 for (const std::string &Id : ExpressionNames) {
421 llvm::erase_if(Enums, [Id](const MacroList &MacroList) {
422 return llvm::any_of(MacroList, [&Id](const EnumMacro &Macro) {
423 return getTokenName(Macro.Name) == Id;
424 });
425 });
426 }
427}
428
430 invalidateExpressionNames();
431 issueDiagnostics();
432}
433
435 llvm::erase_if(Enums, [Range](const MacroList &MacroList) {
436 return llvm::any_of(MacroList, [Range](const EnumMacro &Macro) {
437 return Macro.Directive->getLocation() >= Range.getBegin() &&
438 Macro.Directive->getLocation() <= Range.getEnd();
439 });
440 });
441}
442
443void MacroToEnumCallbacks::issueDiagnostics() {
444 for (const MacroList &MacroList : Enums) {
445 if (MacroList.empty())
446 continue;
447
448 for (const EnumMacro &Macro : MacroList)
449 warnMacroEnum(Macro);
450
451 fixEnumMacro(MacroList);
452 }
453}
454
455void MacroToEnumCallbacks::warnMacroEnum(const EnumMacro &Macro) const {
456 Check->diag(Macro.Directive->getLocation(),
457 "macro '%0' defines an integral constant; prefer an enum instead")
458 << getTokenName(Macro.Name);
459}
460
461void MacroToEnumCallbacks::fixEnumMacro(const MacroList &MacroList) const {
462 SourceLocation Begin =
463 MacroList.front().Directive->getMacroInfo()->getDefinitionLoc();
464 const StringRef LineEnding =
465 SM.getBufferData(SM.getFileID(Begin)).detectEOL();
466
467 Begin = SM.translateLineCol(SM.getFileID(Begin),
468 SM.getSpellingLineNumber(Begin), 1);
469 const DiagnosticBuilder Diagnostic =
470 Check->diag(Begin, "replace macro with enum")
471 << FixItHint::CreateInsertion(Begin,
472 (llvm::Twine("enum {") + LineEnding).str());
473
474 for (size_t I = 0U; I < MacroList.size(); ++I) {
475 const EnumMacro &Macro = MacroList[I];
476 const SourceLocation DefineEnd =
477 Macro.Directive->getMacroInfo()->getDefinitionLoc();
478 const SourceLocation DefineBegin = SM.translateLineCol(
479 SM.getFileID(DefineEnd), SM.getSpellingLineNumber(DefineEnd), 1);
480 CharSourceRange DefineRange;
481 DefineRange.setBegin(DefineBegin);
482 DefineRange.setEnd(DefineEnd);
483 Diagnostic << FixItHint::CreateRemoval(DefineRange);
484
485 const SourceLocation NameEnd = Lexer::getLocForEndOfToken(
486 Macro.Directive->getMacroInfo()->getDefinitionLoc(), 0, SM, LangOpts);
487 Diagnostic << FixItHint::CreateInsertion(NameEnd, " =");
488
489 const SourceLocation ValueEnd = Lexer::getLocForEndOfToken(
490 Macro.Directive->getMacroInfo()->getDefinitionEndLoc(), 0, SM,
491 LangOpts);
492 if (I < MacroList.size() - 1)
493 Diagnostic << FixItHint::CreateInsertion(ValueEnd, ",");
494 }
495
496 SourceLocation End = Lexer::getLocForEndOfToken(
497 MacroList.back().Directive->getMacroInfo()->getDefinitionEndLoc(), 0, SM,
498 LangOpts);
499 End = SM.translateLineCol(SM.getFileID(End),
500 SM.getSpellingLineNumber(End) + 1, 1);
501 Diagnostic << FixItHint::CreateInsertion(
502 End, (llvm::Twine("};") + LineEnding).str());
503}
504
505void MacroToEnumCheck::registerPPCallbacks(const SourceManager &SM,
506 Preprocessor *PP,
507 Preprocessor *ModuleExpanderPP) {
508 auto Callback =
509 std::make_unique<MacroToEnumCallbacks>(this, getLangOpts(), SM);
510 PPCallback = Callback.get();
511 PP->addPPCallbacks(std::move(Callback));
512}
513
514void MacroToEnumCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
515 using namespace ast_matchers;
516 const auto TopLevelDecl = hasParent(translationUnitDecl());
517 Finder->addMatcher(decl(TopLevelDecl).bind("top"), this);
518}
519
520static bool isValid(SourceRange Range) {
521 return Range.getBegin().isValid() && Range.getEnd().isValid();
522}
523
524static bool empty(SourceRange Range) {
525 return Range.getBegin() == Range.getEnd();
526}
527
529 const ast_matchers::MatchFinder::MatchResult &Result) {
530 auto *TLDecl = Result.Nodes.getNodeAs<Decl>("top");
531 if (TLDecl == nullptr)
532 return;
533
534 SourceRange Range = TLDecl->getSourceRange();
535 if (auto *TemplateFn = Result.Nodes.getNodeAs<FunctionTemplateDecl>("top");
536 TemplateFn && TemplateFn->isThisDeclarationADefinition() &&
537 TemplateFn->hasBody())
538 Range = SourceRange{TemplateFn->getBeginLoc(),
539 TemplateFn->getUnderlyingDecl()->getBodyRBrace()};
540
541 if (isValid(Range) && !empty(Range))
542 PPCallback->invalidateRange(Range);
543}
544
545} // namespace clang::tidy::modernize
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for Markdown output.")
void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD) override
void PragmaDirective(SourceLocation Loc, PragmaIntroducerKind Introducer) override
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, CharSourceRange FilenameRange, OptionalFileEntryRef File, StringRef SearchPath, StringRef RelativePath, const Module *SuggestedModule, bool ModuleImported, SrcMgr::CharacteristicKind FileType) override
MacroToEnumCallbacks(MacroToEnumCheck *Check, const LangOptions &LangOptions, const SourceManager &SM)
void Elifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override
void If(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue) override
void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue, SourceLocation IfLoc) override
void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD, const MacroDirective *Undef) override
void Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override
void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override
void Elifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override
void Endif(SourceLocation Loc, SourceLocation IfLoc) override
void Elifdef(SourceLocation Loc, SourceRange ConditionRange, SourceLocation IfLoc) override
void Elifndef(SourceLocation Loc, SourceRange ConditionRange, SourceLocation IfLoc) override
void Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override
Replaces groups of related macros with an unscoped anonymous enum.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static bool empty(SourceRange Range)
static bool hasOnlyComments(SourceLocation Loc, const LangOptions &Options, StringRef Text)
static bool isValid(SourceRange Range)
StringRef getTokenName(const Token &Tok)
Returns the spelling of an identifier token.
static bool textEquals(const char(&Needle)[N], const char *HayStack)
static size_t len(const char(&)[N])
std::vector< Token > getRawTokens(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Returns the raw tokens in Range.
StringRef getTokenName(const Token &Tok)
Returns the spelling of an identifier token.