xref: /llvm-project/clang/unittests/Format/FormatTestCSharp.cpp (revision ed367b9dff10ee1df9ac1984eb2ad7544da7ab06)
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   // AfterEnum is true by default.
406   verifyFormat("public enum var\n"
407                "{\n"
408                "    none,\n"
409                "    @string,\n"
410                "    bool,\n"
411                "    @enum\n"
412                "}");
413 }
414 
415 TEST_F(FormatTestCSharp, CSharpNullCoalescing) {
416   verifyFormat("var test = ABC ?? DEF");
417   verifyFormat("string myname = name ?? \"ABC\";");
418   verifyFormat("return _name ?? \"DEF\";");
419 }
420 
421 TEST_F(FormatTestCSharp, CSharpNullCoalescingAssignment) {
422   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
423   Style.SpaceBeforeAssignmentOperators = true;
424 
425   verifyFormat(R"(test ??= ABC;)", Style);
426   verifyFormat(R"(test ??= true;)", Style);
427 
428   Style.SpaceBeforeAssignmentOperators = false;
429 
430   verifyFormat(R"(test??= ABC;)", Style);
431   verifyFormat(R"(test??= true;)", Style);
432 }
433 
434 TEST_F(FormatTestCSharp, CSharpNullForgiving) {
435   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
436 
437   verifyFormat("var test = null!;", Style);
438   verifyFormat("string test = someFunctionCall()! + \"ABC\"!", Style);
439   verifyFormat("int test = (1! + 2 + bar! + foo())!", Style);
440   verifyFormat(R"(test ??= !foo!;)", Style);
441   verifyFormat("test = !bar! ?? !foo!;", Style);
442   verifyFormat("bool test = !(!true && !true! || !null && !null! || !false && "
443                "!false! && !bar()! + (!foo()))!",
444                Style);
445 
446   // Check that line break keeps identifier with the bang.
447   Style.ColumnLimit = 14;
448 
449   verifyFormat("var test =\n"
450                "    foo!;",
451                Style);
452 }
453 
454 TEST_F(FormatTestCSharp, AttributesIndentation) {
455   FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_CSharp);
456   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
457 
458   verifyFormat("[STAThread]\n"
459                "static void Main(string[] args)\n"
460                "{\n"
461                "}",
462                Style);
463 
464   verifyFormat("[STAThread]\n"
465                "void "
466                "veryLooooooooooooooongFunctionName(string[] args)\n"
467                "{\n"
468                "}",
469                Style);
470 
471   verifyFormat("[STAThread]\n"
472                "veryLoooooooooooooooooooongReturnType "
473                "veryLooooooooooooooongFunctionName(string[] args)\n"
474                "{\n"
475                "}",
476                Style);
477 
478   verifyFormat("[SuppressMessage(\"A\", \"B\", Justification = \"C\")]\n"
479                "public override X Y()\n"
480                "{\n"
481                "}\n",
482                Style);
483 
484   verifyFormat("[SuppressMessage]\n"
485                "public X Y()\n"
486                "{\n"
487                "}\n",
488                Style);
489 
490   verifyFormat("[SuppressMessage]\n"
491                "public override X Y()\n"
492                "{\n"
493                "}\n",
494                Style);
495 
496   verifyFormat("public A(B b) : base(b)\n"
497                "{\n"
498                "    [SuppressMessage]\n"
499                "    public override X Y()\n"
500                "    {\n"
501                "    }\n"
502                "}\n",
503                Style);
504 
505   verifyFormat("public A : Base\n"
506                "{\n"
507                "}\n"
508                "[Test]\n"
509                "public Foo()\n"
510                "{\n"
511                "}\n",
512                Style);
513 
514   verifyFormat("namespace\n"
515                "{\n"
516                "public A : Base\n"
517                "{\n"
518                "}\n"
519                "[Test]\n"
520                "public Foo()\n"
521                "{\n"
522                "}\n"
523                "}\n",
524                Style);
525 }
526 
527 TEST_F(FormatTestCSharp, CSharpSpaceBefore) {
528   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
529   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
530 
531   verifyFormat("List<string> list;", Style);
532   verifyFormat("Dictionary<string, string> dict;", Style);
533 
534   verifyFormat("for (int i = 0; i < size (); i++) {\n"
535                "}",
536                Style);
537   verifyFormat("foreach (var x in y) {\n"
538                "}",
539                Style);
540   verifyFormat("switch (x) {}", Style);
541   verifyFormat("do {\n"
542                "} while (x);",
543                Style);
544 
545   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
546 
547   verifyFormat("List<string> list;", Style);
548   verifyFormat("Dictionary<string, string> dict;", Style);
549 
550   verifyFormat("for(int i = 0; i < size(); i++) {\n"
551                "}",
552                Style);
553   verifyFormat("foreach(var x in y) {\n"
554                "}",
555                Style);
556   verifyFormat("switch(x) {}", Style);
557   verifyFormat("do {\n"
558                "} while(x);",
559                Style);
560 }
561 
562 TEST_F(FormatTestCSharp, CSharpSpaceAfterCStyleCast) {
563   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
564 
565   verifyFormat("(int)x / y;", Style);
566 
567   Style.SpaceAfterCStyleCast = true;
568   verifyFormat("(int) x / y;", Style);
569 }
570 
571 TEST_F(FormatTestCSharp, CSharpEscapedQuotesInVerbatimStrings) {
572   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
573 
574   verifyFormat(R"(string str = @"""";)", Style);
575   verifyFormat(R"(string str = @"""Hello world""";)", Style);
576   verifyFormat(R"(string str = $@"""Hello {friend}""";)", Style);
577 }
578 
579 TEST_F(FormatTestCSharp, CSharpQuotesInInterpolatedStrings) {
580   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
581 
582   verifyFormat(R"(string str1 = $"{null ?? "null"}";)", Style);
583   verifyFormat(R"(string str2 = $"{{{braceCount} braces";)", Style);
584   verifyFormat(R"(string str3 = $"{braceCount}}} braces";)", Style);
585 }
586 
587 TEST_F(FormatTestCSharp, CSharpNewlinesInVerbatimStrings) {
588   // Use MS style as Google Style inserts a line break before multiline strings.
589 
590   // verifyFormat does not understand multiline C# string-literals
591   // so check the format explicitly.
592 
593   FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_CSharp);
594 
595   std::string Code = R"(string s1 = $@"some code:
596   class {className} {{
597     {className}() {{}}
598   }}";)";
599 
600   EXPECT_EQ(Code, format(Code, Style));
601 
602   // Multiline string in the middle of a function call.
603   Code = R"(
604 var x = foo(className, $@"some code:
605   class {className} {{
606     {className}() {{}}
607   }}",
608             y);)"; // y aligned with `className` arg.
609 
610   EXPECT_EQ(Code, format(Code, Style));
611 
612   // Interpolated string with embedded multiline string.
613   Code = R"(Console.WriteLine($"{string.Join(@",
614 		", values)}");)";
615 
616   EXPECT_EQ(Code, format(Code, Style));
617 }
618 
619 TEST_F(FormatTestCSharp, CSharpLambdas) {
620   FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
621   FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
622 
623   verifyFormat(R"(//
624 class MyClass {
625   Action<string> greet = name => {
626     string greeting = $"Hello {name}!";
627     Console.WriteLine(greeting);
628   };
629 })",
630                GoogleStyle);
631 
632   // Microsoft Style:
633   // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions#statement-lambdas
634   verifyFormat(R"(//
635 class MyClass
636 {
637     Action<string> greet = name =>
638     {
639         string greeting = $"Hello {name}!";
640         Console.WriteLine(greeting);
641     };
642 })",
643                MicrosoftStyle);
644 
645   verifyFormat("void bar()\n"
646                "{\n"
647                "    Function(Val, (Action)(() =>\n"
648                "                           {\n"
649                "                               lock (mylock)\n"
650                "                               {\n"
651                "                                   if (true)\n"
652                "                                   {\n"
653                "                                       A.Remove(item);\n"
654                "                                   }\n"
655                "                               }\n"
656                "                           }));\n"
657                "}",
658                MicrosoftStyle);
659 
660   verifyFormat("void baz()\n"
661                "{\n"
662                "    Function(Val, (Action)(() =>\n"
663                "                           {\n"
664                "                               using (var a = new Lock())\n"
665                "                               {\n"
666                "                                   if (true)\n"
667                "                                   {\n"
668                "                                       A.Remove(item);\n"
669                "                                   }\n"
670                "                               }\n"
671                "                           }));\n"
672                "}",
673                MicrosoftStyle);
674 
675   verifyFormat("void baz()\n"
676                "{\n"
677                "    Function(Val, (Action)(() =>\n"
678                "                           {\n"
679                "                               if (true)\n"
680                "                               {\n"
681                "                                   A.Remove(item);\n"
682                "                               }\n"
683                "                           }));\n"
684                "}",
685                MicrosoftStyle);
686 
687   verifyFormat("void baz()\n"
688                "{\n"
689                "    Function(Val, (Action)(() =>\n"
690                "                           {\n"
691                "                               do\n"
692                "                               {\n"
693                "                                   A.Remove(item);\n"
694                "                               } while (true)\n"
695                "                           }));\n"
696                "}",
697                MicrosoftStyle);
698 
699   verifyFormat("void baz()\n"
700                "{\n"
701                "    Function(Val, (Action)(() =>\n"
702                "                           { A.Remove(item); }));\n"
703                "}",
704                MicrosoftStyle);
705 
706   verifyFormat("void bar()\n"
707                "{\n"
708                "    Function(Val, (() =>\n"
709                "                   {\n"
710                "                       lock (mylock)\n"
711                "                       {\n"
712                "                           if (true)\n"
713                "                           {\n"
714                "                               A.Remove(item);\n"
715                "                           }\n"
716                "                       }\n"
717                "                   }));\n"
718                "}",
719                MicrosoftStyle);
720   verifyFormat("void bar()\n"
721                "{\n"
722                "    Function((() =>\n"
723                "              {\n"
724                "                  lock (mylock)\n"
725                "                  {\n"
726                "                      if (true)\n"
727                "                      {\n"
728                "                          A.Remove(item);\n"
729                "                      }\n"
730                "                  }\n"
731                "              }));\n"
732                "}",
733                MicrosoftStyle);
734 
735   MicrosoftStyle.IndentWidth = 2;
736   verifyFormat("void bar()\n"
737                "{\n"
738                "  Function((() =>\n"
739                "            {\n"
740                "              lock (mylock)\n"
741                "              {\n"
742                "                if (true)\n"
743                "                {\n"
744                "                  A.Remove(item);\n"
745                "                }\n"
746                "              }\n"
747                "            }));\n"
748                "}",
749                MicrosoftStyle);
750   verifyFormat("void bar() {\n"
751                "  Function((() => {\n"
752                "    lock (mylock) {\n"
753                "      if (true) {\n"
754                "        A.Remove(item);\n"
755                "      }\n"
756                "    }\n"
757                "  }));\n"
758                "}",
759                GoogleStyle);
760 }
761 
762 TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
763   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
764 
765   // Start code fragments with a comment line so that C++ raw string literals
766   // as seen are identical to expected formatted code.
767 
768   verifyFormat(R"(//
769 Shape[] shapes = new[] {
770   new Circle {
771     Radius = 2.7281,
772     Colour = Colours.Red,
773   },
774   new Square {
775     Side = 101.1,
776     Colour = Colours.Yellow,
777   },
778 };)",
779                Style);
780 
781   // Omitted final `,`s will change the formatting.
782   verifyFormat(R"(//
783 Shape[] shapes = new[] { new Circle { Radius = 2.7281, Colour = Colours.Red },
784                          new Square { Side = 101.1, Colour = Colours.Yellow } };)",
785                Style);
786 
787   // Lambdas can be supplied as initialiser arguments.
788   verifyFormat(R"(//
789 private Transformer _transformer = new X.Y {
790   Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
791   Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
792 };)",
793                Style);
794 
795   // Dictionary initialisation.
796   verifyFormat(R"(//
797 var myDict = new Dictionary<string, string> {
798   ["name"] = _donald,
799   ["age"] = Convert.ToString(DateTime.Today.Year - 1934),
800   ["type"] = _duck,
801 };)",
802                Style);
803 }
804 
805 TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
806   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
807 
808   verifyFormat(R"(//
809 private MySet<Node>[] setPoints = {
810   new Point<Node>(),
811   new Point<Node>(),
812 };)",
813                Style);
814 }
815 
816 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
817   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
818 
819   verifyFormat(R"(//
820 PrintOrderDetails(orderNum: 31, productName: "Red Mug", sellerName: "Gift Shop");)",
821                Style);
822 
823   // Ensure that trailing comments do not cause problems.
824   verifyFormat(R"(//
825 PrintOrderDetails(orderNum: 31, productName: "Red Mug",  // comment
826                   sellerName: "Gift Shop");)",
827                Style);
828 
829   verifyFormat(R"(foreach (var tickCount in task.Begin(seed: 0)) {)", Style);
830 }
831 
832 TEST_F(FormatTestCSharp, CSharpPropertyAccessors) {
833   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
834 
835   verifyFormat("int Value { get }", Style);
836   verifyFormat("int Value { get; }", Style);
837   verifyFormat("int Value { internal get; }", Style);
838   verifyFormat("int Value { get; } = 0", Style);
839   verifyFormat("int Value { set }", Style);
840   verifyFormat("int Value { set; }", Style);
841   verifyFormat("int Value { internal set; }", Style);
842   verifyFormat("int Value { set; } = 0", Style);
843   verifyFormat("int Value { get; set }", Style);
844   verifyFormat("int Value { set; get }", Style);
845   verifyFormat("int Value { get; private set; }", Style);
846   verifyFormat("int Value { get; set; }", Style);
847   verifyFormat("int Value { get; set; } = 0", Style);
848   verifyFormat("int Value { internal get; internal set; }", Style);
849 
850   // Do not wrap expression body definitions.
851   verifyFormat(R"(//
852 public string Name {
853   get => _name;
854   set => _name = value;
855 })",
856                Style);
857 
858   // Examples taken from
859   // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
860   verifyFormat(R"(
861 // Expression body definitions
862 public class SaleItem {
863   public decimal Price {
864     get => _cost;
865     set => _cost = value;
866   }
867 })",
868                Style);
869 
870   verifyFormat(R"(
871 // Properties with backing fields
872 class TimePeriod {
873   public double Hours {
874     get { return _seconds / 3600; }
875     set {
876       if (value < 0 || value > 24)
877         throw new ArgumentOutOfRangeException($"{nameof(value)} must be between 0 and 24.");
878       _seconds = value * 3600;
879     }
880   }
881 })",
882                Style);
883 
884   verifyFormat(R"(
885 // Auto-implemented properties
886 public class SaleItem {
887   public decimal Price { get; set; }
888 })",
889                Style);
890 
891   // Add column limit to wrap long lines.
892   Style.ColumnLimit = 100;
893 
894   // Examples with assignment to default value.
895   verifyFormat(R"(
896 // Long assignment to default value
897 class MyClass {
898   public override VeryLongNamedTypeIndeed VeryLongNamedValue { get; set } =
899       VeryLongNamedTypeIndeed.Create(DefaultFirstArgument, DefaultSecondArgument,
900                                      DefaultThirdArgument);
901 })",
902                Style);
903 
904   verifyFormat(R"(
905 // Long assignment to default value with expression body
906 class MyClass {
907   public override VeryLongNamedTypeIndeed VeryLongNamedValue {
908     get => veryLongNamedField;
909     set => veryLongNamedField = value;
910   } = VeryLongNamedTypeIndeed.Create(DefaultFirstArgument, DefaultSecondArgument,
911                                      DefaultThirdArgument);
912 })",
913                Style);
914 
915   // Brace wrapping and single-lining of accessor can be controlled by config.
916   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
917   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
918   Style.BraceWrapping.AfterFunction = true;
919 
920   verifyFormat(R"(//
921 class TimePeriod {
922   public double Hours
923   {
924     get {
925       return _seconds / 3600;
926     }
927     set {
928       _seconds = value * 3600;
929     }
930   }
931 })",
932                Style);
933 
934   // Microsoft style trivial property accessors have no line break before the
935   // opening brace.
936   auto MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
937   verifyFormat(R"(//
938 public class SaleItem
939 {
940     public decimal Price { get; set; }
941 })",
942                MicrosoftStyle);
943 }
944 
945 TEST_F(FormatTestCSharp, CSharpSpaces) {
946   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
947   Style.SpaceBeforeSquareBrackets = false;
948   Style.SpacesInSquareBrackets = false;
949   Style.SpaceBeforeCpp11BracedList = true;
950   Style.Cpp11BracedListStyle = false;
951   Style.SpacesInContainerLiterals = false;
952   Style.SpaceAfterCStyleCast = false;
953 
954   verifyFormat(R"(new Car { "Door", 0.1 })", Style);
955   verifyFormat(R"(new Car { 0.1, "Door" })", Style);
956   verifyFormat(R"(new string[] { "A" })", Style);
957   verifyFormat(R"(new string[] {})", Style);
958   verifyFormat(R"(new Car { someVariableName })", Style);
959   verifyFormat(R"(new Car { someVariableName })", Style);
960   verifyFormat(R"(new Dictionary<string, string> { ["Key"] = "Value" };)",
961                Style);
962   verifyFormat(R"(Apply(x => x.Name, x => () => x.ID);)", Style);
963   verifyFormat(R"(bool[] xs = { true, true };)", Style);
964   verifyFormat(R"(taskContext.Factory.Run(async () => doThing(args);)", Style);
965   verifyFormat(R"(catch (TestException) when (innerFinallyExecuted))", Style);
966   verifyFormat(R"(private float[,] Values;)", Style);
967   verifyFormat(R"(Result this[Index x] => Foo(x);)", Style);
968 
969   verifyFormat(R"(char[,,] rawCharArray = MakeCharacterGrid();)", Style);
970   verifyFormat(R"(var (key, value))", Style);
971 
972   // `&&` is not seen as a reference.
973   verifyFormat(R"(A == typeof(X) && someBool)", Style);
974 
975   // Not seen as a C-style cast.
976   verifyFormat(R"(//
977 foreach ((A a, B b) in someList) {
978 })",
979                Style);
980 
981   // space after lock in `lock (processes)`.
982   verifyFormat("lock (process)", Style);
983 
984   Style.SpacesInSquareBrackets = true;
985   verifyFormat(R"(private float[ , ] Values;)", Style);
986   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);
987   verifyFormat(R"(char[ ,, ] rawCharArray = MakeCharacterGrid();)", Style);
988 
989   // Method returning tuple
990   verifyFormat(R"(public (string name, int age) methodTuple() {})", Style);
991   verifyFormat(R"(private (string name, int age) methodTuple() {})", Style);
992   verifyFormat(R"(protected (string name, int age) methodTuple() {})", Style);
993   verifyFormat(R"(virtual (string name, int age) methodTuple() {})", Style);
994   verifyFormat(R"(extern (string name, int age) methodTuple() {})", Style);
995   verifyFormat(R"(static (string name, int age) methodTuple() {})", Style);
996   verifyFormat(R"(internal (string name, int age) methodTuple() {})", Style);
997   verifyFormat(R"(abstract (string name, int age) methodTuple() {})", Style);
998   verifyFormat(R"(sealed (string name, int age) methodTuple() {})", Style);
999   verifyFormat(R"(override (string name, int age) methodTuple() {})", Style);
1000   verifyFormat(R"(async (string name, int age) methodTuple() {})", Style);
1001   verifyFormat(R"(unsafe (string name, int age) methodTuple() {})", Style);
1002 }
1003 
1004 TEST_F(FormatTestCSharp, CSharpNullableTypes) {
1005   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
1006   Style.SpacesInSquareBrackets = false;
1007 
1008   verifyFormat(R"(//
1009 public class A {
1010   void foo() {
1011     int? value = some.bar();
1012   }
1013 })",
1014                Style); // int? is nullable not a conditional expression.
1015 
1016   verifyFormat(R"(void foo(int? x, int? y, int? z) {})",
1017                Style); // Nullables in function definitions.
1018 
1019   verifyFormat(R"(public float? Value;)", Style); // no space before `?`.
1020 
1021   verifyFormat(R"(int?[] arr = new int?[10];)",
1022                Style); // An array of a nullable type.
1023 
1024   verifyFormat(R"(var x = (int?)y;)", Style); // Cast to a nullable type.
1025 
1026   verifyFormat(R"(var x = new MyContainer<int?>();)", Style); // Generics.
1027 
1028   verifyFormat(R"(//
1029 public interface I {
1030   int? Function();
1031 })",
1032                Style); // Interface methods.
1033 
1034   Style.ColumnLimit = 10;
1035   verifyFormat(R"(//
1036 public VeryLongType? Function(
1037     int arg1,
1038     int arg2) {
1039   //
1040 })",
1041                Style); // ? sticks with identifier.
1042 }
1043 
1044 TEST_F(FormatTestCSharp, CSharpArraySubscripts) {
1045   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
1046 
1047   // Do not format array subscript operators as attributes.
1048   verifyFormat(R"(//
1049 if (someThings[index].Contains(myThing)) {
1050 })",
1051                Style);
1052 
1053   verifyFormat(R"(//
1054 if (someThings[i][j][k].Contains(myThing)) {
1055 })",
1056                Style);
1057 }
1058 
1059 TEST_F(FormatTestCSharp, CSharpGenericTypeConstraints) {
1060   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
1061 
1062   EXPECT_TRUE(Style.BraceWrapping.SplitEmptyRecord);
1063 
1064   verifyFormat("class ItemFactory<T>\n"
1065                "    where T : new() {\n"
1066                "}",
1067                Style);
1068 
1069   verifyFormat("class Dictionary<TKey, TVal>\n"
1070                "    where TKey : IComparable<TKey>\n"
1071                "    where TVal : IMyInterface {\n"
1072                "  public void MyMethod<T>(T t)\n"
1073                "      where T : IMyInterface {\n"
1074                "    doThing();\n"
1075                "  }\n"
1076                "}",
1077                Style);
1078 
1079   verifyFormat("class ItemFactory<T>\n"
1080                "    where T : new(), IAnInterface<T>, IAnotherInterface<T>, "
1081                "IAnotherInterfaceStill<T> {\n"
1082                "}",
1083                Style);
1084 
1085   Style.ColumnLimit = 50; // Force lines to be wrapped.
1086   verifyFormat(R"(//
1087 class ItemFactory<T, U>
1088     where T : new(),
1089               IAnInterface<T>,
1090               IAnotherInterface<T, U>,
1091               IAnotherInterfaceStill<T, U> {
1092 })",
1093                Style);
1094 
1095   // In other languages `where` can be used as a normal identifier.
1096   // This example is in C++!
1097   verifyFormat(R"(//
1098 class A {
1099   int f(int where) {}
1100 };)",
1101                getGoogleStyle(FormatStyle::LK_Cpp));
1102 }
1103 
1104 TEST_F(FormatTestCSharp, CSharpAfterEnum) {
1105   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
1106   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1107   Style.BraceWrapping.AfterEnum = false;
1108   Style.AllowShortEnumsOnASingleLine = false;
1109 
1110   verifyFormat("enum MyEnum {\n"
1111                "  Foo,\n"
1112                "  Bar,\n"
1113                "}",
1114                Style);
1115   verifyFormat("internal enum MyEnum {\n"
1116                "  Foo,\n"
1117                "  Bar,\n"
1118                "}",
1119                Style);
1120   verifyFormat("public enum MyEnum {\n"
1121                "  Foo,\n"
1122                "  Bar,\n"
1123                "}",
1124                Style);
1125   verifyFormat("protected enum MyEnum {\n"
1126                "  Foo,\n"
1127                "  Bar,\n"
1128                "}",
1129                Style);
1130   verifyFormat("private enum MyEnum {\n"
1131                "  Foo,\n"
1132                "  Bar,\n"
1133                "}",
1134                Style);
1135 
1136   Style.BraceWrapping.AfterEnum = true;
1137   Style.AllowShortEnumsOnASingleLine = false;
1138 
1139   verifyFormat("enum MyEnum\n"
1140                "{\n"
1141                "  Foo,\n"
1142                "  Bar,\n"
1143                "}",
1144                Style);
1145   verifyFormat("internal enum MyEnum\n"
1146                "{\n"
1147                "  Foo,\n"
1148                "  Bar,\n"
1149                "}",
1150                Style);
1151   verifyFormat("public enum MyEnum\n"
1152                "{\n"
1153                "  Foo,\n"
1154                "  Bar,\n"
1155                "}",
1156                Style);
1157   verifyFormat("protected enum MyEnum\n"
1158                "{\n"
1159                "  Foo,\n"
1160                "  Bar,\n"
1161                "}",
1162                Style);
1163   verifyFormat("private enum MyEnum\n"
1164                "{\n"
1165                "  Foo,\n"
1166                "  Bar,\n"
1167                "}",
1168                Style);
1169   verifyFormat("/* Foo */ private enum MyEnum\n"
1170                "{\n"
1171                "  Foo,\n"
1172                "  Bar,\n"
1173                "}",
1174                Style);
1175   verifyFormat("/* Foo */ /* Bar */ private enum MyEnum\n"
1176                "{\n"
1177                "  Foo,\n"
1178                "  Bar,\n"
1179                "}",
1180                Style);
1181 }
1182 
1183 TEST_F(FormatTestCSharp, CSharpAfterClass) {
1184   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
1185   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1186   Style.BraceWrapping.AfterClass = false;
1187 
1188   verifyFormat("class MyClass {\n"
1189                "  int a;\n"
1190                "  int b;\n"
1191                "}",
1192                Style);
1193   verifyFormat("internal class MyClass {\n"
1194                "  int a;\n"
1195                "  int b;\n"
1196                "}",
1197                Style);
1198   verifyFormat("public class MyClass {\n"
1199                "  int a;\n"
1200                "  int b;\n"
1201                "}",
1202                Style);
1203   verifyFormat("protected class MyClass {\n"
1204                "  int a;\n"
1205                "  int b;\n"
1206                "}",
1207                Style);
1208   verifyFormat("private class MyClass {\n"
1209                "  int a;\n"
1210                "  int b;\n"
1211                "}",
1212                Style);
1213 
1214   verifyFormat("interface Interface {\n"
1215                "  int a;\n"
1216                "  int b;\n"
1217                "}",
1218                Style);
1219   verifyFormat("internal interface Interface {\n"
1220                "  int a;\n"
1221                "  int b;\n"
1222                "}",
1223                Style);
1224   verifyFormat("public interface Interface {\n"
1225                "  int a;\n"
1226                "  int b;\n"
1227                "}",
1228                Style);
1229   verifyFormat("protected interface Interface {\n"
1230                "  int a;\n"
1231                "  int b;\n"
1232                "}",
1233                Style);
1234   verifyFormat("private interface Interface {\n"
1235                "  int a;\n"
1236                "  int b;\n"
1237                "}",
1238                Style);
1239 
1240   Style.BraceWrapping.AfterClass = true;
1241 
1242   verifyFormat("class MyClass\n"
1243                "{\n"
1244                "  int a;\n"
1245                "  int b;\n"
1246                "}",
1247                Style);
1248   verifyFormat("internal class MyClass\n"
1249                "{\n"
1250                "  int a;\n"
1251                "  int b;\n"
1252                "}",
1253                Style);
1254   verifyFormat("public class MyClass\n"
1255                "{\n"
1256                "  int a;\n"
1257                "  int b;\n"
1258                "}",
1259                Style);
1260   verifyFormat("protected class MyClass\n"
1261                "{\n"
1262                "  int a;\n"
1263                "  int b;\n"
1264                "}",
1265                Style);
1266   verifyFormat("private class MyClass\n"
1267                "{\n"
1268                "  int a;\n"
1269                "  int b;\n"
1270                "}",
1271                Style);
1272 
1273   verifyFormat("interface MyInterface\n"
1274                "{\n"
1275                "  int a;\n"
1276                "  int b;\n"
1277                "}",
1278                Style);
1279   verifyFormat("internal interface MyInterface\n"
1280                "{\n"
1281                "  int a;\n"
1282                "  int b;\n"
1283                "}",
1284                Style);
1285   verifyFormat("public interface MyInterface\n"
1286                "{\n"
1287                "  int a;\n"
1288                "  int b;\n"
1289                "}",
1290                Style);
1291   verifyFormat("protected interface MyInterface\n"
1292                "{\n"
1293                "  int a;\n"
1294                "  int b;\n"
1295                "}",
1296                Style);
1297   verifyFormat("private interface MyInterface\n"
1298                "{\n"
1299                "  int a;\n"
1300                "  int b;\n"
1301                "}",
1302                Style);
1303   verifyFormat("/* Foo */ private interface MyInterface\n"
1304                "{\n"
1305                "  int a;\n"
1306                "  int b;\n"
1307                "}",
1308                Style);
1309   verifyFormat("/* Foo */ /* Bar */ private interface MyInterface\n"
1310                "{\n"
1311                "  int a;\n"
1312                "  int b;\n"
1313                "}",
1314                Style);
1315 }
1316 
1317 } // namespace format
1318 } // end namespace clang
1319