[clang] [clang-format] Fix clang-format issue with 'new' and 'delete' keywords in C files (PR #85470)

via cfe-commits cfe-commits at lists.llvm.org
Fri Mar 15 14:53:00 PDT 2024


https://github.com/scythris updated https://github.com/llvm/llvm-project/pull/85470

>From 451a664dc3d325deff54ff7d582b0063569f54cd Mon Sep 17 00:00:00 2001
From: Trym Strand <trym.strand at hotmail.no>
Date: Fri, 15 Mar 2024 21:56:22 +0100
Subject: [PATCH] Fix clang-format issue with 'new' and 'delete' keywords in C
 files

This patch resolves an issue in clang-format where 'new' and 'delete' were incorrectly recognized as keywords in C files. The fix modifies the TokenAnnotator::spaceRequiredBetween to correctly handle 'new' and 'delete' as an identifier in C code, preventing incorrect formatting.
---
 clang/lib/Format/TokenAnnotator.cpp   | 2 +-
 clang/unittests/Format/FormatTest.cpp | 5 +++++
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index e464c2b5731a35..c58204ce33ae52 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4607,7 +4607,7 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
       return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
              spaceRequiredBeforeParens(Right);
     }
-    if (!Left.Previous || Left.Previous->isNot(tok::period)) {
+    if (!Left.Previous || !Left.Previous->isOneOf(tok::period, tok::arrow)) {
       if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
         return Style.SpaceBeforeParensOptions.AfterControlStatements ||
                spaceRequiredBeforeParens(Right);
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index fc367a7a5a8981..a6f9a0941cb040 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11450,6 +11450,11 @@ TEST_F(FormatTest, UnderstandsNewAndDelete) {
                "void new (link p);\n"
                "void delete (link p);");
 
+  verifyFormat("{ p->delete(); }\n"
+               "{ p->new(); }",
+               "{ p->delete (); }\n"
+               "{ p->new (); }");
+
   FormatStyle AfterPlacementOperator = getLLVMStyle();
   AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
   EXPECT_TRUE(



More information about the cfe-commits mailing list