[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:36:53 PDT 2024


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

This resolves an issue in clang-format where `new` and `delete` were incorrectly formatted as keywords in C files. The fix modifies `TokenAnnotator::spaceRequiredBetween` to handle `new` and `delete` when used as identifiers for function pointers in structs in C code.

>From 1e815bb2090f7747da027a04f69906063db7b02a 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 'delete' keyword in C files

This patch resolves an issue in clang-format where 'delete' was incorrectly recognized as a keyword in C files. The fix modifies the TokenAnnotator rules to correctly handle '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..410e08ea589692 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11449,6 +11449,11 @@ TEST_F(FormatTest, UnderstandsNewAndDelete) {
                "void delete(link p);",
                "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;



More information about the cfe-commits mailing list