diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 3dc88315c35238..f6df58dac2d663 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -2873,6 +2873,13 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, if (Left.is(tok::kw_using)) return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements || spaceRequiredBeforeParens(Right); + // space between ']' and '{' + if (Left.is(tok::r_square) && Right.is(tok::l_brace)) + return true; + // space before '{' in "new MyType {" + if (Right.is(tok::l_brace) && Left.Previous && + Left.Previous->is(tok::kw_new)) + return true; } else if (Style.Language == FormatStyle::LK_JavaScript) { if (Left.is(TT_JsFatArrow)) return true; diff --git a/clang/unittests/Format/FormatTestCSharp.cpp b/clang/unittests/Format/FormatTestCSharp.cpp index 3d1b597174d832..5d1131aa0c3a6e 100644 --- a/clang/unittests/Format/FormatTestCSharp.cpp +++ b/clang/unittests/Format/FormatTestCSharp.cpp @@ -457,5 +457,34 @@ var x = foo(className, $@"some code: EXPECT_EQ(Code, format(Code, Style)); } +TEST_F(FormatTestCSharp, CSharpObjectInitializers) { + FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); + + // Start code fragemnts with a comment line so that C++ raw string literals + // as seen are identical to expected formatted code. + + verifyFormat(R"(// +Shape[] shapes = new[] { + new Circle { + Radius = 2.7281, + Colour = Colours.Red, + }, + new Square { + Side = 101.1, + Colour = Colours.Yellow, + }, +};)", + Style); + + // Omitted final `,`s will change the formatting. + verifyFormat(R"(// +Shape[] shapes = new[] {new Circle {Radius = 2.7281, Colour = Colours.Red}, + new Square { + Side = 101.1, + Colour = Colours.Yellow, + }};)", + Style); +} + } // namespace format } // end namespace clang