[clang] [clang-format] Fix crashes when the macro expansion is empty (PR #119428)

via cfe-commits cfe-commits at lists.llvm.org
Sat Dec 14 23:15:36 PST 2024


https://github.com/amane-ame updated https://github.com/llvm/llvm-project/pull/119428

>From 3a4c1a924faef3a7a09126694fcb943bd7083451 Mon Sep 17 00:00:00 2001
From: amane-ame <i at amane-a.me>
Date: Wed, 11 Dec 2024 02:13:43 +0800
Subject: [PATCH 1/2] Fix crashes when the macro expansion is empty

---
 clang/lib/Format/MacroExpander.cpp | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/clang/lib/Format/MacroExpander.cpp b/clang/lib/Format/MacroExpander.cpp
index fd2a16894d643d..ed9e51dfbfef1f 100644
--- a/clang/lib/Format/MacroExpander.cpp
+++ b/clang/lib/Format/MacroExpander.cpp
@@ -233,6 +233,10 @@ MacroExpander::expand(FormatToken *ID,
   if (Result.size() > 1) {
     ++Result[0]->MacroCtx->StartOfExpansion;
     ++Result[Result.size() - 2]->MacroCtx->EndOfExpansion;
+  } else {
+    // If the macro expansion is empty, mark the start and end
+    Result[0]->MacroCtx->StartOfExpansion = 1;
+    Result[0]->MacroCtx->EndOfExpansion = 1;
   }
   return Result;
 }

>From 8bf68f87b897bab9da9464d594082be5012afdb1 Mon Sep 17 00:00:00 2001
From: amane-ame <i at amane-a.me>
Date: Sun, 15 Dec 2024 15:15:17 +0800
Subject: [PATCH 2/2] [clang-format] Add a testcase for empty macro

---
 clang/test/Format/empty-macro.cpp | 5 +++++
 1 file changed, 5 insertions(+)
 create mode 100644 clang/test/Format/empty-macro.cpp

diff --git a/clang/test/Format/empty-macro.cpp b/clang/test/Format/empty-macro.cpp
new file mode 100644
index 00000000000000..81b255219b0c2b
--- /dev/null
+++ b/clang/test/Format/empty-macro.cpp
@@ -0,0 +1,5 @@
+// RUN: grep -Ev "// *[A-Z-]+:" %s | clang-format -style="{Macros: [A(x)=x]}" \
+// RUN:   | FileCheck -strict-whitespace %s
+
+// CHECK: A()
+A()



More information about the cfe-commits mailing list