https://github.com/LegalizeAdulthood updated https://github.com/llvm/llvm-project/pull/244989
>From e427a9620dbb3d86d91d1533b785b080c8497788 Mon Sep 17 00:00:00 2001 From: Richard <[email protected]> Date: Sat, 21 Nov 2026 20:22:44 -0700 Subject: [PATCH] [clang-tidy] Validate macro expansions before enum conversion Require every observed macro expansion to form a complete expression before replacing its cluster with an enum. Reject call argument lists, partial expressions, redefined names, and definitions inside declarations. Track expansions by definition identity and source location, validate nested boundaries, and avoid repeated candidate scans. Use translation- unit source order to exclude definitions inside declarations. Add C and C++ regressions for aliases, wrappers, headers, preprocessing exclusions, and repeated template instantiations. Check diagnostics, exact fixes, and resulting syntax, and document the eligibility rules. --- .../clang-tidy/modernize/MacroToEnumCheck.cpp | 323 +++++++++++++++++- .../checks/modernize/macro-to-enum.md | 33 +- .../Inputs/macro-to-enum/expansion-local.h | 8 + .../macro-to-enum/expansion-redefined.h | 8 + .../Inputs/macro-to-enum/expansion-uses.h | 22 ++ .../Inputs/macro-to-enum/linkage-local.h | 8 + .../Inputs/macro-to-enum/linkage-values.h | 21 ++ .../Inputs/macro-to-enum/linkage-wrapper.h | 10 + .../Inputs/macro-to-enum/namespace-values.h | 18 + .../macro-to-enum-expand-arguments.c | 98 ++++++ .../macro-to-enum-expand-headers.cpp | 42 +++ .../modernize/macro-to-enum-expand-nested.cpp | 98 ++++++ .../macro-to-enum-expand-redefined.c | 67 ++++ .../checkers/modernize/macro-to-enum-expand.c | 86 +++++ .../modernize/macro-to-enum-expand.cpp | 27 ++ .../modernize/macro-to-enum-linkage.cpp | 89 +++++ .../modernize/macro-to-enum-namespace.cpp | 232 +++++++++++++ .../checkers/modernize/macro-to-enum.cpp | 7 +- 18 files changed, 1186 insertions(+), 11 deletions(-) create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-local.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-redefined.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-uses.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-local.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-values.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-wrapper.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/namespace-values.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-arguments.c create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-headers.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-nested.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-redefined.c create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.c create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-linkage.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-namespace.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp index 2b5b8fe0e07e7b..cecf8d19c2df87 100644 --- a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp @@ -13,6 +13,7 @@ #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Lex/Preprocessor.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include <cassert> #include <cctype> @@ -85,6 +86,21 @@ struct EnumMacro { const MacroDirective *Directive; }; +struct MacroExpansion { + const MacroInfo *Info; + SourceLocation End; + bool Complete = true; + bool Consumed = false; +}; + +struct MacroState { + unsigned UnmatchedExpansions = 0; + const NamespaceDecl *DefinitionNamespace = nullptr; + // The innermost namespace enclosing every matched use. + const NamespaceDecl *CommonUseNamespace = nullptr; + bool HasUses = false; +}; + using MacroList = SmallVector<EnumMacro>; enum class IncludeGuard { None, FileChanged, IfGuard, DefineGuard }; @@ -174,11 +190,19 @@ class MacroToEnumCallbacks : public PPCallbacks { void PragmaDirective(SourceLocation Loc, PragmaIntroducerKind Introducer) override; + void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, + SourceRange Range, const MacroArgs *Args) override; + // After we've seen everything, issue warnings and fix-its. void EndOfMainFile() override; void invalidateRange(SourceRange Range); + void validateExpansionRange(SourceRange Range, + const NamespaceDecl *UseNamespace); + + void recordNamespace(const NamespaceDecl *Namespace); + private: void newEnum() { if (Enums.empty() || !Enums.back().empty()) @@ -207,6 +231,9 @@ class MacroToEnumCallbacks : public PPCallbacks { void rememberExpressionName(const Token &Tok); void rememberExpressionTokens(ArrayRef<Token> MacroTokens); void invalidateExpressionNames(); + void collectArgumentExpansions(); + void validateExpansion(MacroExpansion &Expansion, + const NamespaceDecl *UseNamespace); void issueDiagnostics(); void warnMacroEnum(const EnumMacro &Macro) const; void fixEnumMacro(const MacroList &MacroList) const; @@ -216,6 +243,12 @@ class MacroToEnumCallbacks : public PPCallbacks { const LangOptions &LangOpts; const SourceManager &SM; SmallVector<MacroList> Enums; + llvm::DenseMap<const MacroInfo *, MacroState> MacroStates; + llvm::DenseMap<SourceLocation, MacroExpansion> Expansions; + llvm::DenseMap<unsigned, MacroExpansion> ArgumentExpansions; + bool ArgumentExpansionsCollected = false; + SmallVector<const MacroInfo *> CandidateDefinitions; + bool DefinitionsSorted = false; SmallVector<FileState> Files; std::vector<std::string> ExpressionNames; FileState *CurrentFile = nullptr; @@ -325,6 +358,10 @@ void MacroToEnumCallbacks::MacroDefined(const Token &MacroNameTok, return; } + // An earlier definition would still expand the generated enumerator name. + if (MD->getPrevious()) + checkName(MacroNameTok); + if (insideConditional()) return; @@ -346,6 +383,9 @@ void MacroToEnumCallbacks::MacroDefined(const Token &MacroNameTok, if (!isConsecutiveMacro(MD)) newEnum(); Enums.back().emplace_back(MacroNameTok, MD); + MacroStates.try_emplace(Info); + CandidateDefinitions.push_back(Info); + DefinitionsSorted = false; rememberLastMacroLocation(MD); } @@ -416,6 +456,25 @@ void MacroToEnumCallbacks::PragmaDirective(SourceLocation Loc, CurrentFile->GuardScanner = IncludeGuard::IfGuard; } +void MacroToEnumCallbacks::MacroExpands(const Token &MacroNameTok, + const MacroDefinition &MD, + SourceRange Range, + const MacroArgs *Args) { + // Ignore function-like macro expansions. + if (Args != nullptr) + return; + + const MacroInfo *Info = MD.getMacroInfo(); + const auto Candidate = MacroStates.find(Info); + if (Candidate == MacroStates.end()) + return; + + if (Expansions + .try_emplace(Range.getBegin(), MacroExpansion{Info, Range.getEnd()}) + .second) + ++Candidate->second.UnmatchedExpansions; +} + void MacroToEnumCallbacks::invalidateExpressionNames() { for (const std::string &Id : ExpressionNames) { llvm::erase_if(Enums, [Id](const MacroList &MacroList) { @@ -426,20 +485,251 @@ void MacroToEnumCallbacks::invalidateExpressionNames() { } } +static const NamespaceDecl *getNamespaceContext(const DeclContext *Context) { + for (; Context; Context = Context->getParent()) + if (const auto *Namespace = dyn_cast<NamespaceDecl>(Context)) + return Namespace->getCanonicalDecl(); + return nullptr; +} + +static const NamespaceDecl *getEnclosingNamespace(const Decl *Declaration) { + return getNamespaceContext(Declaration->getDeclContext()); +} + +static const NamespaceDecl *getUseNamespace(const Decl *Use, + SourceLocation Location, + const SourceManager &SM) { + for (const Decl *Declaration = Use; Declaration;) { + const DeclContext *Context = Declaration->getDeclContext(); + const DeclContext *Lexical = Declaration->getLexicalDeclContext(); + if (Context != Lexical) { + // A qualified declaration's leading type is still in its lexical scope. + bool InSemanticScope = false; + if (const auto *Function = dyn_cast<FunctionDecl>(Declaration)) { + const SourceLocation NameEnd = Function->getNameInfo().getEndLoc(); + SourceLocation ScopeBegin = NameEnd; + if (const auto *Arguments = + Function->getTemplateSpecializationArgsAsWritten()) + ScopeBegin = Arguments->getRAngleLoc(); + InSemanticScope = NameEnd.isValid() && ScopeBegin.isValid() && + !SM.isBeforeInTranslationUnit(ScopeBegin, NameEnd) && + !SM.isBeforeInTranslationUnit(Location, ScopeBegin); + } else { + SourceRange ScopeRange; + if (const auto *Record = dyn_cast<RecordDecl>(Declaration)) { + ScopeRange = Record->getBraceRange(); + } else if (const auto *Variable = dyn_cast<VarDecl>(Declaration)) { + if (const Expr *Initializer = Variable->getInit()) + ScopeRange = Initializer->getSourceRange(); + } + InSemanticScope = ScopeRange.isValid() && + SM.isPointWithin(Location, ScopeRange.getBegin(), + ScopeRange.getEnd()); + } + if (!InSemanticScope) + return getNamespaceContext(Lexical); + } + Declaration = Context ? Decl::castFromDeclContext(Context) : nullptr; + } + return getEnclosingNamespace(Use); +} + +static bool isWithinNamespace(const NamespaceDecl *UseNamespace, + const NamespaceDecl *DefinitionNamespace) { + if (!DefinitionNamespace) + return true; + for (const NamespaceDecl *Namespace = UseNamespace; Namespace; + Namespace = getEnclosingNamespace(Namespace)) { + if (Namespace == DefinitionNamespace) + return true; + } + return false; +} + +static const NamespaceDecl *getCommonNamespace(const NamespaceDecl *Left, + const NamespaceDecl *Right) { + if (!Left || !Right) + return nullptr; + for (const NamespaceDecl *Namespace = Left; Namespace; + Namespace = getEnclosingNamespace(Namespace)) { + if (isWithinNamespace(Right, Namespace)) + return Namespace; + } + return nullptr; +} + +void MacroToEnumCallbacks::recordNamespace(const NamespaceDecl *Namespace) { + if (Namespace->getBeginLoc().isInvalid() || + Namespace->getEndLoc().isInvalid()) + return; + + if (!DefinitionsSorted) { + llvm::sort(CandidateDefinitions, + [this](const MacroInfo *Left, const MacroInfo *Right) { + return SM.isBeforeInTranslationUnit(Left->getDefinitionLoc(), + Right->getDefinitionLoc()); + }); + DefinitionsSorted = true; + } + + const SourceRange Range = + SM.getExpansionRange(Namespace->getSourceRange()).getAsRange(); + const auto *It = llvm::lower_bound( + CandidateDefinitions, Range.getBegin(), + [this](const MacroInfo *Info, SourceLocation Location) { + return SM.isBeforeInTranslationUnit(Info->getDefinitionLoc(), Location); + }); + const NamespaceDecl *Canonical = Namespace->getCanonicalDecl(); + for (; It != CandidateDefinitions.end() && + SM.isPointWithin((*It)->getDefinitionLoc(), Range.getBegin(), + Range.getEnd()); + ++It) { + MacroState &State = MacroStates.find(*It)->second; + // Nested namespaces can share source ranges, as in namespace A::B {}. + if (isWithinNamespace(Canonical, State.DefinitionNamespace)) + State.DefinitionNamespace = Canonical; + } +} + void MacroToEnumCallbacks::EndOfMainFile() { invalidateExpressionNames(); + llvm::erase_if(Enums, [this](const MacroList &Macros) { + return llvm::any_of(Macros, [this](const EnumMacro &Macro) { + const MacroState &State = + MacroStates.find(Macro.Directive->getMacroInfo())->second; + return State.UnmatchedExpansions != 0 || + (State.HasUses && !isWithinNamespace(State.CommonUseNamespace, + State.DefinitionNamespace)); + }); + }); issueDiagnostics(); } void MacroToEnumCallbacks::invalidateRange(SourceRange Range) { - llvm::erase_if(Enums, [Range](const MacroList &MacroList) { - return llvm::any_of(MacroList, [Range](const EnumMacro &Macro) { - return Macro.Directive->getLocation() >= Range.getBegin() && - Macro.Directive->getLocation() <= Range.getEnd(); + // A declaration can end in a macro expansion. Compare file locations so it + // does not also invalidate unrelated macros defined after the declaration. + Range = SM.getExpansionRange(Range).getAsRange(); + llvm::erase_if(Enums, [this, Range](const MacroList &MacroList) { + return llvm::any_of(MacroList, [this, Range](const EnumMacro &Macro) { + return SM.isPointWithin(Macro.Directive->getLocation(), Range.getBegin(), + Range.getEnd()); }); }); } +void MacroToEnumCallbacks::collectArgumentExpansions() { + if (ArgumentExpansionsCollected) + return; + ArgumentExpansionsCollected = true; + + // Argument prescanning expands a candidate once, but each substituted copy + // must be validated independently. Source entries are created parent first. + for (unsigned I = 1, Size = SM.local_sloc_entry_size(); I < Size; ++I) { + const auto &Entry = SM.getLocalSLocEntry(I); + if (!Entry.isExpansion() || !Entry.getExpansion().isMacroArgExpansion()) + continue; + + const SourceLocation Spelling = Entry.getExpansion().getSpellingLoc(); + if (!Spelling.isMacroID()) + continue; + + const unsigned NextOffset = I + 1 == Size + ? SM.getNextLocalOffset() + : SM.getLocalSLocEntry(I + 1).getOffset(); + const unsigned Length = NextOffset - Entry.getOffset() - 1; + const SourceLocation SpellingEnd = Spelling.getLocWithOffset(Length); + const FileID SpellingFile = SM.getFileID(Spelling); + MacroExpansion *Parent = nullptr; + bool Complete = false; + if (SM.isMacroArgExpansion(Spelling)) { + const auto Argument = + ArgumentExpansions.find(SM.getSLocEntry(SpellingFile).getOffset()); + if (Argument == ArgumentExpansions.end()) + continue; + Parent = &Argument->second; + Complete = Parent->Complete && SM.getFileOffset(Spelling) == 0 && + Length == SM.getFileIDSize(SpellingFile); + } else { + const SourceRange Range = + SM.getImmediateExpansionRange(Spelling).getAsRange(); + const auto Expansion = Expansions.find(Range.getBegin()); + if (Expansion == Expansions.end() || + Expansion->second.End != Range.getEnd()) + continue; + Parent = &Expansion->second; + Complete = SM.isAtStartOfImmediateMacroExpansion(Spelling) && + SM.isInFileID(SpellingEnd, SpellingFile) && + SM.isAtEndOfImmediateMacroExpansion(SpellingEnd); + } + + const MacroInfo *Info = Parent->Info; + MacroState &State = MacroStates.find(Info)->second; + // Forwarding replaces the parent's obligation with one for each child. + if (!Parent->Consumed) { + assert(State.UnmatchedExpansions != 0); + --State.UnmatchedExpansions; + Parent->Consumed = true; + } + ArgumentExpansions.try_emplace(Entry.getOffset(), + MacroExpansion{Info, SpellingEnd, Complete}); + ++State.UnmatchedExpansions; + } +} + +void MacroToEnumCallbacks::validateExpansion( + MacroExpansion &Expansion, const NamespaceDecl *UseNamespace) { + if (Expansion.Consumed || !Expansion.Complete) + return; + + MacroState &State = MacroStates.find(Expansion.Info)->second; + assert(State.UnmatchedExpansions != 0); + --State.UnmatchedExpansions; + State.CommonUseNamespace = + State.HasUses ? getCommonNamespace(State.CommonUseNamespace, UseNamespace) + : UseNamespace; + State.HasUses = true; + // A template instantiation can revisit this expression's source range. + Expansion.Consumed = true; +} + +void MacroToEnumCallbacks::validateExpansionRange( + SourceRange Range, const NamespaceDecl *UseNamespace) { + collectArgumentExpansions(); + SourceLocation Begin = Range.getBegin(); + SourceLocation End = Range.getEnd(); + while (Begin.isMacroID() && End.isMacroID() && + SM.getFileID(Begin) == SM.getFileID(End)) { + const unsigned Length = + Lexer::MeasureTokenLength(SM.getSpellingLoc(End), SM, LangOpts); + const SourceLocation TokenEnd = End.getLocWithOffset(Length); + if (Length == 0 || !SM.isInFileID(TokenEnd, SM.getFileID(End))) + return; + + if (SM.isMacroArgExpansion(Begin)) { + const auto Argument = ArgumentExpansions.find( + SM.getSLocEntry(SM.getFileID(Begin)).getOffset()); + if (Argument != ArgumentExpansions.end() && + SM.getFileOffset(Begin) == 0 && + SM.getImmediateSpellingLoc(TokenEnd) == Argument->second.End) + validateExpansion(Argument->second, UseNamespace); + return; + } + + // An inner expression can be complete without consuming its enclosing + // object-like macro expansion. + SourceLocation ExpansionBegin, ExpansionEnd; + if (!SM.isAtStartOfImmediateMacroExpansion(Begin, &ExpansionBegin) || + !SM.isAtEndOfImmediateMacroExpansion(TokenEnd, &ExpansionEnd)) + return; + + const auto Expansion = Expansions.find(ExpansionBegin); + if (Expansion != Expansions.end() && Expansion->second.End == ExpansionEnd) + validateExpansion(Expansion->second, UseNamespace); + Begin = ExpansionBegin; + End = ExpansionEnd; + } +} + void MacroToEnumCallbacks::issueDiagnostics() { for (const MacroList &MacroList : Enums) { if (MacroList.empty()) @@ -513,8 +803,16 @@ void MacroToEnumCheck::registerPPCallbacks(const SourceManager &SM, void MacroToEnumCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { using namespace ast_matchers; - const auto TopLevelDecl = hasParent(translationUnitDecl()); - Finder->addMatcher(decl(TopLevelDecl).bind("top"), this); + // Inspect declarations inside namespace and linkage containers. Namespace + // ownership is checked separately against each expansion's context. + const auto TopLevelDecl = hasParent( + decl(anyOf(translationUnitDecl(), linkageSpecDecl(), namespaceDecl()))); + Finder->addMatcher( + decl(TopLevelDecl, unless(anyOf(linkageSpecDecl(), namespaceDecl()))) + .bind("top"), + this); + Finder->addMatcher(namespaceDecl().bind("namespace"), this); + Finder->addMatcher(expr(hasAncestor(decl().bind("use"))).bind("expr"), this); } static bool isValid(SourceRange Range) { @@ -527,6 +825,19 @@ static bool empty(SourceRange Range) { void MacroToEnumCheck::check( const ast_matchers::MatchFinder::MatchResult &Result) { + if (const auto *Namespace = + Result.Nodes.getNodeAs<NamespaceDecl>("namespace")) + PPCallback->recordNamespace(Namespace); + + if (const auto *E = Result.Nodes.getNodeAs<Expr>("expr"); + E && E->getBeginLoc().isMacroID() && E->getEndLoc().isMacroID()) { + const auto *Use = Result.Nodes.getNodeAs<Decl>("use"); + assert(Use); + PPCallback->validateExpansionRange( + E->getSourceRange(), + getUseNamespace(Use, E->getBeginLoc(), *Result.SourceManager)); + } + auto *TLDecl = Result.Nodes.getNodeAs<Decl>("top"); if (TLDecl == nullptr) return; diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/macro-to-enum.md b/clang-tools-extra/docs/clang-tidy/checks/modernize/macro-to-enum.md index 35a3a5e9f558d9..b2710524e8bfd3 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/modernize/macro-to-enum.md +++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/macro-to-enum.md @@ -23,6 +23,9 @@ Potential macros for replacement must meet the following constraints: Parenthesized expressions are also recognized. This recognizes most valid expressions. In particular, expressions with the `sizeof` operator are not recognized. +- Every observed expansion in the translation unit must form a complete + expression. Macros supplying call parentheses or argument lists are + excluded, even if their replacement tokens are otherwise eligible. - Macros must be defined on sequential source file lines, or with only comment lines in between macro definitions. - Macros must all be defined in the same source file. @@ -30,10 +33,32 @@ Potential macros for replacement must meet the following constraints: (Conditional include guards are exempt from this constraint.) - Macros must not be defined adjacent to other preprocessor directives. - Macros must not be used in any conditional preprocessing directive. -- Macros must not be used as arguments to other macros. -- Macros must not be undefined. -- Macros must be defined at the top-level, not inside any declaration or - definition. +- Macros passed as arguments to other macros must form complete + expressions in every substituted copy. Expanded arguments used to + construct strings or tokens are excluded. +- Macros must not be referenced in the body of a function-like macro. +- Macros must not be undefined or redefined. +- Macros must be defined at namespace or translation-unit scope, not + inside a function or class. For a macro defined inside a namespace, + every observed use must be within that namespace or a nested namespace. + Reopened namespace blocks count as the same namespace. Language linkage + blocks, such as `extern "C"`, do not introduce a scope and are allowed. + +For example, this macro remains unchanged: + +```c++ +#define CALL_ARGS (1, 2) + +void consume(int, int); +void example() { + consume CALL_ARGS; +} +``` + +Here, `CALL_ARGS` supplies the function call's argument list. Each argument +is an expression, but the complete expansion is not. Replacing the macro +with an enumerator would remove the call parentheses. In C++, the same +replacement text used as a complete comma expression can still be eligible. Each cluster of macros meeting the above constraints is presumed to be a set of values suitable for replacement by an anonymous enum. diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-local.h b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-local.h new file mode 100644 index 00000000000000..12cf12baf06263 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-local.h @@ -0,0 +1,8 @@ +#ifndef EXPANSION_LOCAL_H +#define EXPANSION_LOCAL_H + +#define HEADER_LOCAL 41 +// CHECK-MESSAGES-NOT: warning: +// CHECK-FIXES: #define HEADER_LOCAL 41 + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-redefined.h b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-redefined.h new file mode 100644 index 00000000000000..cf6f0434e43406 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-redefined.h @@ -0,0 +1,8 @@ +#ifndef EXPANSION_REDEFINED_H +#define EXPANSION_REDEFINED_H + +#define REDEFINED_HEADER (22) +// CHECK-MESSAGES-NOT: warning: +// CHECK-FIXES: #define REDEFINED_HEADER (22) + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-uses.h b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-uses.h new file mode 100644 index 00000000000000..60704b4e0e53e2 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/expansion-uses.h @@ -0,0 +1,22 @@ +#ifndef EXPANSION_USES_H +#define EXPANSION_USES_H + +#define HEADER_SAFE (13) +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'HEADER_SAFE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: HEADER_SAFE = (13) +// CHECK-FIXES-NEXT: }; + +#define HEADER_BAD (14) +// CHECK-FIXES: #define HEADER_BAD (14) + +#define HEADER_LATE_BAD (15) +// CHECK-FIXES: #define HEADER_LATE_BAD (15) + +void header_uses() { + use_one(HEADER_SAFE); + use_one HEADER_BAD; +} + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-local.h b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-local.h new file mode 100644 index 00000000000000..dcb014ca28461d --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-local.h @@ -0,0 +1,8 @@ +#ifndef LINKAGE_LOCAL_H +#define LINKAGE_LOCAL_H + +#define LINKAGE_HEADER_LOCAL 9 +// CHECK-MESSAGES-NOT: warning: +// CHECK-FIXES: #define LINKAGE_HEADER_LOCAL 9 + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-values.h b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-values.h new file mode 100644 index 00000000000000..b51bd2d3bf9ad6 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-values.h @@ -0,0 +1,21 @@ +#ifndef LINKAGE_VALUES_H +#define LINKAGE_VALUES_H + +extern "C" { + +#define HEADER_SEEK_CUR (1) +#define HEADER_SEEK_END (2) +#define HEADER_SEEK_SET (0) +// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: macro 'HEADER_SEEK_CUR' defines an integral constant; prefer an enum instead +// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: macro 'HEADER_SEEK_END' defines an integral constant; prefer an enum instead +// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: macro 'HEADER_SEEK_SET' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: HEADER_SEEK_CUR = (1), +// CHECK-FIXES-NEXT: HEADER_SEEK_END = (2), +// CHECK-FIXES-NEXT: HEADER_SEEK_SET = (0) +// CHECK-FIXES-NEXT: }; + +} + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-wrapper.h b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-wrapper.h new file mode 100644 index 00000000000000..ac92f41cc43a05 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/linkage-wrapper.h @@ -0,0 +1,10 @@ +#ifndef LINKAGE_WRAPPER_H +#define LINKAGE_WRAPPER_H + +extern "C" { +// CHECK-FIXES: extern "C" { +#include "linkage-values.h" +// CHECK-FIXES: #include "linkage-values.h" +} + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/namespace-values.h b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/namespace-values.h new file mode 100644 index 00000000000000..7ae7c8e76cfbf5 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/macro-to-enum/namespace-values.h @@ -0,0 +1,18 @@ +#ifndef NAMESPACE_VALUES_H +#define NAMESPACE_VALUES_H + +#define NAMESPACE_HEADER_VALUE 41 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'NAMESPACE_HEADER_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: NAMESPACE_HEADER_VALUE = 41 +// CHECK-FIXES-NEXT: }; + +#define NAMESPACE_HEADER_ESCAPE 42 +// CHECK-FIXES: #define NAMESPACE_HEADER_ESCAPE 42 + +int header_value() { + return NAMESPACE_HEADER_VALUE + NAMESPACE_HEADER_ESCAPE; +} + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-arguments.c b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-arguments.c new file mode 100644 index 00000000000000..5482b30564f894 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-arguments.c @@ -0,0 +1,98 @@ +// RUN: %check_clang_tidy -std=c11-or-later %s modernize-macro-to-enum %t-c -- -- -Wno-unused-value +// RUN: %clang -std=c11 -Wno-unused-value -fsyntax-only %t-c.c +// RUN: %check_clang_tidy -std=c++14-or-later -assume-filename=arguments.cpp %s modernize-macro-to-enum %t-cxx -- -- -Wno-unused-value +// RUN: %clang -std=c++14 -Wno-unused-value -fsyntax-only %t-cxx.cpp + +void use_one(int); + +#define CURLMIN(a, b) ((a) < (b) ? (a) : (b)) +#define FORWARD_MIN(a, b) CURLMIN(a, b) + +// Each substituted copy is a complete expression, including forwarded copies. +#define CW_PAUSE_DEC_WRITE_CHUNK (4096) +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'CW_PAUSE_DEC_WRITE_CHUNK' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: CW_PAUSE_DEC_WRITE_CHUNK = (4096) +// CHECK-FIXES-NEXT: }; + +int chunk_size(int length) { + return CURLMIN(length, CW_PAUSE_DEC_WRITE_CHUNK); +} + +int forwarded_chunk_size(int length) { + return FORWARD_MIN(length, CW_PAUSE_DEC_WRITE_CHUNK); +} + +#define SUM_VALUE 1 + 2 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'SUM_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: SUM_VALUE = 1 + 2 +// CHECK-FIXES-NEXT: }; + +int sum_size(int length) { + return CURLMIN(length, SUM_VALUE); +} + +struct hwb_color { + float H, W, B; +}; + +#define RETURN_HWB(h, w, b) { HWB->H = h; HWB->W = w; HWB->B = b; return HWB; } + +// A constant used in a statement macro still forms a complete expression. +#define HWB_UNDEFINED -1 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'HWB_UNDEFINED' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: HWB_UNDEFINED = -1 +// CHECK-FIXES-NEXT: }; + +struct hwb_color *undefined_hue(struct hwb_color *HWB, float w, float b) { + RETURN_HWB(HWB_UNDEFINED, w, b); +} + +// One complete copy cannot validate another copy used as partial syntax. +#define SAFE_FIRST(x) ((x), 3 * x) +#define UNSAFE_FIRST(x) (3 * x, (x)) +#define MIXED_VALUE 1 + 2 +// CHECK-FIXES: #define MIXED_VALUE 1 + 2 + +int mixed_first(void) { + return SAFE_FIRST(MIXED_VALUE); +} + +#define REVERSED_VALUE 1 + 2 +// CHECK-FIXES: #define REVERSED_VALUE 1 + 2 + +int mixed_last(void) { + return UNSAFE_FIRST(REVERSED_VALUE); +} + +#define MIXED_CALL(x) (use_one(x), use_one x) +#define CALL_VALUE (7) +// CHECK-FIXES: #define CALL_VALUE (7) + +void mixed_call(void) { + MIXED_CALL(CALL_VALUE); +} + +// A forwarded copy used only to construct a string is not an expression. +#define STRINGIFY_IMPL(x) #x +#define STRINGIFY(x) STRINGIFY_IMPL(x) +#define USE_AND_STRINGIFY(x) ((void)(x), STRINGIFY(x)) +#define STRING_VALUE 42 +// CHECK-FIXES: #define STRING_VALUE 42 + +const char *string_value(void) { + return USE_AND_STRINGIFY(STRING_VALUE); +} + +// A separate valid expansion cannot hide an invalid macro argument. +#define MULTIPLY(x) 3 * x +#define PARTIAL_VALUE 1 + 2 +// CHECK-FIXES: #define PARTIAL_VALUE 1 + 2 + +int Direct = PARTIAL_VALUE; +int Partial = MULTIPLY(PARTIAL_VALUE); diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-headers.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-headers.cpp new file mode 100644 index 00000000000000..2881a97b747987 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-headers.cpp @@ -0,0 +1,42 @@ +// RUN: %check_clang_tidy -std=c++14-or-later \ +// RUN: -check-header %S/Inputs/macro-to-enum/expansion-uses.h \ +// RUN: -check-header %S/Inputs/macro-to-enum/expansion-local.h \ +// RUN: -check-header %S/Inputs/macro-to-enum/expansion-redefined.h \ +// RUN: %s modernize-macro-to-enum %t -- \ +// RUN: -- -I%S/Inputs/macro-to-enum -Wno-macro-redefined -fno-delayed-template-parsing +// RUN: %clang -std=c++14 -Wno-macro-redefined -fsyntax-only -I%t.cpp.headers %t.cpp + +void use_one(int); + +#include "expansion-uses.h" +#include "expansion-uses.h" + +// The definition is in a header, but its scope is the enclosing function. +void local_header_definition() { +#include "expansion-local.h" +} + +int LocalUse = HEADER_LOCAL; + +void old_header_definition() { +#define REDEFINED_HEADER (21) + // CHECK-FIXES: #define REDEFINED_HEADER (21) +} + +#include "expansion-redefined.h" + +// Keep a positive control so source diagnostics are checked as well. +#define SOURCE_SAFE (23) +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'SOURCE_SAFE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: SOURCE_SAFE = (23) +// CHECK-FIXES-NEXT: }; + +void including_file_uses() { + use_one(SOURCE_SAFE); + use_one(HEADER_SAFE); + use_one(HEADER_SAFE); + use_one HEADER_LATE_BAD; + use_one REDEFINED_HEADER; +} diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-nested.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-nested.cpp new file mode 100644 index 00000000000000..e27a31121d1962 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-nested.cpp @@ -0,0 +1,98 @@ +// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -Wno-unused-value -fno-delayed-template-parsing +// RUN: %clang -std=c++14 -Wno-unused-value -fno-delayed-template-parsing -fsyntax-only %t.cpp + +void use_one(int); +void use_two(int, int); + +// Validate the defining macro through several object-like expansions. +#define NESTED_VALUE 12345 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'NESTED_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: NESTED_VALUE = 12345 +// CHECK-FIXES-NEXT: }; +#define VALUE_ALIAS NESTED_VALUE +#define SECOND_ALIAS VALUE_ALIAS + +int Nested = SECOND_ALIAS; + +// The inner expression need not consume its enclosing macro expansion. +#define NESTED_TERM (12 + 34) +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'NESTED_TERM' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: NESTED_TERM = (12 + 34) +// CHECK-FIXES-NEXT: }; +#define TERM_ALIAS 3 * NESTED_TERM + +int Term = TERM_ALIAS; + +// A containing expression must not validate a partial inner expansion. +#define PARTIAL_VALUE 1 + 2 +// CHECK-FIXES: #define PARTIAL_VALUE 1 + 2 +#define PARTIAL_ALIAS 3 * PARTIAL_VALUE + +int Partial = PARTIAL_ALIAS; + +// One safe nested use cannot validate another invocation used as syntax. +#define MIXED_ARGS (1, 2) +// CHECK-FIXES: #define MIXED_ARGS (1, 2) +#define ARGS_ALIAS MIXED_ARGS + +int Mixed = ARGS_ALIAS; +void nested_call() { + use_two ARGS_ALIAS; +} + +// Preserve exclusions for references in function-like macro bodies. +#define BODY_VALUE 20 +// CHECK-FIXES: #define BODY_VALUE 20 +#define BODY_WRAPPER() BODY_VALUE + +int Body = BODY_WRAPPER(); + +#define ARG_VALUE 21 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'ARG_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: ARG_VALUE = 21 +// CHECK-FIXES-NEXT: }; +#define IDENTITY(x) x + +int Argument = IDENTITY(ARG_VALUE); + +#define PASTE_VALUE 22 +// CHECK-FIXES: #define PASTE_VALUE 22 +#define PASTE_IMPL(a, b) a##b +#define PASTE(a, b) PASTE_IMPL(a, b) + +int pasted22; +int *Pasted = &PASTE(pasted, PASTE_VALUE); + +// Instantiations revisit source locations already seen in the template body. +#define TEMPLATE_VALUE (31) +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'TEMPLATE_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: TEMPLATE_VALUE = (31) +// CHECK-FIXES-NEXT: }; + +template <typename T> int safe_template(T) { + use_one(TEMPLATE_VALUE); + return TEMPLATE_VALUE; +} + +int First = safe_template(0); +int Second = safe_template(0L); + +#define TEMPLATE_ARGS (32) +// CHECK-FIXES: #define TEMPLATE_ARGS (32) + +template <typename T> void unsafe_template(T) { + use_one TEMPLATE_ARGS; +} + +void instantiate() { + unsafe_template(0); + unsafe_template(0L); +} diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-redefined.c b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-redefined.c new file mode 100644 index 00000000000000..93e877c3b8a10a --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand-redefined.c @@ -0,0 +1,67 @@ +// RUN: %check_clang_tidy -std=c11-or-later %s modernize-macro-to-enum %t-c -- -- -Wno-macro-redefined +// RUN: %clang -std=c11 -Wno-macro-redefined -fsyntax-only %t-c.c +// RUN: %check_clang_tidy -std=c++14-or-later -assume-filename=redefined.cpp %s modernize-macro-to-enum %t-cxx -- -- -Wno-macro-redefined +// RUN: %clang -std=c++14 -Wno-macro-redefined -fsyntax-only %t-cxx.cpp + +void use_one(int); + +// A new definition's unsafe use must not attach to an older, excluded one. +void old_definition(void) { +#define REDEFINED (1) + // CHECK-FIXES: #define REDEFINED (1) +} + +#define REDEFINED (2) +// CHECK-FIXES: #define REDEFINED (2) + +void redefined_use(void) { + use_one REDEFINED; +} + +// Replacing the second definition would leave the first macro active at the +// enumerator declaration, even though all uses are complete expressions. +#define REDEFINED_LITERAL unknown_identifier +// CHECK-FIXES: #define REDEFINED_LITERAL unknown_identifier +#define REDEFINED_LITERAL 3 +// CHECK-FIXES: #define REDEFINED_LITERAL 3 + +int Literal = REDEFINED_LITERAL; + +#define CONDITIONAL_REDEF (4) +// CHECK-FIXES: #define CONDITIONAL_REDEF (4) + +int BeforeConditional = CONDITIONAL_REDEF; +#if 1 +#define CONDITIONAL_REDEF (5) +// CHECK-FIXES: #define CONDITIONAL_REDEF (5) +#endif +int AfterConditional = CONDITIONAL_REDEF; + +// Preserve the existing exclusion of all definitions of an undefined name. +#define UNDEFINED (6) +// CHECK-FIXES: #define UNDEFINED (6) + +int BeforeUndef = UNDEFINED; +#undef UNDEFINED +#define UNDEFINED (7) +// CHECK-FIXES: #define UNDEFINED (7) + +int AfterUndef = UNDEFINED; + +// Redefined function-like macros still exclude names in their new bodies. +#define WRAPPER() 0 +#define WRAPPED_VALUE 8 +// CHECK-FIXES: #define WRAPPED_VALUE 8 +#define WRAPPER() WRAPPED_VALUE + +int Wrapped = WRAPPER(); + +// Unrelated definitions still convert. +#define INDEPENDENT 70 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'INDEPENDENT' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: INDEPENDENT = 70 +// CHECK-FIXES-NEXT: }; + +int Independent = INDEPENDENT; diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.c b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.c new file mode 100644 index 00000000000000..49ffe7f6f99586 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.c @@ -0,0 +1,86 @@ +// RUN: %check_clang_tidy -std=c11-or-later %s modernize-macro-to-enum %t-c +// RUN: %clang -std=c11 -fsyntax-only %t-c.c +// RUN: %check_clang_tidy -std=c++14-or-later -assume-filename=expand.cpp %s modernize-macro-to-enum %t-cxx +// RUN: %clang -std=c++14 -fsyntax-only %t-cxx.cpp + +void use_one(int); + +// A macro supplying call parentheses is not an expression. Reject its entire +// cluster, including a safely used macro and an unused macro. +#define CLUSTER_SAFE 9 +#define CALL_ARGS (1) +#define CLUSTER_UNUSED 2 +// CHECK-FIXES: #define CLUSTER_SAFE 9 +// CHECK-FIXES-NEXT: #define CALL_ARGS (1) +// CHECK-FIXES-NEXT: #define CLUSTER_UNUSED 2 + +int ClusterValue = CLUSTER_SAFE; +void call_args(void) { + use_one CALL_ARGS; +} + +// A safe use cannot validate a different, unsafe use of the same macro. +#define SAFE_THEN_UNSAFE (3) +// CHECK-FIXES: #define SAFE_THEN_UNSAFE (3) + +int SafeFirst = SAFE_THEN_UNSAFE; +void safe_then_unsafe(void) { + use_one SAFE_THEN_UNSAFE; +} + +#define UNSAFE_THEN_SAFE (4) +// CHECK-FIXES: #define UNSAFE_THEN_SAFE (4) + +void unsafe_then_safe(void) { + use_one UNSAFE_THEN_SAFE; +} +int SafeLast = UNSAFE_THEN_SAFE; + +// Replacing either fragment with an enumerator would change parsing. +#define UNGROUPED 1 + 2 +// CHECK-FIXES: #define UNGROUPED 1 + 2 + +int Product = 3 * UNGROUPED; + +#define SUBTRACTION -1 +// CHECK-FIXES: #define SUBTRACTION -1 + +int Difference = 3 SUBTRACTION; + +// Independent safe clusters still convert, including repeated expansions. +#define SAFE_LITERAL 1 +#define SAFE_UNARY -2 +#define SAFE_BINARY 1 + 2 +#define SAFE_PARENS ((4)) +// CHECK-MESSAGES: :[[@LINE-4]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: macro 'SAFE_LITERAL' defines an integral constant; prefer an enum instead +// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: macro 'SAFE_UNARY' defines an integral constant; prefer an enum instead +// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: macro 'SAFE_BINARY' defines an integral constant; prefer an enum instead +// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: macro 'SAFE_PARENS' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: SAFE_LITERAL = 1, +// CHECK-FIXES-NEXT: SAFE_UNARY = -2, +// CHECK-FIXES-NEXT: SAFE_BINARY = 1 + 2, +// CHECK-FIXES-NEXT: SAFE_PARENS = ((4)) +// CHECK-FIXES-NEXT: }; + +int Literal = SAFE_LITERAL; +int Unary = SAFE_UNARY; +int Binary = SAFE_BINARY; +int Parens = SAFE_PARENS; + +void safe_uses(void) { + use_one(SAFE_LITERAL); + use_one(SAFE_LITERAL); + use_one(SAFE_UNARY); + use_one(SAFE_BINARY); + use_one(SAFE_PARENS); +} + +// No observed expansions is not evidence of an unsafe use. +#define UNUSED 7 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'UNUSED' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: UNUSED = 7 +// CHECK-FIXES-NEXT: }; diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.cpp new file mode 100644 index 00000000000000..fdd4efb04e226e --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-expand.cpp @@ -0,0 +1,27 @@ +// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -Wno-unused-value +// RUN: %clang -std=c++14 -Wno-unused-value -fsyntax-only %t.cpp + +void use_two(int, int); + +// The arguments are expressions, but the complete expansion is an argument +// list. Neither a partial argument nor the enclosing call validates it. +#define CALL_ARGS (1, 2) +// CHECK-FIXES: #define CALL_ARGS (1, 2) + +void call_args() { + use_two CALL_ARGS; +} + +// Identical replacement tokens can instead supply a complete comma expression. +#define COMMA_EXPR (1, 2) +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'COMMA_EXPR' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: COMMA_EXPR = (1, 2) +// CHECK-FIXES-NEXT: }; + +int Comma = COMMA_EXPR; + +void comma_uses() { + use_two(COMMA_EXPR, COMMA_EXPR); +} diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-linkage.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-linkage.cpp new file mode 100644 index 00000000000000..8e33d6b00219c7 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-linkage.cpp @@ -0,0 +1,89 @@ +// RUN: %check_clang_tidy -std=c++14-or-later \ +// RUN: -check-header %S/Inputs/macro-to-enum/linkage-wrapper.h \ +// RUN: -check-header %S/Inputs/macro-to-enum/linkage-values.h \ +// RUN: -check-header %S/Inputs/macro-to-enum/linkage-local.h \ +// RUN: %s modernize-macro-to-enum %t -- \ +// RUN: -- -I%S/Inputs/macro-to-enum -fno-delayed-template-parsing +// RUN: %clang -std=c++14 -fsyntax-only -I%t.cpp.headers %t.cpp + +// Nested linkage blocks and repeated header inclusion are transparent. +#include "linkage-wrapper.h" +#include "linkage-wrapper.h" + +extern "C" { + +#define LINKAGE_ONE 1 +#define LINKAGE_TWO 2 +// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-3]]:9: warning: macro 'LINKAGE_ONE' defines an integral constant; prefer an enum instead +// CHECK-MESSAGES: :[[@LINE-3]]:9: warning: macro 'LINKAGE_TWO' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: LINKAGE_ONE = 1, +// CHECK-FIXES-NEXT: LINKAGE_TWO = 2 +// CHECK-FIXES-NEXT: }; + +int linkage_use() { + return LINKAGE_ONE + LINKAGE_TWO + HEADER_SEEK_CUR + HEADER_SEEK_END + + HEADER_SEEK_SET; +} + +// Declarations inside the linkage block still exclude local definitions. +int local_definition() { +#define FUNCTION_LOCAL 3 + // CHECK-FIXES: #define FUNCTION_LOCAL 3 + return FUNCTION_LOCAL; +} + +int local_header_definition() { +#include "linkage-local.h" + return LINKAGE_HEADER_LOCAL; +} + +struct LinkageClass { +#define CLASS_LOCAL 4 + // CHECK-FIXES: #define CLASS_LOCAL 4 + int Value; +}; + +} + +// The enum names remain visible after the linkage block. +int Following = LINKAGE_ONE + HEADER_SEEK_CUR; +int LocalUses = FUNCTION_LOCAL + LINKAGE_HEADER_LOCAL + CLASS_LOCAL; + +// An unbraced linkage specification must still inspect its function body. +extern "C" int unbraced_definition() { +#define UNBRACED_LOCAL 5 + // CHECK-FIXES: #define UNBRACED_LOCAL 5 + return UNBRACED_LOCAL; +} + +int UnbracedUse = UNBRACED_LOCAL; + +namespace Hidden { +extern "C" { +#define NAMESPACE_LOCAL 6 +// CHECK-FIXES: #define NAMESPACE_LOCAL 6 +} +} + +int NamespaceUse = NAMESPACE_LOCAL; + +extern "C++" { + +#define CXX_LINKAGE 7 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'CXX_LINKAGE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: CXX_LINKAGE = 7 +// CHECK-FIXES-NEXT: }; + +template <typename T> int template_definition(T) { +#define TEMPLATE_LOCAL 8 + // CHECK-FIXES: #define TEMPLATE_LOCAL 8 + return TEMPLATE_LOCAL + CXX_LINKAGE; +} + +} + +int TemplateUse = template_definition(0) + TEMPLATE_LOCAL; diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-namespace.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-namespace.cpp new file mode 100644 index 00000000000000..00803e1863b1d7 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum-namespace.cpp @@ -0,0 +1,232 @@ +// RUN: %check_clang_tidy -std=c++17-or-later \ +// RUN: -check-header %S/Inputs/macro-to-enum/namespace-values.h \ +// RUN: %s modernize-macro-to-enum %t -- \ +// RUN: -- -I%S/Inputs/macro-to-enum -fno-delayed-template-parsing +// RUN: %clang -std=c++17 -fsyntax-only -I%t.cpp.headers %t.cpp + +// Translation-unit definitions remain usable from any namespace. +#define GLOBAL_VALUE 10 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'GLOBAL_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: GLOBAL_VALUE = 10 +// CHECK-FIXES-NEXT: }; + +namespace Same { + +#define SAME_VALUE 11 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'SAME_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: SAME_VALUE = 11 +// CHECK-FIXES-NEXT: }; + +int First = SAME_VALUE + GLOBAL_VALUE; +int function(); +struct Object { + int method(); +}; +} + +// Reopened blocks and out-of-line definitions retain their namespace. +namespace Same { +int Second = SAME_VALUE; +} + +int Same::function() { return SAME_VALUE; } +int Same::Object::method() { return SAME_VALUE; } + +namespace Same { +int parameter(int Value); +auto trailing() -> decltype(SAME_VALUE); +} + +int Same::parameter(int Value = SAME_VALUE) { return Value; } +auto Same::trailing() -> decltype(SAME_VALUE) { return SAME_VALUE; } + +// A leading return type is outside the qualified function's namespace. +namespace ReturnTypes { +#define RETURN_SIZE 23 +// CHECK-FIXES: #define RETURN_SIZE 23 + +template <int N> struct Buffer {}; +Buffer<RETURN_SIZE> make(); +} + +ReturnTypes::Buffer<RETURN_SIZE> ReturnTypes::make() { return {}; } + +// Specialization arguments precede the class scope, even after its name. +namespace Specializations { +#define SPECIALIZATION_SIZE 24 +// CHECK-FIXES: #define SPECIALIZATION_SIZE 24 + +template <int N> struct Buffer; +} + +template <> struct Specializations::Buffer<SPECIALIZATION_SIZE> {}; + +namespace Specializations { +#define FUNCTION_ARGUMENT_SIZE 26 +// CHECK-FIXES: #define FUNCTION_ARGUMENT_SIZE 26 + +template <int N> int function(); +} + +template <> int Specializations::function<FUNCTION_ARGUMENT_SIZE>() { return 0; } + +namespace Initializers { +#define INITIALIZER_VALUE 25 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'INITIALIZER_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: INITIALIZER_VALUE = 25 +// CHECK-FIXES-NEXT: }; + +extern int Value; +} + +int Initializers::Value = INITIALIZER_VALUE; + +namespace Outer { + +#define OUTER_VALUE 12 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'OUTER_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: OUTER_VALUE = 12 +// CHECK-FIXES-NEXT: }; + +namespace Child { +int NestedUse = OUTER_VALUE; +} +} + +// Qualified namespace syntax can give nested declarations shared ranges. +namespace Outer::Inner { + +#define INNER_VALUE 13 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'INNER_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: INNER_VALUE = 13 +// CHECK-FIXES-NEXT: }; + +int Value = INNER_VALUE; +int DescendantUse = OUTER_VALUE; + +#define INNER_ESCAPE 14 +// CHECK-FIXES: #define INNER_ESCAPE 14 + +int SafeUse = INNER_ESCAPE; +} + +namespace Outer::Inner { +int ReopenedUse = INNER_VALUE; +} + +namespace Outer { +// A use in the parent is outside the defining inner namespace. +int ParentUse = INNER_ESCAPE; +} + +// One outside use rejects the whole cluster, including its safely used member. +namespace Mixed { +#define GROUP_SAFE 15 +#define GROUP_ESCAPE 16 +// CHECK-FIXES: #define GROUP_SAFE 15 +// CHECK-FIXES-NEXT: #define GROUP_ESCAPE 16 + +int Local = GROUP_SAFE; +} + +int Outside = GROUP_ESCAPE; + +namespace Mixed { +#define MIXED_USES 17 +// CHECK-FIXES: #define MIXED_USES 17 + +int LocalMixed = MIXED_USES; +} + +namespace Other { +int OtherMixed = MIXED_USES; +} + +// Object-like aliases are checked at the eventual use, not their definition. +namespace Aliases { +#define ALIAS_VALUE 18 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'ALIAS_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: ALIAS_VALUE = 18 +// CHECK-FIXES-NEXT: }; +} + +#define VALUE_ALIAS ALIAS_VALUE + +namespace Aliases { +int Value = VALUE_ALIAS; +} + +// Separate anonymous namespace blocks refer to the same namespace. +namespace { +#define ANONYMOUS_VALUE 19 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'ANONYMOUS_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: ANONYMOUS_VALUE = 19 +// CHECK-FIXES-NEXT: }; + +int AnonymousFirst = ANONYMOUS_VALUE; +} + +namespace { +int AnonymousSecond = ANONYMOUS_VALUE; +} + +namespace Templates { +#define TEMPLATE_VALUE 20 +// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: replace macro with enum +// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: macro 'TEMPLATE_VALUE' defines an integral constant; prefer an enum instead +// CHECK-FIXES: enum { +// CHECK-FIXES-NEXT: TEMPLATE_VALUE = 20 +// CHECK-FIXES-NEXT: }; + +template <typename T> int value(T) { return TEMPLATE_VALUE; } +} + +int FirstInstance = Templates::value(0); +int SecondInstance = Templates::value(0L); + +// Included definitions inherit the namespace, through linkage blocks as well. +namespace Headers { +extern "C" { +#include "namespace-values.h" +} +} + +namespace Headers { +#include "namespace-values.h" +int HeaderUse = NAMESPACE_HEADER_VALUE; +} + +int HeaderEscape = NAMESPACE_HEADER_ESCAPE; + +// Namespace support must not admit definitions inside functions or classes. +namespace LocalScopes { +int function() { +#define NAMESPACE_FUNCTION_LOCAL 21 + // CHECK-FIXES: #define NAMESPACE_FUNCTION_LOCAL 21 + return NAMESPACE_FUNCTION_LOCAL; +} + +int AfterFunction = NAMESPACE_FUNCTION_LOCAL; + +struct Object { +#define NAMESPACE_CLASS_LOCAL 22 + // CHECK-FIXES: #define NAMESPACE_CLASS_LOCAL 22 + int Value; +}; + +int AfterClass = NAMESPACE_CLASS_LOCAL; +} diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum.cpp index e2df29d2d163e6..ced22e532b09e5 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/macro-to-enum.cpp @@ -1,4 +1,9 @@ -// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -I%S/Inputs/macro-to-enum -fno-delayed-template-parsing +// RUN: %check_clang_tidy -std=c++14-or-later \ +// RUN: -check-header %S/Inputs/macro-to-enum/modernize-macro-to-enum.h \ +// RUN: -check-header %S/Inputs/macro-to-enum/modernize-macro-to-enum2.h \ +// RUN: -check-header %S/Inputs/macro-to-enum/modernize-macro-to-enum3.h \ +// RUN: %s modernize-macro-to-enum %t -- \ +// RUN: -- -I%S/Inputs/macro-to-enum -fno-delayed-template-parsing // C++14 or later required for binary literals. #if 1 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
