[clang] [clang-format] Fix a bug in annotating `*` in `#define`s (PR #99433)

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Wed Jul 17 22:34:20 PDT 2024


https://github.com/owenca created https://github.com/llvm/llvm-project/pull/99433

Fixes #99271.

>From ebf25d890ff47be48bd153942d943906943a247b Mon Sep 17 00:00:00 2001
From: Owen Pan <owenpiano at gmail.com>
Date: Wed, 17 Jul 2024 22:30:21 -0700
Subject: [PATCH] [clang-format] Fix a bug in annotating `*` in `#define`s

Fixes #99271.
---
 clang/lib/Format/TokenAnnotator.cpp           | 3 ++-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 4 ++++
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index b6d6e52ccb8f8..f1125fd35b427 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -374,7 +374,8 @@ class AnnotatingParser {
       Contexts.back().IsExpression = true;
     } else if (Line.InPPDirective &&
                (!OpeningParen.Previous ||
-                OpeningParen.Previous->isNot(tok::identifier))) {
+                OpeningParen.Previous->isNot(tok::identifier) ||
+                !OpeningParen.Previous->Previous)) {
       Contexts.back().IsExpression = true;
     } else if (Contexts[Contexts.size() - 2].CaretFound) {
       // This is the parameter list of an ObjC block.
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index c5e8aa72cd2cb..82c9be0f4df71 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -75,6 +75,10 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::star, TT_PointerOrReference);
 
+  Tokens = annotate("#define FOO bar(a * b)");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::star, TT_BinaryOperator);
+
   Tokens = annotate("void f() {\n"
                     "  while (p < a && *p == 'a')\n"
                     "    p++;\n"



More information about the cfe-commits mailing list