[clang] [clang-format] Correctly handle C# new modifier (PR #137430)
Owen Pan via cfe-commits
cfe-commits at lists.llvm.org
Fri Apr 25 18:44:30 PDT 2025
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/137430
Fix #75815
>From f02cb0bca31a46e815fa3bc8df8a18d9757e5020 Mon Sep 17 00:00:00 2001
From: Owen Pan <owenpiano at gmail.com>
Date: Fri, 25 Apr 2025 18:41:48 -0700
Subject: [PATCH] [clang-format] Correctly handle C# new modifier
Fix #75815
---
clang/lib/Format/UnwrappedLineParser.cpp | 8 +++++++-
clang/unittests/Format/FormatTestCSharp.cpp | 7 +++++++
clang/unittests/Format/TokenAnnotatorTest.cpp | 11 +++++++++++
3 files changed, 25 insertions(+), 1 deletion(-)
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index 9e86d9b19afb8..c7ad9962eb77f 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2089,7 +2089,13 @@ void UnwrappedLineParser::parseStructuralElement(
parseSquare();
break;
case tok::kw_new:
- parseNew();
+ if (Style.isCSharp() &&
+ (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
+ (Previous && Previous->isAccessSpecifierKeyword()))) {
+ nextToken();
+ } else {
+ parseNew();
+ }
break;
case tok::kw_switch:
if (Style.isJava())
diff --git a/clang/unittests/Format/FormatTestCSharp.cpp b/clang/unittests/Format/FormatTestCSharp.cpp
index dae362c37b52b..ea85ed6140dd0 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -689,6 +689,13 @@ TEST_F(FormatTestCSharp, CSharpNewOperator) {
Style);
}
+TEST_F(FormatTestCSharp, NewModifier) {
+ verifyFormat("public new class NestedC {\n"
+ " public int x = 100;\n"
+ "}",
+ getLLVMStyle(FormatStyle::LK_CSharp));
+}
+
TEST_F(FormatTestCSharp, CSharpLambdas) {
FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 8d4aeb7dec89a..08216dd971ac4 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3109,6 +3109,17 @@ TEST_F(TokenAnnotatorTest, CSharpGenericTypeConstraint) {
EXPECT_TOKEN(Tokens[18], tok::r_brace, TT_NamespaceRBrace);
}
+TEST_F(TokenAnnotatorTest, CSharpNewModifier) {
+ auto Tokens = annotate("new public class NestedC {\n"
+ " public int x = 100;\n"
+ "}",
+ getGoogleStyle(FormatStyle::LK_CSharp));
+ ASSERT_EQ(Tokens.size(), 13u) << Tokens;
+ EXPECT_TOKEN(Tokens[3], tok::identifier, TT_ClassHeadName);
+ EXPECT_TOKEN(Tokens[4], tok::l_brace, TT_ClassLBrace);
+ EXPECT_TOKEN(Tokens[11], tok::r_brace, TT_ClassRBrace);
+}
+
TEST_F(TokenAnnotatorTest, UnderstandsLabels) {
auto Tokens = annotate("{ x: break; }");
ASSERT_EQ(Tokens.size(), 7u) << Tokens;
More information about the cfe-commits
mailing list