[clang] [clang-format] Fix parsing attrs in class/struct (PR #124634)

via cfe-commits cfe-commits at lists.llvm.org
Mon Jan 27 13:55:41 PST 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-format

Author: Gedare Bloom (gedare)

<details>
<summary>Changes</summary>

An attribute in a class/struct declaration confuses the parser to treat the identifier following the attribute as a function or variable name.

Fixes #<!-- -->124574

---
Full diff: https://github.com/llvm/llvm-project/pull/124634.diff


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+11-3) 
- (modified) clang/unittests/Format/FormatTest.cpp (+12) 


``````````diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 08fda7a2ffa51a..3b4b0b78e8bf16 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2633,12 +2633,20 @@ class AnnotatingParser {
              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
     }
 
-    if ((PreviousNotConst->is(tok::r_paren) &&
-         PreviousNotConst->is(TT_TypeDeclarationParen)) ||
-        PreviousNotConst->is(TT_AttributeRParen)) {
+    if (PreviousNotConst->is(tok::r_paren) &&
+        PreviousNotConst->is(TT_TypeDeclarationParen)) {
       return true;
     }
 
+    auto InTypeDecl = [&]() {
+      for (auto Next = Tok.Next; Next; Next = Next->Next)
+        if (Next->isOneOf(TT_ClassLBrace, TT_StructLBrace))
+          return true;
+      return false;
+    };
+    if (PreviousNotConst->is(TT_AttributeRParen) && (!IsCpp || !InTypeDecl()))
+      return true;
+
     // If is a preprocess keyword like #define.
     if (IsPPKeyword)
       return false;
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 265461561d2012..6145500a56582a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -12415,6 +12415,18 @@ TEST_F(FormatTest, UnderstandsAttributes) {
   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
+
+  FormatStyle Style = getLLVMStyle(FormatStyle::LK_Cpp);
+  verifyFormat(
+      "template <>\n"
+      "struct __declspec(uuid(\"3895C200-8F26-4F5A-B29D-2B5D72E68F99\"))\n"
+      "IAsyncOperation<IUnknown *> : IAsyncOperation_impl<IUnknown *> {};",
+      Style);
+  verifyFormat(
+      "template <>\n"
+      "class __declspec(uuid(\"3895C200-8F26-4F5A-B29D-2B5D72E68F99\"))\n"
+      "IAsyncOperation<IUnknown *> : IAsyncOperation_impl<IUnknown *> {};",
+      Style);
 }
 
 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {

``````````

</details>


https://github.com/llvm/llvm-project/pull/124634


More information about the cfe-commits mailing list