https://github.com/matthew-j-code created https://github.com/llvm/llvm-project/pull/242355
Allow entries in: AttributeMacros, ForEachMacros, IfMacros, NamespaceMacros, StatementAttributeLikeMacros, StatementMacros, TypeNameMacros, WhitespaceSensitiveMacros to be regular expressions matched against the whole macro name. This lets a single pattern cover a family of macros that share a naming convention, instead of listing each one: WhitespaceSensitiveMacros: ['^DEBUG_WRITE.*$'] Plain macro names continue to work as before. AI usage: Claude (to review code) >From efab0a16fd78673a28333da2c0dba34c9086521e Mon Sep 17 00:00:00 2001 From: "Jones, Matthew (DI SW SIM FRWK PLAT SIMFW HPC)" <[email protected]> Date: Wed, 28 Oct 2026 07:50:31 -0700 Subject: [PATCH] [clang-format] Macro list options now accept regular expressions --- clang/docs/ClangFormatStyleOptions.md | 24 ++++++ clang/docs/ReleaseNotes.md | 2 + clang/include/clang/Format/Format.h | 23 +++++ clang/lib/Format/Format.cpp | 27 ++++++ clang/lib/Format/FormatTokenLexer.cpp | 86 +++++++++---------- clang/lib/Format/FormatTokenLexer.h | 4 +- clang/lib/Format/TokenAnnotator.cpp | 15 ++-- clang/unittests/Format/ConfigParseTest.cpp | 32 +++++++ clang/unittests/Format/TokenAnnotatorTest.cpp | 50 +++++++++++ 9 files changed, 210 insertions(+), 53 deletions(-) diff --git a/clang/docs/ClangFormatStyleOptions.md b/clang/docs/ClangFormatStyleOptions.md index c7de6fc25e1f3..3dce7762143e4 100644 --- a/clang/docs/ClangFormatStyleOptions.md +++ b/clang/docs/ClangFormatStyleOptions.md @@ -2291,6 +2291,9 @@ the configuration (without a prefix: `Auto`). AttributeMacros: [__capability, __output, __unused] ``` + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (binpackarguments)= **BinPackArguments** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <BinPackArguments>` @@ -4600,6 +4603,9 @@ the configuration (without a prefix: `Auto`). For example: BOOST_FOREACH. + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (ifmacros)= **IfMacros** (`List of Strings`) {versionbadge}`clang-format 13` {ref}`¶ <IfMacros>` @@ -4625,6 +4631,9 @@ the configuration (without a prefix: `Auto`). For example: [KJ_IF_MAYBE](https://github.com/capnproto/capnproto/blob/master/kjdoc/tour.md#maybes) + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (includeblocks)= **IncludeBlocks** (`IncludeBlocksStyle`) {versionbadge}`clang-format 6` {ref}`¶ <IncludeBlocks>` @@ -5797,6 +5806,9 @@ the configuration (without a prefix: `Auto`). For example: TESTSUITE + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (numericliteralcase)= **NumericLiteralCase** (`NumericLiteralCaseStyle`) {versionbadge}`clang-format 22` {ref}`¶ <NumericLiteralCase>` @@ -7989,6 +8001,9 @@ the configuration (without a prefix: `Auto`). emit signal(data); // Now it's fine again. ``` + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (statementmacros)= **StatementMacros** (`List of Strings`) {versionbadge}`clang-format 8` {ref}`¶ <StatementMacros>` @@ -8001,6 +8016,9 @@ the configuration (without a prefix: `Auto`). For example: Q_UNUSED + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (tabwidth)= **TabWidth** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <TabWidth>` @@ -8114,6 +8132,9 @@ the configuration (without a prefix: `Auto`). For example: OpenSSL STACK_OF, BSD LIST_ENTRY. + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (usecrlf)= **UseCRLF** (`Boolean`) {versionbadge}`clang-format 10` {ref}`¶ <UseCRLF>` @@ -8196,6 +8217,9 @@ the configuration (without a prefix: `Auto`). For example: BOOST_PP_STRINGIZE + Entries that are not plain identifiers are regular expressions matched + against identifiers, e.g. `DEBUG_WRITE.*`. + (wrapnamespacebodywithemptylines)= **WrapNamespaceBodyWithEmptyLines** (`WrapNamespaceBodyWithEmptyLinesStyle`) {versionbadge}`clang-format 20` {ref}`¶ <WrapNamespaceBodyWithEmptyLines>` diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md index 14382a06db34c..e7caa006460ff 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -1516,6 +1516,8 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and - Recognize `.mts` and `.cts` files as TypeScript, including in `git-clang-format` and `clang-format-diff.py`. The latter also now includes `.mjs` and `.cjs` files by default. +- Macro list options (`ForEachMacros`, `WhitespaceSensitiveMacros`, etc.) + now accept regular expressions such as `DEBUG_WRITE.*`. ### libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 1f29dd630b802..13719941a40d4 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -1292,6 +1292,8 @@ struct FormatStyle { /// AttributeMacros: [__capability, __output, __unused] /// \endcode /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 12 std::vector<std::string> AttributeMacros; @@ -3170,6 +3172,9 @@ struct FormatStyle { /// \endcode /// /// For example: BOOST_FOREACH. + /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 3.7 std::vector<std::string> ForEachMacros; @@ -3193,6 +3198,9 @@ struct FormatStyle { /// /// For example: /// [KJ_IF_MAYBE](https://github.com/capnproto/capnproto/blob/master/kjdoc/tour.md#maybes) + /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 13 std::vector<std::string> IfMacros; @@ -4078,6 +4086,9 @@ struct FormatStyle { /// \endcode /// /// For example: TESTSUITE + /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 9 std::vector<std::string> NamespaceMacros; @@ -5973,6 +5984,9 @@ struct FormatStyle { /// unsigned char data = 'x'; /// emit signal(data); // Now it's fine again. /// \endcode + /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 12 std::vector<std::string> StatementAttributeLikeMacros; @@ -5983,6 +5997,9 @@ struct FormatStyle { /// of such cases. /// /// For example: Q_UNUSED + /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 8 std::vector<std::string> StatementMacros; @@ -6077,6 +6094,9 @@ struct FormatStyle { /// \endcode /// /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY. + /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 9 std::vector<std::string> TypenameMacros; @@ -6142,6 +6162,9 @@ struct FormatStyle { /// \endcode /// /// For example: BOOST_PP_STRINGIZE + /// + /// Entries that are not plain identifiers are regular expressions matched + /// against identifiers, e.g. `DEBUG_WRITE.*`. /// \version 11 std::vector<std::string> WhitespaceSensitiveMacros; diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index b5518101c92af..35ff98574084b 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1110,6 +1110,22 @@ struct ScalarEnumerationTraits< } }; +static void validateMacroPatterns(IO &Io, StringRef Key, + ArrayRef<std::string> Names) { + if (Io.outputting()) + return; + std::string Error; + for (const StringRef Name : Names) { + if (llvm::Regex::isLiteralERE(Name)) + continue; + llvm::Regex Re(Name); + if (!Re.isValid(Error)) { + Io.setError("Invalid regex pattern in " + Key + ": " + Name + " (" + + Error + ")"); + } + } +} + template <> struct MappingTraits<FormatStyle> { static void mapping(IO &IO, FormatStyle &Style) { // When reading, read the language first, we need it for getPredefinedStyle. @@ -1569,6 +1585,17 @@ template <> struct MappingTraits<FormatStyle> { IO.mapOptional("WrapNamespaceBodyWithEmptyLines", Style.WrapNamespaceBodyWithEmptyLines); + validateMacroPatterns(IO, "AttributeMacros", Style.AttributeMacros); + validateMacroPatterns(IO, "ForEachMacros", Style.ForEachMacros); + validateMacroPatterns(IO, "IfMacros", Style.IfMacros); + validateMacroPatterns(IO, "NamespaceMacros", Style.NamespaceMacros); + validateMacroPatterns(IO, "StatementAttributeLikeMacros", + Style.StatementAttributeLikeMacros); + validateMacroPatterns(IO, "StatementMacros", Style.StatementMacros); + validateMacroPatterns(IO, "TypenameMacros", Style.TypenameMacros); + validateMacroPatterns(IO, "WhitespaceSensitiveMacros", + Style.WhitespaceSensitiveMacros); + // If AlwaysBreakAfterDefinitionReturnType was specified but // BreakAfterReturnType was not, initialize the latter from the former for // backwards compatibility. diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index 336dd79563aad..b656b80d03883 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -39,40 +39,22 @@ FormatTokenLexer::FormatTokenLexer( LangOpts); Lex->SetKeepWhitespaceMode(true); - for (const std::string &ForEachMacro : Style.ForEachMacros) { - auto Identifier = &IdentTable.get(ForEachMacro); - Macros.insert({Identifier, TT_ForEachMacro}); - } - for (const std::string &IfMacro : Style.IfMacros) { - auto Identifier = &IdentTable.get(IfMacro); - Macros.insert({Identifier, TT_IfMacro}); - } - for (const std::string &AttributeMacro : Style.AttributeMacros) { - auto Identifier = &IdentTable.get(AttributeMacro); - Macros.insert({Identifier, TT_AttributeMacro}); - } - for (const std::string &StatementMacro : Style.StatementMacros) { - auto Identifier = &IdentTable.get(StatementMacro); - Macros.insert({Identifier, TT_StatementMacro}); - } - for (const std::string &TypenameMacro : Style.TypenameMacros) { - auto Identifier = &IdentTable.get(TypenameMacro); - Macros.insert({Identifier, TT_TypenameMacro}); - } - for (const std::string &NamespaceMacro : Style.NamespaceMacros) { - auto Identifier = &IdentTable.get(NamespaceMacro); - Macros.insert({Identifier, TT_NamespaceMacro}); - } - for (const std::string &WhitespaceSensitiveMacro : - Style.WhitespaceSensitiveMacros) { - auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro); - Macros.insert({Identifier, TT_UntouchableMacroFunc}); - } - for (const std::string &StatementAttributeLikeMacro : - Style.StatementAttributeLikeMacros) { - auto Identifier = &IdentTable.get(StatementAttributeLikeMacro); - Macros.insert({Identifier, TT_StatementAttributeLikeMacro}); - } + auto addMacros = [&](ArrayRef<std::string> Names, TokenType Type) { + for (const StringRef Name : Names) + if (!llvm::Regex::isLiteralERE(Name)) + MacroPatterns.emplace_back(llvm::Regex(Name), Type); + else + Macros.try_emplace(&IdentTable.get(Name), Type); + }; + + addMacros(Style.ForEachMacros, TT_ForEachMacro); + addMacros(Style.IfMacros, TT_IfMacro); + addMacros(Style.AttributeMacros, TT_AttributeMacro); + addMacros(Style.StatementMacros, TT_StatementMacro); + addMacros(Style.TypenameMacros, TT_TypenameMacro); + addMacros(Style.NamespaceMacros, TT_NamespaceMacro); + addMacros(Style.WhitespaceSensitiveMacros, TT_UntouchableMacroFunc); + addMacros(Style.StatementAttributeLikeMacros, TT_StatementAttributeLikeMacro); for (const auto &Macro : Style.MacrosSkippedByRemoveParentheses) MacrosSkippedByRemoveParentheses.insert(&IdentTable.get(Macro)); @@ -1494,17 +1476,31 @@ FormatToken *FormatTokenLexer::getNextToken() { if (IsCpp) { auto *Identifier = FormatTok->Tok.getIdentifierInfo(); - auto it = Macros.find(Identifier); - if ((Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() || - Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() != - tok::pp_define) && - it != Macros.end()) { - FormatTok->setType(it->second); - if (it->second == TT_IfMacro) { - // The lexer token currently has type tok::kw_unknown. However, for this - // substitution to be treated correctly in the TokenAnnotator, faking - // the tok value seems to be needed. Not sure if there's a more elegant - // way. + const bool NotDefineName = + Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() || + Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() != + tok::pp_define; + std::optional<TokenType> MacroType; + if (Identifier && NotDefineName) { + if (const auto It = Macros.find(Identifier); It != Macros.end()) { + MacroType = It->second; + } else if (FormatTok->is(tok::identifier) && !MacroPatterns.empty()) { + for (const auto &[Re, Type] : MacroPatterns) { + if (Re.match(Identifier->getName())) { + MacroType = Type; + break; + } + } + Macros.try_emplace(Identifier, MacroType); + } + } + if (MacroType) { + FormatTok->setType(*MacroType); + if (*MacroType == TT_IfMacro) { + // The lexer token currently has type tok::kw_unknown. However, for + // this substitution to be treated correctly in the TokenAnnotator, + // faking the tok value seems to be needed. Not sure if there's a more + // elegant way. FormatTok->Tok.setKind(tok::kw_if); } } else if (FormatTok->is(tok::identifier)) { diff --git a/clang/lib/Format/FormatTokenLexer.h b/clang/lib/Format/FormatTokenLexer.h index 6fbd05aef7747..1c9962299820c 100644 --- a/clang/lib/Format/FormatTokenLexer.h +++ b/clang/lib/Format/FormatTokenLexer.h @@ -130,7 +130,9 @@ class FormatTokenLexer { unsigned FirstInLineIndex; SmallVector<FormatToken *, 16> Tokens; - llvm::SmallMapVector<IdentifierInfo *, TokenType, 8> Macros; + llvm::SmallMapVector<const IdentifierInfo *, std::optional<TokenType>, 8> + Macros; + SmallVector<std::pair<llvm::Regex, TokenType>> MacroPatterns; llvm::SmallPtrSet<IdentifierInfo *, 8> MacrosSkippedByRemoveParentheses, TemplateNames, TypeNames, VariableTemplates; diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 9bbce9552bb9d..efce9fdf54db6 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -2115,13 +2115,14 @@ class AnnotatingParser { if (!CurrentToken->isTypeFinalized() && CurrentToken->isNoneOf( TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro, - TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace, - TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow, - TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator, - TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral, - TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro, - TT_FunctionLikeOrFreestandingMacro, TT_ClassLBrace, TT_EnumLBrace, - TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause, + TT_ForEachMacro, TT_TypenameMacro, TT_StatementMacro, + TT_FunctionLBrace, TT_ImplicitStringLiteral, TT_InlineASMBrace, + TT_FatArrow, TT_LambdaArrow, TT_NamespaceMacro, + TT_OverloadedOperator, TT_RegexLiteral, TT_TemplateString, + TT_ObjCStringLiteral, TT_UntouchableMacroFunc, + TT_StatementAttributeLikeMacro, TT_FunctionLikeOrFreestandingMacro, + TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace, TT_StructLBrace, + TT_UnionLBrace, TT_RequiresClause, TT_RequiresClauseInARequiresExpression, TT_RequiresExpression, TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace, TT_CompoundRequirementLBrace, TT_BracedListLBrace, diff --git a/clang/unittests/Format/ConfigParseTest.cpp b/clang/unittests/Format/ConfigParseTest.cpp index c7903d3cc5187..41bfb92fb3e23 100644 --- a/clang/unittests/Format/ConfigParseTest.cpp +++ b/clang/unittests/Format/ConfigParseTest.cpp @@ -1401,6 +1401,38 @@ TEST(ConfigParseTest, ParsesConfiguration) { HexMinDigitsInsert, 5); } +TEST(ConfigParseTest, ParseMacroRegex) { + FormatStyle Style = {}; + Style.Language = FormatStyle::LK_Cpp; + EXPECT_EQ(parseConfiguration("ForEachMacros: [\"^FOREACH_.*$\"]", &Style), + ParseError::Success); + ASSERT_EQ(Style.ForEachMacros.size(), 1u); + EXPECT_EQ(Style.ForEachMacros[0], "^FOREACH_.*$"); +} + +TEST(ConfigParseTest, ReportsEveryInvalidMacroRegex) { + FormatStyle Style = {}; + Style.Language = FormatStyle::LK_Cpp; + std::vector<std::string> Messages; + auto Handler = [](const llvm::SMDiagnostic &D, void *Ctx) { + static_cast<std::vector<std::string> *>(Ctx)->push_back( + D.getMessage().str()); + }; + EXPECT_EQ(parseConfiguration( + llvm::MemoryBufferRef("ForEachMacros: [\"a(\", \"b[\"]\n" + "IfMacros: [\"c(\"]", + "YAML"), + &Style, /*AllowUnknownOptions=*/false, Handler, &Messages), + std::make_error_code(std::errc::invalid_argument)); + ASSERT_EQ(Messages.size(), 3u); + EXPECT_TRUE(StringRef(Messages[0]) + .starts_with("Invalid regex pattern in ForEachMacros: a(")); + EXPECT_TRUE(StringRef(Messages[1]) + .starts_with("Invalid regex pattern in ForEachMacros: b[")); + EXPECT_TRUE(StringRef(Messages[2]) + .starts_with("Invalid regex pattern in IfMacros: c(")); +} + TEST(ConfigParseTest, ParsesConfigurationWithLanguages) { FormatStyle Style = {}; Style.Language = FormatStyle::LK_Cpp; diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 2534dba281bd8..b0f8f14da8231 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -4672,6 +4672,56 @@ TEST_F(TokenAnnotatorTest, CSharpUtf8StringLiterals) { EXPECT_TOKEN(Tokens[4], tok::identifier, TT_Unknown); } +TEST_F(TokenAnnotatorTest, MacroPatternBothMatch) { + auto Style = getLLVMStyle(); + Style.TypenameMacros = {"typename.*"}; + + auto Tokens = annotate("my_typename_alpha", Style); + ASSERT_EQ(Tokens.size(), 2u) << Tokens; + EXPECT_TOKEN(Tokens[0], tok::identifier, TT_TypenameMacro); +} + +TEST_F(TokenAnnotatorTest, MacroPatternForEach) { + auto Style = getLLVMStyle(); + Style.ForEachMacros = {"^FOREACH_.*$"}; + + auto Tokens = annotate("FOREACH_ITEM(a, b);", Style); + ASSERT_EQ(Tokens.size(), 8u) << Tokens; + EXPECT_TOKEN(Tokens[0], tok::identifier, TT_ForEachMacro); +} + +TEST_F(TokenAnnotatorTest, MacroPatternExactNameWins) { + auto Style = getLLVMStyle(); + Style.ForEachMacros = {"^.*_begin$"}; + Style.StatementMacros = {"SPECIAL_begin"}; + + auto Tokens = annotate("SPECIAL_begin(x);", Style); + ASSERT_EQ(Tokens.size(), 6u) << Tokens; + EXPECT_TOKEN(Tokens[0], tok::identifier, TT_StatementMacro); + + Tokens = annotate("OTHER_begin(x);", Style); + ASSERT_EQ(Tokens.size(), 6u) << Tokens; + EXPECT_TOKEN(Tokens[0], tok::identifier, TT_ForEachMacro); +} + +TEST_F(TokenAnnotatorTest, MacroPatternIgnoresKeywords) { + auto Style = getLLVMStyle(); + Style.ForEachMacros = {"^i.$"}; + + auto Tokens = annotate("if (x) {}", Style); + ASSERT_EQ(Tokens.size(), 7u) << Tokens; + EXPECT_NE(Tokens[0]->getType(), TT_ForEachMacro); +} + +TEST_F(TokenAnnotatorTest, MacroPatternSkipsDefineName) { + auto Style = getLLVMStyle(); + Style.ForEachMacros = {"^FOREACH_.*$"}; + + auto Tokens = annotate("#define FOREACH_X(a) a", Style); + ASSERT_EQ(Tokens.size(), 8u) << Tokens; + EXPECT_NE(Tokens[2]->getType(), TT_ForEachMacro); +} + } // namespace } // namespace format } // namespace clang _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
