1 //===- unittest/Format/FormatTestCSharp.cpp - Formatting tests for CSharp -===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "FormatTestUtils.h" 10 #include "clang/Format/Format.h" 11 #include "llvm/Support/Debug.h" 12 #include "gtest/gtest.h" 13 14 #define DEBUG_TYPE "format-test" 15 16 namespace clang { 17 namespace format { 18 19 class FormatTestCSharp : public ::testing::Test { 20 protected: 21 static std::string format(llvm::StringRef Code, unsigned Offset, 22 unsigned Length, const FormatStyle &Style) { 23 LLVM_DEBUG(llvm::errs() << "---\n"); 24 LLVM_DEBUG(llvm::errs() << Code << "\n\n"); 25 std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length)); 26 tooling::Replacements Replaces = reformat(Style, Code, Ranges); 27 auto Result = applyAllReplacements(Code, Replaces); 28 EXPECT_TRUE(static_cast<bool>(Result)); 29 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); 30 return *Result; 31 } 32 33 static std::string 34 format(llvm::StringRef Code, 35 const FormatStyle &Style = getMicrosoftStyle(FormatStyle::LK_CSharp)) { 36 return format(Code, 0, Code.size(), Style); 37 } 38 39 static FormatStyle getStyleWithColumns(unsigned ColumnLimit) { 40 FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_CSharp); 41 Style.ColumnLimit = ColumnLimit; 42 return Style; 43 } 44 45 static void verifyFormat( 46 llvm::StringRef Code, 47 const FormatStyle &Style = getMicrosoftStyle(FormatStyle::LK_CSharp)) { 48 EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not stable"; 49 EXPECT_EQ(Code.str(), format(test::messUp(Code), Style)); 50 } 51 }; 52 53 TEST_F(FormatTestCSharp, CSharpClass) { 54 verifyFormat("public class SomeClass\n" 55 "{\n" 56 " void f()\n" 57 " {\n" 58 " }\n" 59 " int g()\n" 60 " {\n" 61 " return 0;\n" 62 " }\n" 63 " void h()\n" 64 " {\n" 65 " while (true)\n" 66 " f();\n" 67 " for (;;)\n" 68 " f();\n" 69 " if (true)\n" 70 " f();\n" 71 " }\n" 72 "}"); 73 74 // Ensure that small and empty classes are handled correctly with condensed 75 // (Google C++-like) brace-breaking style. 76 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 77 Style.BreakBeforeBraces = FormatStyle::BS_Attach; 78 79 verifyFormat("public class SomeEmptyClass {}", Style); 80 81 verifyFormat("public class SomeTinyClass {\n" 82 " int X;\n" 83 "}", 84 Style); 85 verifyFormat("private class SomeTinyClass {\n" 86 " int X;\n" 87 "}", 88 Style); 89 verifyFormat("protected class SomeTinyClass {\n" 90 " int X;\n" 91 "}", 92 Style); 93 verifyFormat("internal class SomeTinyClass {\n" 94 " int X;\n" 95 "}", 96 Style); 97 } 98 99 TEST_F(FormatTestCSharp, AccessModifiers) { 100 verifyFormat("public String toString()\n" 101 "{\n" 102 "}"); 103 verifyFormat("private String toString()\n" 104 "{\n" 105 "}"); 106 verifyFormat("protected String toString()\n" 107 "{\n" 108 "}"); 109 verifyFormat("internal String toString()\n" 110 "{\n" 111 "}"); 112 113 verifyFormat("public override String toString()\n" 114 "{\n" 115 "}"); 116 verifyFormat("private override String toString()\n" 117 "{\n" 118 "}"); 119 verifyFormat("protected override String toString()\n" 120 "{\n" 121 "}"); 122 verifyFormat("internal override String toString()\n" 123 "{\n" 124 "}"); 125 126 verifyFormat("internal static String toString()\n" 127 "{\n" 128 "}"); 129 } 130 131 TEST_F(FormatTestCSharp, NoStringLiteralBreaks) { 132 verifyFormat("foo(" 133 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 134 "aaaaaa\");"); 135 } 136 137 TEST_F(FormatTestCSharp, CSharpVerbatiumStringLiterals) { 138 verifyFormat("foo(@\"aaaaaaaa\\abc\\aaaa\");"); 139 // @"ABC\" + ToString("B") - handle embedded \ in literal string at 140 // the end 141 // 142 /* 143 * After removal of Lexer change we are currently not able 144 * To handle these cases 145 verifyFormat("string s = @\"ABC\\\" + ToString(\"B\");"); 146 verifyFormat("string s = @\"ABC\"\"DEF\"\"GHI\""); 147 verifyFormat("string s = @\"ABC\"\"DEF\"\"\""); 148 verifyFormat("string s = @\"ABC\"\"DEF\"\"\" + abc"); 149 */ 150 } 151 152 TEST_F(FormatTestCSharp, CSharpInterpolatedStringLiterals) { 153 verifyFormat("foo($\"aaaaaaaa{aaa}aaaa\");"); 154 verifyFormat("foo($\"aaaa{A}\");"); 155 verifyFormat( 156 "foo($\"aaaa{A}" 157 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\");"); 158 verifyFormat("Name = $\"{firstName} {lastName}\";"); 159 160 // $"ABC\" + ToString("B") - handle embedded \ in literal string at 161 // the end 162 verifyFormat("string s = $\"A{abc}BC\" + ToString(\"B\");"); 163 verifyFormat("$\"{domain}\\\\{user}\""); 164 verifyFormat( 165 "var verbatimInterpolated = $@\"C:\\Users\\{userName}\\Documents\\\";"); 166 } 167 168 TEST_F(FormatTestCSharp, CSharpFatArrows) { 169 verifyFormat("Task serverTask = Task.Run(async() => {"); 170 verifyFormat("public override string ToString() => \"{Name}\\{Age}\";"); 171 } 172 173 TEST_F(FormatTestCSharp, CSharpConditionalExpressions) { 174 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 175 // conditional expression is not seen as a NullConditional. 176 verifyFormat("var y = A < B ? -1 : 1;", Style); 177 } 178 179 TEST_F(FormatTestCSharp, CSharpNullConditional) { 180 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 181 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 182 183 verifyFormat( 184 "public Person(string firstName, string lastName, int? age = null)"); 185 186 verifyFormat("foo () {\n" 187 " switch (args?.Length) {}\n" 188 "}", 189 Style); 190 191 verifyFormat("switch (args?.Length) {}", Style); 192 193 verifyFormat("public static void Main(string[] args)\n" 194 "{\n" 195 " string dirPath = args?[0];\n" 196 "}"); 197 198 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 199 200 verifyFormat("switch(args?.Length) {}", Style); 201 } 202 203 TEST_F(FormatTestCSharp, Attributes) { 204 verifyFormat("[STAThread]\n" 205 "static void Main(string[] args)\n" 206 "{\n" 207 "}"); 208 209 verifyFormat("[TestMethod]\n" 210 "private class Test\n" 211 "{\n" 212 "}"); 213 214 verifyFormat("[TestMethod]\n" 215 "protected class Test\n" 216 "{\n" 217 "}"); 218 219 verifyFormat("[TestMethod]\n" 220 "internal class Test\n" 221 "{\n" 222 "}"); 223 224 verifyFormat("[TestMethod]\n" 225 "class Test\n" 226 "{\n" 227 "}"); 228 229 verifyFormat("[TestMethod]\n" 230 "[DeploymentItem(\"Test.txt\")]\n" 231 "public class Test\n" 232 "{\n" 233 "}"); 234 235 verifyFormat("[System.AttributeUsage(System.AttributeTargets.Method)]\n" 236 "[System.Runtime.InteropServices.ComVisible(true)]\n" 237 "public sealed class STAThreadAttribute : Attribute\n" 238 "{\n" 239 "}"); 240 241 verifyFormat("[Verb(\"start\", HelpText = \"Starts the server listening on " 242 "provided port\")]\n" 243 "class Test\n" 244 "{\n" 245 "}"); 246 247 verifyFormat("[TestMethod]\n" 248 "public string Host { set; get; }"); 249 250 // Adjacent properties should not cause line wrapping issues 251 verifyFormat("[JsonProperty(\"foo\")]\n" 252 "public string Foo { set; get; }\n" 253 "[JsonProperty(\"bar\")]\n" 254 "public string Bar { set; get; }\n" 255 "[JsonProperty(\"bar\")]\n" 256 "protected string Bar { set; get; }\n" 257 "[JsonProperty(\"bar\")]\n" 258 "internal string Bar { set; get; }"); 259 260 // Multiple attributes should always be split (not just the first ones) 261 verifyFormat("[XmlIgnore]\n" 262 "[JsonProperty(\"foo\")]\n" 263 "public string Foo { set; get; }"); 264 265 verifyFormat("[XmlIgnore]\n" 266 "[JsonProperty(\"foo\")]\n" 267 "public string Foo { set; get; }\n" 268 "[XmlIgnore]\n" 269 "[JsonProperty(\"bar\")]\n" 270 "public string Bar { set; get; }"); 271 272 verifyFormat("[XmlIgnore]\n" 273 "[ScriptIgnore]\n" 274 "[JsonProperty(\"foo\")]\n" 275 "public string Foo { set; get; }\n" 276 "[XmlIgnore]\n" 277 "[ScriptIgnore]\n" 278 "[JsonProperty(\"bar\")]\n" 279 "public string Bar { set; get; }"); 280 281 verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server " 282 "listening on provided host\")]\n" 283 "public string Host { set; get; }"); 284 285 verifyFormat( 286 "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n" 287 "// The const char* returned by hello_world must not be deleted.\n" 288 "private static extern IntPtr HelloFromCpp();)"); 289 290 // Class attributes go on their own line and do not affect layout of 291 // interfaces. Line wrapping decisions previously caused each interface to be 292 // on its own line. 293 verifyFormat("[SomeAttribute]\n" 294 "[SomeOtherAttribute]\n" 295 "public class A : IShape, IAnimal, IVehicle\n" 296 "{\n" 297 " int X;\n" 298 "}"); 299 300 // Attributes in a method declaration do not cause line wrapping. 301 verifyFormat("void MethodA([In][Out] ref double x)\n" 302 "{\n" 303 "}"); 304 305 verifyFormat("void MethodA([In, Out] ref double x)\n" 306 "{\n" 307 "}"); 308 309 verifyFormat("void MethodA([In, Out] double[] x)\n" 310 "{\n" 311 "}"); 312 313 verifyFormat("void MethodA([In] double[] x)\n" 314 "{\n" 315 "}"); 316 317 verifyFormat("void MethodA(int[] x)\n" 318 "{\n" 319 "}"); 320 verifyFormat("void MethodA(int[][] x)\n" 321 "{\n" 322 "}"); 323 verifyFormat("void MethodA([] x)\n" 324 "{\n" 325 "}"); 326 327 verifyFormat("public void Log([CallerLineNumber] int line = -1, " 328 "[CallerFilePath] string path = null,\n" 329 " [CallerMemberName] string name = null)\n" 330 "{\n" 331 "}"); 332 333 // [] in an attribute do not cause premature line wrapping or indenting. 334 verifyFormat(R"(// 335 public class A 336 { 337 [SomeAttribute(new[] { RED, GREEN, BLUE }, -1.0f, 1.0f)] 338 [DoNotSerialize] 339 public Data MemberVariable; 340 })"); 341 342 // Unwrappable lines go on a line of their own. 343 // 'target:' is not treated as a label. 344 // Modify Style to enforce a column limit. 345 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 346 Style.ColumnLimit = 10; 347 verifyFormat(R"([assembly:InternalsVisibleTo( 348 "SomeAssembly, PublicKey=SomePublicKeyThatExceedsTheColumnLimit")])", 349 Style); 350 } 351 352 TEST_F(FormatTestCSharp, CSharpUsing) { 353 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 354 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 355 verifyFormat("public void foo () {\n" 356 " using (StreamWriter sw = new StreamWriter (filenameA)) {}\n" 357 " using () {}\n" 358 "}", 359 Style); 360 361 // Ensure clang-format affects top-level snippets correctly. 362 verifyFormat("using (StreamWriter sw = new StreamWriter (filenameB)) {}", 363 Style); 364 365 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 366 verifyFormat("public void foo() {\n" 367 " using(StreamWriter sw = new StreamWriter(filenameB)) {}\n" 368 " using() {}\n" 369 "}", 370 Style); 371 372 // Ensure clang-format affects top-level snippets correctly. 373 verifyFormat("using(StreamWriter sw = new StreamWriter(filenameB)) {}", 374 Style); 375 376 Style.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements; 377 verifyFormat("public void foo() {\n" 378 " using (StreamWriter sw = new StreamWriter(filenameA)) {}\n" 379 " using () {}\n" 380 "}", 381 Style); 382 383 // Ensure clang-format affects top-level snippets correctly. 384 verifyFormat("using (StreamWriter sw = new StreamWriter(filenameB)) {}", 385 Style); 386 387 Style.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 388 verifyFormat("public void foo() {\n" 389 " using (StreamWriter sw = new StreamWriter (filenameA)) {}\n" 390 " using() {}\n" 391 "}", 392 Style); 393 394 // Ensure clang-format affects top-level snippets correctly. 395 verifyFormat("using (StreamWriter sw = new StreamWriter (filenameB)) {}", 396 Style); 397 } 398 399 TEST_F(FormatTestCSharp, CSharpRegions) { 400 verifyFormat("#region aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa " 401 "aaaaaaaaaaaaaaa long region"); 402 } 403 404 TEST_F(FormatTestCSharp, CSharpKeyWordEscaping) { 405 verifyFormat("public enum var {\n" 406 " none,\n" 407 " @string,\n" 408 " bool,\n" 409 " @enum\n" 410 "}"); 411 } 412 413 TEST_F(FormatTestCSharp, CSharpNullCoalescing) { 414 verifyFormat("var test = ABC ?? DEF"); 415 verifyFormat("string myname = name ?? \"ABC\";"); 416 verifyFormat("return _name ?? \"DEF\";"); 417 } 418 419 TEST_F(FormatTestCSharp, CSharpNullCoalescingAssignment) { 420 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 421 Style.SpaceBeforeAssignmentOperators = true; 422 423 verifyFormat(R"(test ??= ABC;)", Style); 424 verifyFormat(R"(test ??= true;)", Style); 425 426 Style.SpaceBeforeAssignmentOperators = false; 427 428 verifyFormat(R"(test??= ABC;)", Style); 429 verifyFormat(R"(test??= true;)", Style); 430 } 431 432 TEST_F(FormatTestCSharp, CSharpNullForgiving) { 433 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 434 435 verifyFormat("var test = null!;", Style); 436 verifyFormat("string test = someFunctionCall()! + \"ABC\"!", Style); 437 verifyFormat("int test = (1! + 2 + bar! + foo())!", Style); 438 verifyFormat(R"(test ??= !foo!;)", Style); 439 verifyFormat("test = !bar! ?? !foo!;", Style); 440 verifyFormat("bool test = !(!true && !true! || !null && !null! || !false && " 441 "!false! && !bar()! + (!foo()))!", 442 Style); 443 444 // Check that line break keeps identifier with the bang. 445 Style.ColumnLimit = 14; 446 447 verifyFormat("var test =\n" 448 " foo!;", 449 Style); 450 } 451 452 TEST_F(FormatTestCSharp, AttributesIndentation) { 453 FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_CSharp); 454 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 455 456 verifyFormat("[STAThread]\n" 457 "static void Main(string[] args)\n" 458 "{\n" 459 "}", 460 Style); 461 462 verifyFormat("[STAThread]\n" 463 "void " 464 "veryLooooooooooooooongFunctionName(string[] args)\n" 465 "{\n" 466 "}", 467 Style); 468 469 verifyFormat("[STAThread]\n" 470 "veryLoooooooooooooooooooongReturnType " 471 "veryLooooooooooooooongFunctionName(string[] args)\n" 472 "{\n" 473 "}", 474 Style); 475 476 verifyFormat("[SuppressMessage(\"A\", \"B\", Justification = \"C\")]\n" 477 "public override X Y()\n" 478 "{\n" 479 "}\n", 480 Style); 481 482 verifyFormat("[SuppressMessage]\n" 483 "public X Y()\n" 484 "{\n" 485 "}\n", 486 Style); 487 488 verifyFormat("[SuppressMessage]\n" 489 "public override X Y()\n" 490 "{\n" 491 "}\n", 492 Style); 493 494 verifyFormat("public A(B b) : base(b)\n" 495 "{\n" 496 " [SuppressMessage]\n" 497 " public override X Y()\n" 498 " {\n" 499 " }\n" 500 "}\n", 501 Style); 502 503 verifyFormat("public A : Base\n" 504 "{\n" 505 "}\n" 506 "[Test]\n" 507 "public Foo()\n" 508 "{\n" 509 "}\n", 510 Style); 511 512 verifyFormat("namespace\n" 513 "{\n" 514 "public A : Base\n" 515 "{\n" 516 "}\n" 517 "[Test]\n" 518 "public Foo()\n" 519 "{\n" 520 "}\n" 521 "}\n", 522 Style); 523 } 524 525 TEST_F(FormatTestCSharp, CSharpSpaceBefore) { 526 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 527 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 528 529 verifyFormat("List<string> list;", Style); 530 verifyFormat("Dictionary<string, string> dict;", Style); 531 532 verifyFormat("for (int i = 0; i < size (); i++) {\n" 533 "}", 534 Style); 535 verifyFormat("foreach (var x in y) {\n" 536 "}", 537 Style); 538 verifyFormat("switch (x) {}", Style); 539 verifyFormat("do {\n" 540 "} while (x);", 541 Style); 542 543 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 544 545 verifyFormat("List<string> list;", Style); 546 verifyFormat("Dictionary<string, string> dict;", Style); 547 548 verifyFormat("for(int i = 0; i < size(); i++) {\n" 549 "}", 550 Style); 551 verifyFormat("foreach(var x in y) {\n" 552 "}", 553 Style); 554 verifyFormat("switch(x) {}", Style); 555 verifyFormat("do {\n" 556 "} while(x);", 557 Style); 558 } 559 560 TEST_F(FormatTestCSharp, CSharpSpaceAfterCStyleCast) { 561 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 562 563 verifyFormat("(int)x / y;", Style); 564 565 Style.SpaceAfterCStyleCast = true; 566 verifyFormat("(int) x / y;", Style); 567 } 568 569 TEST_F(FormatTestCSharp, CSharpEscapedQuotesInVerbatimStrings) { 570 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 571 572 verifyFormat(R"(string str = @"""";)", Style); 573 verifyFormat(R"(string str = @"""Hello world""";)", Style); 574 verifyFormat(R"(string str = $@"""Hello {friend}""";)", Style); 575 } 576 577 TEST_F(FormatTestCSharp, CSharpQuotesInInterpolatedStrings) { 578 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 579 580 verifyFormat(R"(string str1 = $"{null ?? "null"}";)", Style); 581 verifyFormat(R"(string str2 = $"{{{braceCount} braces";)", Style); 582 verifyFormat(R"(string str3 = $"{braceCount}}} braces";)", Style); 583 } 584 585 TEST_F(FormatTestCSharp, CSharpNewlinesInVerbatimStrings) { 586 // Use MS style as Google Style inserts a line break before multiline strings. 587 588 // verifyFormat does not understand multiline C# string-literals 589 // so check the format explicitly. 590 591 FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_CSharp); 592 593 std::string Code = R"(string s1 = $@"some code: 594 class {className} {{ 595 {className}() {{}} 596 }}";)"; 597 598 EXPECT_EQ(Code, format(Code, Style)); 599 600 // Multiline string in the middle of a function call. 601 Code = R"( 602 var x = foo(className, $@"some code: 603 class {className} {{ 604 {className}() {{}} 605 }}", 606 y);)"; // y aligned with `className` arg. 607 608 EXPECT_EQ(Code, format(Code, Style)); 609 610 // Interpolated string with embedded multiline string. 611 Code = R"(Console.WriteLine($"{string.Join(@", 612 ", values)}");)"; 613 614 EXPECT_EQ(Code, format(Code, Style)); 615 } 616 617 TEST_F(FormatTestCSharp, CSharpLambdas) { 618 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp); 619 FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp); 620 621 verifyFormat(R"(// 622 class MyClass { 623 Action<string> greet = name => { 624 string greeting = $"Hello {name}!"; 625 Console.WriteLine(greeting); 626 }; 627 })", 628 GoogleStyle); 629 630 // Microsoft Style: 631 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions#statement-lambdas 632 verifyFormat(R"(// 633 class MyClass 634 { 635 Action<string> greet = name => 636 { 637 string greeting = $"Hello {name}!"; 638 Console.WriteLine(greeting); 639 }; 640 })", 641 MicrosoftStyle); 642 643 verifyFormat("void bar()\n" 644 "{\n" 645 " Function(Val, (Action)(() =>\n" 646 " {\n" 647 " lock (mylock)\n" 648 " {\n" 649 " if (true)\n" 650 " {\n" 651 " A.Remove(item);\n" 652 " }\n" 653 " }\n" 654 " }));\n" 655 "}", 656 MicrosoftStyle); 657 658 verifyFormat("void baz()\n" 659 "{\n" 660 " Function(Val, (Action)(() =>\n" 661 " {\n" 662 " using (var a = new Lock())\n" 663 " {\n" 664 " if (true)\n" 665 " {\n" 666 " A.Remove(item);\n" 667 " }\n" 668 " }\n" 669 " }));\n" 670 "}", 671 MicrosoftStyle); 672 673 verifyFormat("void baz()\n" 674 "{\n" 675 " Function(Val, (Action)(() =>\n" 676 " {\n" 677 " if (true)\n" 678 " {\n" 679 " A.Remove(item);\n" 680 " }\n" 681 " }));\n" 682 "}", 683 MicrosoftStyle); 684 685 verifyFormat("void baz()\n" 686 "{\n" 687 " Function(Val, (Action)(() =>\n" 688 " {\n" 689 " do\n" 690 " {\n" 691 " A.Remove(item);\n" 692 " } while (true)\n" 693 " }));\n" 694 "}", 695 MicrosoftStyle); 696 697 verifyFormat("void baz()\n" 698 "{\n" 699 " Function(Val, (Action)(() =>\n" 700 " { A.Remove(item); }));\n" 701 "}", 702 MicrosoftStyle); 703 704 verifyFormat("void bar()\n" 705 "{\n" 706 " Function(Val, (() =>\n" 707 " {\n" 708 " lock (mylock)\n" 709 " {\n" 710 " if (true)\n" 711 " {\n" 712 " A.Remove(item);\n" 713 " }\n" 714 " }\n" 715 " }));\n" 716 "}", 717 MicrosoftStyle); 718 verifyFormat("void bar()\n" 719 "{\n" 720 " Function((() =>\n" 721 " {\n" 722 " lock (mylock)\n" 723 " {\n" 724 " if (true)\n" 725 " {\n" 726 " A.Remove(item);\n" 727 " }\n" 728 " }\n" 729 " }));\n" 730 "}", 731 MicrosoftStyle); 732 733 MicrosoftStyle.IndentWidth = 2; 734 verifyFormat("void bar()\n" 735 "{\n" 736 " Function((() =>\n" 737 " {\n" 738 " lock (mylock)\n" 739 " {\n" 740 " if (true)\n" 741 " {\n" 742 " A.Remove(item);\n" 743 " }\n" 744 " }\n" 745 " }));\n" 746 "}", 747 MicrosoftStyle); 748 verifyFormat("void bar() {\n" 749 " Function((() => {\n" 750 " lock (mylock) {\n" 751 " if (true) {\n" 752 " A.Remove(item);\n" 753 " }\n" 754 " }\n" 755 " }));\n" 756 "}", 757 GoogleStyle); 758 } 759 760 TEST_F(FormatTestCSharp, CSharpObjectInitializers) { 761 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 762 763 // Start code fragments with a comment line so that C++ raw string literals 764 // as seen are identical to expected formatted code. 765 766 verifyFormat(R"(// 767 Shape[] shapes = new[] { 768 new Circle { 769 Radius = 2.7281, 770 Colour = Colours.Red, 771 }, 772 new Square { 773 Side = 101.1, 774 Colour = Colours.Yellow, 775 }, 776 };)", 777 Style); 778 779 // Omitted final `,`s will change the formatting. 780 verifyFormat(R"(// 781 Shape[] shapes = new[] { new Circle { Radius = 2.7281, Colour = Colours.Red }, 782 new Square { Side = 101.1, Colour = Colours.Yellow } };)", 783 Style); 784 785 // Lambdas can be supplied as initialiser arguments. 786 verifyFormat(R"(// 787 private Transformer _transformer = new X.Y { 788 Filler = (Shape shape) => { return new Transform.Fill(shape, RED); }, 789 Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); }, 790 };)", 791 Style); 792 793 // Dictionary initialisation. 794 verifyFormat(R"(// 795 var myDict = new Dictionary<string, string> { 796 ["name"] = _donald, 797 ["age"] = Convert.ToString(DateTime.Today.Year - 1934), 798 ["type"] = _duck, 799 };)", 800 Style); 801 } 802 803 TEST_F(FormatTestCSharp, CSharpArrayInitializers) { 804 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 805 806 verifyFormat(R"(// 807 private MySet<Node>[] setPoints = { 808 new Point<Node>(), 809 new Point<Node>(), 810 };)", 811 Style); 812 } 813 814 TEST_F(FormatTestCSharp, CSharpNamedArguments) { 815 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 816 817 verifyFormat(R"(// 818 PrintOrderDetails(orderNum: 31, productName: "Red Mug", sellerName: "Gift Shop");)", 819 Style); 820 821 // Ensure that trailing comments do not cause problems. 822 verifyFormat(R"(// 823 PrintOrderDetails(orderNum: 31, productName: "Red Mug", // comment 824 sellerName: "Gift Shop");)", 825 Style); 826 827 verifyFormat(R"(foreach (var tickCount in task.Begin(seed: 0)) {)", Style); 828 } 829 830 TEST_F(FormatTestCSharp, CSharpPropertyAccessors) { 831 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 832 833 verifyFormat("int Value { get }", Style); 834 verifyFormat("int Value { get; }", Style); 835 verifyFormat("int Value { internal get; }", Style); 836 verifyFormat("int Value { get; } = 0", Style); 837 verifyFormat("int Value { set }", Style); 838 verifyFormat("int Value { set; }", Style); 839 verifyFormat("int Value { internal set; }", Style); 840 verifyFormat("int Value { set; } = 0", Style); 841 verifyFormat("int Value { get; set }", Style); 842 verifyFormat("int Value { set; get }", Style); 843 verifyFormat("int Value { get; private set; }", Style); 844 verifyFormat("int Value { get; set; }", Style); 845 verifyFormat("int Value { get; set; } = 0", Style); 846 verifyFormat("int Value { internal get; internal set; }", Style); 847 848 // Do not wrap expression body definitions. 849 verifyFormat(R"(// 850 public string Name { 851 get => _name; 852 set => _name = value; 853 })", 854 Style); 855 856 // Examples taken from 857 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties 858 verifyFormat(R"( 859 // Expression body definitions 860 public class SaleItem { 861 public decimal Price { 862 get => _cost; 863 set => _cost = value; 864 } 865 })", 866 Style); 867 868 verifyFormat(R"( 869 // Properties with backing fields 870 class TimePeriod { 871 public double Hours { 872 get { return _seconds / 3600; } 873 set { 874 if (value < 0 || value > 24) 875 throw new ArgumentOutOfRangeException($"{nameof(value)} must be between 0 and 24."); 876 _seconds = value * 3600; 877 } 878 } 879 })", 880 Style); 881 882 verifyFormat(R"( 883 // Auto-implemented properties 884 public class SaleItem { 885 public decimal Price { get; set; } 886 })", 887 Style); 888 889 // Add column limit to wrap long lines. 890 Style.ColumnLimit = 100; 891 892 // Examples with assignment to default value. 893 verifyFormat(R"( 894 // Long assignment to default value 895 class MyClass { 896 public override VeryLongNamedTypeIndeed VeryLongNamedValue { get; set } = 897 VeryLongNamedTypeIndeed.Create(DefaultFirstArgument, DefaultSecondArgument, 898 DefaultThirdArgument); 899 })", 900 Style); 901 902 verifyFormat(R"( 903 // Long assignment to default value with expression body 904 class MyClass { 905 public override VeryLongNamedTypeIndeed VeryLongNamedValue { 906 get => veryLongNamedField; 907 set => veryLongNamedField = value; 908 } = VeryLongNamedTypeIndeed.Create(DefaultFirstArgument, DefaultSecondArgument, 909 DefaultThirdArgument); 910 })", 911 Style); 912 913 // Brace wrapping and single-lining of accessor can be controlled by config. 914 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 915 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 916 Style.BraceWrapping.AfterFunction = true; 917 918 verifyFormat(R"(// 919 class TimePeriod { 920 public double Hours 921 { 922 get { 923 return _seconds / 3600; 924 } 925 set { 926 _seconds = value * 3600; 927 } 928 } 929 })", 930 Style); 931 932 // Microsoft style trivial property accessors have no line break before the 933 // opening brace. 934 auto MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp); 935 verifyFormat(R"(// 936 public class SaleItem 937 { 938 public decimal Price { get; set; } 939 })", 940 MicrosoftStyle); 941 } 942 943 TEST_F(FormatTestCSharp, CSharpSpaces) { 944 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 945 Style.SpaceBeforeSquareBrackets = false; 946 Style.SpacesInSquareBrackets = false; 947 Style.SpaceBeforeCpp11BracedList = true; 948 Style.Cpp11BracedListStyle = false; 949 Style.SpacesInContainerLiterals = false; 950 Style.SpaceAfterCStyleCast = false; 951 952 verifyFormat(R"(new Car { "Door", 0.1 })", Style); 953 verifyFormat(R"(new Car { 0.1, "Door" })", Style); 954 verifyFormat(R"(new string[] { "A" })", Style); 955 verifyFormat(R"(new string[] {})", Style); 956 verifyFormat(R"(new Car { someVariableName })", Style); 957 verifyFormat(R"(new Car { someVariableName })", Style); 958 verifyFormat(R"(new Dictionary<string, string> { ["Key"] = "Value" };)", 959 Style); 960 verifyFormat(R"(Apply(x => x.Name, x => () => x.ID);)", Style); 961 verifyFormat(R"(bool[] xs = { true, true };)", Style); 962 verifyFormat(R"(taskContext.Factory.Run(async () => doThing(args);)", Style); 963 verifyFormat(R"(catch (TestException) when (innerFinallyExecuted))", Style); 964 verifyFormat(R"(private float[,] Values;)", Style); 965 verifyFormat(R"(Result this[Index x] => Foo(x);)", Style); 966 967 verifyFormat(R"(char[,,] rawCharArray = MakeCharacterGrid();)", Style); 968 verifyFormat(R"(var (key, value))", Style); 969 970 // `&&` is not seen as a reference. 971 verifyFormat(R"(A == typeof(X) && someBool)", Style); 972 973 // Not seen as a C-style cast. 974 verifyFormat(R"(// 975 foreach ((A a, B b) in someList) { 976 })", 977 Style); 978 979 // space after lock in `lock (processes)`. 980 verifyFormat("lock (process)", Style); 981 982 Style.SpacesInSquareBrackets = true; 983 verifyFormat(R"(private float[ , ] Values;)", Style); 984 verifyFormat(R"(string dirPath = args?[ 0 ];)", Style); 985 verifyFormat(R"(char[ ,, ] rawCharArray = MakeCharacterGrid();)", Style); 986 987 // Method returning tuple 988 verifyFormat(R"(public (string name, int age) methodTuple() {})", Style); 989 verifyFormat(R"(private (string name, int age) methodTuple() {})", Style); 990 verifyFormat(R"(protected (string name, int age) methodTuple() {})", Style); 991 verifyFormat(R"(virtual (string name, int age) methodTuple() {})", Style); 992 verifyFormat(R"(extern (string name, int age) methodTuple() {})", Style); 993 verifyFormat(R"(static (string name, int age) methodTuple() {})", Style); 994 verifyFormat(R"(internal (string name, int age) methodTuple() {})", Style); 995 verifyFormat(R"(abstract (string name, int age) methodTuple() {})", Style); 996 verifyFormat(R"(sealed (string name, int age) methodTuple() {})", Style); 997 verifyFormat(R"(override (string name, int age) methodTuple() {})", Style); 998 verifyFormat(R"(async (string name, int age) methodTuple() {})", Style); 999 verifyFormat(R"(unsafe (string name, int age) methodTuple() {})", Style); 1000 } 1001 1002 TEST_F(FormatTestCSharp, CSharpNullableTypes) { 1003 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 1004 Style.SpacesInSquareBrackets = false; 1005 1006 verifyFormat(R"(// 1007 public class A { 1008 void foo() { 1009 int? value = some.bar(); 1010 } 1011 })", 1012 Style); // int? is nullable not a conditional expression. 1013 1014 verifyFormat(R"(void foo(int? x, int? y, int? z) {})", 1015 Style); // Nullables in function definitions. 1016 1017 verifyFormat(R"(public float? Value;)", Style); // no space before `?`. 1018 1019 verifyFormat(R"(int?[] arr = new int?[10];)", 1020 Style); // An array of a nullable type. 1021 1022 verifyFormat(R"(var x = (int?)y;)", Style); // Cast to a nullable type. 1023 1024 verifyFormat(R"(var x = new MyContainer<int?>();)", Style); // Generics. 1025 1026 verifyFormat(R"(// 1027 public interface I { 1028 int? Function(); 1029 })", 1030 Style); // Interface methods. 1031 1032 Style.ColumnLimit = 10; 1033 verifyFormat(R"(// 1034 public VeryLongType? Function( 1035 int arg1, 1036 int arg2) { 1037 // 1038 })", 1039 Style); // ? sticks with identifier. 1040 } 1041 1042 TEST_F(FormatTestCSharp, CSharpArraySubscripts) { 1043 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 1044 1045 // Do not format array subscript operators as attributes. 1046 verifyFormat(R"(// 1047 if (someThings[index].Contains(myThing)) { 1048 })", 1049 Style); 1050 1051 verifyFormat(R"(// 1052 if (someThings[i][j][k].Contains(myThing)) { 1053 })", 1054 Style); 1055 } 1056 1057 TEST_F(FormatTestCSharp, CSharpGenericTypeConstraints) { 1058 FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); 1059 1060 EXPECT_TRUE(Style.BraceWrapping.SplitEmptyRecord); 1061 1062 verifyFormat("class ItemFactory<T>\n" 1063 " where T : new() {\n" 1064 "}", 1065 Style); 1066 1067 verifyFormat("class Dictionary<TKey, TVal>\n" 1068 " where TKey : IComparable<TKey>\n" 1069 " where TVal : IMyInterface {\n" 1070 " public void MyMethod<T>(T t)\n" 1071 " where T : IMyInterface {\n" 1072 " doThing();\n" 1073 " }\n" 1074 "}", 1075 Style); 1076 1077 verifyFormat("class ItemFactory<T>\n" 1078 " where T : new(), IAnInterface<T>, IAnotherInterface<T>, " 1079 "IAnotherInterfaceStill<T> {\n" 1080 "}", 1081 Style); 1082 1083 Style.ColumnLimit = 50; // Force lines to be wrapped. 1084 verifyFormat(R"(// 1085 class ItemFactory<T, U> 1086 where T : new(), 1087 IAnInterface<T>, 1088 IAnotherInterface<T, U>, 1089 IAnotherInterfaceStill<T, U> { 1090 })", 1091 Style); 1092 1093 // In other languages `where` can be used as a normal identifier. 1094 // This example is in C++! 1095 verifyFormat(R"(// 1096 class A { 1097 int f(int where) {} 1098 };)", 1099 getGoogleStyle(FormatStyle::LK_Cpp)); 1100 } 1101 1102 } // namespace format 1103 } // end namespace clang 1104