[clang] [clang-format] Correctly handle C# new modifier (PR #137430)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Apr 25 18:45:01 PDT 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-format
Author: Owen Pan (owenca)
<details>
<summary>Changes</summary>
Fix #<!-- -->75815
---
Full diff: https://github.com/llvm/llvm-project/pull/137430.diff
3 Files Affected:
- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+7-1)
- (modified) clang/unittests/Format/FormatTestCSharp.cpp (+7)
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+11)
``````````diff
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;
``````````
</details>
https://github.com/llvm/llvm-project/pull/137430
More information about the cfe-commits
mailing list