13#include "clang/AST/ASTContext.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15#include "clang/Lex/Preprocessor.h"
16#include "llvm/ADT/STLExtras.h"
29 const std::string Buffer{Text};
30 Lexer Lex(Loc, Options, Buffer.c_str(), Buffer.c_str(),
31 Buffer.c_str() + Buffer.size());
33 bool SeenHash =
false;
34 while (!Lex.LexFromRawLexer(Tok)) {
35 if (Tok.getKind() == tok::hash && !SeenHash) {
44 enum class WhiteSpace {
52 WhiteSpace State = WhiteSpace::Nothing;
53 for (
const char C : Text) {
56 if (State == WhiteSpace::CR)
59 State = State == WhiteSpace::CRLF ? WhiteSpace::CRLFCR : WhiteSpace::CR;
63 if (State == WhiteSpace::LF || State == WhiteSpace::CRLFCR)
66 State = State == WhiteSpace::CR ? WhiteSpace::CRLF : WhiteSpace::LF;
70 State = WhiteSpace::Nothing;
81 EnumMacro(Token Name,
const MacroDirective *Directive)
82 : Name(Name), Directive(Directive) {}
85 const MacroDirective *Directive;
90enum class IncludeGuard { None, FileChanged, IfGuard, DefineGuard };
93 FileState() =
default;
95 int ConditionScopes = 0;
96 unsigned int LastLine = 0;
97 IncludeGuard GuardScanner = IncludeGuard::None;
98 SourceLocation LastMacroLocation;
106 const SourceManager &SM)
107 : Check(Check), LangOpts(LangOptions), SM(SM) {}
109 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
110 SrcMgr::CharacteristicKind FileType,
111 FileID PrevFID)
override;
114 StringRef FileName,
bool IsAngled,
115 CharSourceRange FilenameRange,
116 OptionalFileEntryRef File, StringRef SearchPath,
117 StringRef RelativePath,
const Module *SuggestedModule,
119 SrcMgr::CharacteristicKind FileType)
override {
120 clearCurrentEnum(HashLoc);
125 const MacroDirective *
MD)
override;
129 const MacroDirective *Undef)
override;
138 void If(SourceLocation Loc, SourceRange ConditionRange,
139 ConditionValueKind ConditionValue)
override {
141 checkCondition(ConditionRange);
143 void Ifndef(SourceLocation Loc,
const Token &MacroNameTok,
144 const MacroDefinition &
MD)
override {
146 checkName(MacroNameTok);
148 void Ifdef(SourceLocation Loc,
const Token &MacroNameTok,
149 const MacroDefinition &
MD)
override {
151 checkName(MacroNameTok);
153 void Elif(SourceLocation Loc, SourceRange ConditionRange,
154 ConditionValueKind ConditionValue, SourceLocation IfLoc)
override {
155 checkCondition(ConditionRange);
157 void Elifdef(SourceLocation Loc,
const Token &MacroNameTok,
158 const MacroDefinition &
MD)
override {
159 checkName(MacroNameTok);
161 void Elifdef(SourceLocation Loc, SourceRange ConditionRange,
162 SourceLocation IfLoc)
override {
163 PPCallbacks::Elifdef(Loc, ConditionRange, IfLoc);
165 void Elifndef(SourceLocation Loc,
const Token &MacroNameTok,
166 const MacroDefinition &
MD)
override {
167 checkName(MacroNameTok);
169 void Elifndef(SourceLocation Loc, SourceRange ConditionRange,
170 SourceLocation IfLoc)
override {
171 PPCallbacks::Elifndef(Loc, ConditionRange, IfLoc);
173 void Endif(SourceLocation Loc, SourceLocation IfLoc)
override;
175 PragmaIntroducerKind Introducer)
override;
184 if (Enums.empty() || !Enums.back().empty())
185 Enums.emplace_back();
187 bool insideConditional()
const {
188 return (CurrentFile->GuardScanner == IncludeGuard::DefineGuard &&
189 CurrentFile->ConditionScopes > 1) ||
190 (CurrentFile->GuardScanner != IncludeGuard::DefineGuard &&
191 CurrentFile->ConditionScopes > 0);
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);
199 void clearLastMacroLocation() {
200 CurrentFile->LastLine = 0;
201 CurrentFile->LastMacroLocation = SourceLocation{};
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);
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;
224bool MacroToEnumCallbacks::isConsecutiveMacro(
const MacroDirective *
MD)
const {
225 if (CurrentFile->LastMacroLocation.isInvalid())
228 const SourceLocation Loc =
MD->getLocation();
229 if (CurrentFile->LastLine + 1 == SM.getSpellingLineNumber(Loc))
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);
242void MacroToEnumCallbacks::clearCurrentEnum(SourceLocation Loc) {
244 if (!Enums.empty() && !Enums.back().empty() &&
245 SM.getSpellingLineNumber(Loc) == CurrentFile->LastLine + 1)
248 clearLastMacroLocation();
251void MacroToEnumCallbacks::conditionStart(
const SourceLocation &Loc) {
252 ++CurrentFile->ConditionScopes;
253 clearCurrentEnum(Loc);
254 if (CurrentFile->GuardScanner == IncludeGuard::FileChanged)
255 CurrentFile->GuardScanner = IncludeGuard::IfGuard;
258void MacroToEnumCallbacks::checkCondition(SourceRange Range) {
260 CharSourceRange::getTokenRange(Range), SM, LangOpts)) {
261 if (Tok.is(tok::raw_identifier) &&
getTokenName(Tok) !=
"defined")
266void MacroToEnumCallbacks::checkName(
const Token &MacroNameTok) {
267 rememberExpressionName(MacroNameTok);
270 llvm::erase_if(Enums, [&Id](
const MacroList &MacroList) {
271 return llvm::any_of(MacroList, [&Id](
const EnumMacro &Macro) {
277void MacroToEnumCallbacks::rememberExpressionName(
const Token &Tok) {
279 const auto Pos = llvm::lower_bound(ExpressionNames, Id);
280 if (Pos == ExpressionNames.end() || *Pos != Id)
281 ExpressionNames.insert(Pos, Id);
284void MacroToEnumCallbacks::rememberExpressionTokens(
285 ArrayRef<Token> MacroTokens) {
286 for (
const Token Tok : MacroTokens)
287 if (Tok.isAnyIdentifier())
288 rememberExpressionName(Tok);
292 FileChangeReason Reason,
293 SrcMgr::CharacteristicKind FileType,
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);
304 CurrentFile = &Files.back();
307bool MacroToEnumCallbacks::isInitializer(ArrayRef<Token> MacroTokens) {
309 const bool Matched = Matcher.match();
310 const bool IsC = !LangOpts.CPlusPlus;
321 const MacroDirective *
MD) {
323 if (CurrentFile->GuardScanner == IncludeGuard::IfGuard) {
324 CurrentFile->GuardScanner = IncludeGuard::DefineGuard;
328 if (insideConditional())
331 if (SM.getFilename(
MD->getLocation()).empty())
334 const MacroInfo *Info =
MD->getMacroInfo();
335 const ArrayRef<Token> MacroTokens = Info->tokens();
336 if (Info->isBuiltinMacro() || MacroTokens.empty())
338 if (Info->isFunctionLike()) {
339 rememberExpressionTokens(MacroTokens);
343 if (!isInitializer(MacroTokens))
346 if (!isConsecutiveMacro(
MD))
348 Enums.back().emplace_back(MacroNameTok,
MD);
349 rememberLastMacroLocation(
MD);
355 const MacroDefinition &
MD,
356 const MacroDirective *Undef) {
357 rememberExpressionName(MacroNameTok);
359 const auto MatchesToken = [&MacroNameTok](
const EnumMacro &Macro) {
364 llvm::find_if(Enums, [MatchesToken](
const MacroList &MacroList) {
365 return llvm::any_of(MacroList, MatchesToken);
367 if (It != Enums.end())
370 clearLastMacroLocation();
371 CurrentFile->GuardScanner = IncludeGuard::None;
377 if (CurrentFile->ConditionScopes == 0 &&
378 CurrentFile->GuardScanner == IncludeGuard::DefineGuard)
383 assert(CurrentFile->ConditionScopes > 0);
384 --CurrentFile->ConditionScopes;
388static bool textEquals(
const char (&Needle)[N],
const char *HayStack) {
389 return StringRef{HayStack, N - 1} == Needle;
392template <
size_t N>
static size_t len(
const char (&)[N]) {
return N - 1; }
395 PragmaIntroducerKind Introducer) {
396 if (CurrentFile->GuardScanner != IncludeGuard::FileChanged)
399 bool Invalid =
false;
400 const char *Text = SM.getCharacterData(
401 Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts), &Invalid);
405 while (*Text && std::isspace(*Text))
411 Text +=
len(
"pragma");
412 while (*Text && std::isspace(*Text))
416 CurrentFile->GuardScanner = IncludeGuard::IfGuard;
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) {
430 invalidateExpressionNames();
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();
443void MacroToEnumCallbacks::issueDiagnostics() {
444 for (
const MacroList &MacroList : Enums) {
445 if (MacroList.empty())
448 for (
const EnumMacro &Macro : MacroList)
449 warnMacroEnum(Macro);
451 fixEnumMacro(MacroList);
455void MacroToEnumCallbacks::warnMacroEnum(
const EnumMacro &Macro)
const {
456 Check->diag(Macro.Directive->getLocation(),
457 "macro '%0' defines an integral constant; prefer an enum instead")
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();
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());
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);
485 const SourceLocation NameEnd = Lexer::getLocForEndOfToken(
486 Macro.Directive->getMacroInfo()->getDefinitionLoc(), 0, SM, LangOpts);
487 Diagnostic << FixItHint::CreateInsertion(NameEnd,
" =");
489 const SourceLocation ValueEnd = Lexer::getLocForEndOfToken(
490 Macro.Directive->getMacroInfo()->getDefinitionEndLoc(), 0, SM,
492 if (I < MacroList.size() - 1)
493 Diagnostic << FixItHint::CreateInsertion(ValueEnd,
",");
496 SourceLocation End = Lexer::getLocForEndOfToken(
497 MacroList.back().Directive->getMacroInfo()->getDefinitionEndLoc(), 0, SM,
499 End = SM.translateLineCol(SM.getFileID(End),
500 SM.getSpellingLineNumber(End) + 1, 1);
501 Diagnostic << FixItHint::CreateInsertion(
502 End, (llvm::Twine(
"};") + LineEnding).str());
507 Preprocessor *ModuleExpanderPP) {
509 std::make_unique<MacroToEnumCallbacks>(
this, getLangOpts(), SM);
510 PPCallback = Callback.get();
511 PP->addPPCallbacks(std::move(Callback));
516 const auto TopLevelDecl = hasParent(translationUnitDecl());
517 Finder->addMatcher(decl(TopLevelDecl).bind(
"top"),
this);
521 return Range.getBegin().isValid() && Range.getEnd().isValid();
524static bool empty(SourceRange Range) {
525 return Range.getBegin() == Range.getEnd();
529 const ast_matchers::MatchFinder::MatchResult &Result) {
530 auto *TLDecl = Result.Nodes.getNodeAs<Decl>(
"top");
531 if (TLDecl ==
nullptr)
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()};
542 PPCallback->invalidateRange(Range);
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 invalidateRange(SourceRange Range)
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 EndOfMainFile() 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.