xref: /llvm-project/clang/unittests/Format/FormatTestCSharp.cpp (revision 2f9fc8d9718fb19c04e169f7ba7ae26ea6a05085)
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   verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server "
251                "listening on provided host\")]\n"
252                "public string Host { set; get; }");
253 
254   verifyFormat(
255       "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
256       "// The const char* returned by hello_world must not be deleted.\n"
257       "private static extern IntPtr HelloFromCpp();)");
258 
259   // Class attributes go on their own line and do not affect layout of
260   // interfaces. Line wrapping decisions previously caused each interface to be
261   // on its own line.
262   verifyFormat("[SomeAttribute]\n"
263                "[SomeOtherAttribute]\n"
264                "public class A : IShape, IAnimal, IVehicle\n"
265                "{\n"
266                "    int X;\n"
267                "}");
268 
269   // Attributes in a method declaration do not cause line wrapping.
270   verifyFormat("void MethodA([In][Out] ref double x)\n"
271                "{\n"
272                "}");
273 
274   // [] in an attribute do not cause premature line wrapping or indenting.
275   verifyFormat(R"(//
276 public class A
277 {
278     [SomeAttribute(new[] { RED, GREEN, BLUE }, -1.0f, 1.0f)]
279     [DoNotSerialize]
280     public Data MemberVariable;
281 })");
282 
283   //  Unwrappable lines go on a line of their own.
284   // 'target:' is not treated as a label.
285   // Modify Style to enforce a column limit.
286   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
287   Style.ColumnLimit = 10;
288   verifyFormat(R"([assembly:InternalsVisibleTo(
289     "SomeAssembly, PublicKey=SomePublicKeyThatExceedsTheColumnLimit")])",
290                Style);
291 }
292 
293 TEST_F(FormatTestCSharp, CSharpUsing) {
294   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
295   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
296   verifyFormat("public void foo () {\n"
297                "  using (StreamWriter sw = new StreamWriter (filenameA)) {}\n"
298                "  using () {}\n"
299                "}",
300                Style);
301 
302   // Ensure clang-format affects top-level snippets correctly.
303   verifyFormat("using (StreamWriter sw = new StreamWriter (filenameB)) {}",
304                Style);
305 
306   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
307   verifyFormat("public void foo() {\n"
308                "  using(StreamWriter sw = new StreamWriter(filenameB)) {}\n"
309                "  using() {}\n"
310                "}",
311                Style);
312 
313   // Ensure clang-format affects top-level snippets correctly.
314   verifyFormat("using(StreamWriter sw = new StreamWriter(filenameB)) {}",
315                Style);
316 
317   Style.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
318   verifyFormat("public void foo() {\n"
319                "  using (StreamWriter sw = new StreamWriter(filenameA)) {}\n"
320                "  using () {}\n"
321                "}",
322                Style);
323 
324   // Ensure clang-format affects top-level snippets correctly.
325   verifyFormat("using (StreamWriter sw = new StreamWriter(filenameB)) {}",
326                Style);
327 
328   Style.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
329   verifyFormat("public void foo() {\n"
330                "  using (StreamWriter sw = new StreamWriter (filenameA)) {}\n"
331                "  using() {}\n"
332                "}",
333                Style);
334 
335   // Ensure clang-format affects top-level snippets correctly.
336   verifyFormat("using (StreamWriter sw = new StreamWriter (filenameB)) {}",
337                Style);
338 }
339 
340 TEST_F(FormatTestCSharp, CSharpRegions) {
341   verifyFormat("#region aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa "
342                "aaaaaaaaaaaaaaa long region");
343 }
344 
345 TEST_F(FormatTestCSharp, CSharpKeyWordEscaping) {
346   verifyFormat("public enum var { none, @string, bool, @enum }");
347 }
348 
349 TEST_F(FormatTestCSharp, CSharpNullCoalescing) {
350   verifyFormat("var test = ABC ?? DEF");
351   verifyFormat("string myname = name ?? \"ABC\";");
352   verifyFormat("return _name ?? \"DEF\";");
353 }
354 
355 TEST_F(FormatTestCSharp, AttributesIndentation) {
356   FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_CSharp);
357   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
358 
359   verifyFormat("[STAThread]\n"
360                "static void Main(string[] args)\n"
361                "{\n"
362                "}",
363                Style);
364 
365   verifyFormat("[STAThread]\n"
366                "void "
367                "veryLooooooooooooooongFunctionName(string[] args)\n"
368                "{\n"
369                "}",
370                Style);
371 
372   verifyFormat("[STAThread]\n"
373                "veryLoooooooooooooooooooongReturnType "
374                "veryLooooooooooooooongFunctionName(string[] args)\n"
375                "{\n"
376                "}",
377                Style);
378 
379   verifyFormat("[SuppressMessage(\"A\", \"B\", Justification = \"C\")]\n"
380                "public override X Y()\n"
381                "{\n"
382                "}\n",
383                Style);
384 
385   verifyFormat("[SuppressMessage]\n"
386                "public X Y()\n"
387                "{\n"
388                "}\n",
389                Style);
390 
391   verifyFormat("[SuppressMessage]\n"
392                "public override X Y()\n"
393                "{\n"
394                "}\n",
395                Style);
396 
397   verifyFormat("public A(B b) : base(b)\n"
398                "{\n"
399                "    [SuppressMessage]\n"
400                "    public override X Y()\n"
401                "    {\n"
402                "    }\n"
403                "}\n",
404                Style);
405 
406   verifyFormat("public A : Base\n"
407                "{\n"
408                "}\n"
409                "[Test]\n"
410                "public Foo()\n"
411                "{\n"
412                "}\n",
413                Style);
414 
415   verifyFormat("namespace\n"
416                "{\n"
417                "public A : Base\n"
418                "{\n"
419                "}\n"
420                "[Test]\n"
421                "public Foo()\n"
422                "{\n"
423                "}\n"
424                "}\n",
425                Style);
426 }
427 
428 TEST_F(FormatTestCSharp, CSharpSpaceBefore) {
429   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
430   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
431 
432   verifyFormat("List<string> list;", Style);
433   verifyFormat("Dictionary<string, string> dict;", Style);
434 
435   verifyFormat("for (int i = 0; i < size (); i++) {\n"
436                "}",
437                Style);
438   verifyFormat("foreach (var x in y) {\n"
439                "}",
440                Style);
441   verifyFormat("switch (x) {}", Style);
442   verifyFormat("do {\n"
443                "} while (x);",
444                Style);
445 
446   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
447 
448   verifyFormat("List<string> list;", Style);
449   verifyFormat("Dictionary<string, string> dict;", Style);
450 
451   verifyFormat("for(int i = 0; i < size(); i++) {\n"
452                "}",
453                Style);
454   verifyFormat("foreach(var x in y) {\n"
455                "}",
456                Style);
457   verifyFormat("switch(x) {}", Style);
458   verifyFormat("do {\n"
459                "} while(x);",
460                Style);
461 }
462 
463 TEST_F(FormatTestCSharp, CSharpSpaceAfterCStyleCast) {
464   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
465 
466   verifyFormat("(int)x / y;", Style);
467 
468   Style.SpaceAfterCStyleCast = true;
469   verifyFormat("(int) x / y;", Style);
470 }
471 
472 TEST_F(FormatTestCSharp, CSharpEscapedQuotesInVerbatimStrings) {
473   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
474 
475   verifyFormat(R"(string str = @"""";)", Style);
476   verifyFormat(R"(string str = @"""Hello world""";)", Style);
477   verifyFormat(R"(string str = $@"""Hello {friend}""";)", Style);
478 }
479 
480 TEST_F(FormatTestCSharp, CSharpQuotesInInterpolatedStrings) {
481   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
482 
483   verifyFormat(R"(string str1 = $"{null ?? "null"}";)", Style);
484   verifyFormat(R"(string str2 = $"{{{braceCount} braces";)", Style);
485   verifyFormat(R"(string str3 = $"{braceCount}}} braces";)", Style);
486 }
487 
488 TEST_F(FormatTestCSharp, CSharpNewlinesInVerbatimStrings) {
489   // Use MS style as Google Style inserts a line break before multiline strings.
490 
491   // verifyFormat does not understand multiline C# string-literals
492   // so check the format explicitly.
493 
494   FormatStyle Style = getMicrosoftStyle(FormatStyle::LK_CSharp);
495 
496   std::string Code = R"(string s1 = $@"some code:
497   class {className} {{
498     {className}() {{}}
499   }}";)";
500 
501   EXPECT_EQ(Code, format(Code, Style));
502 
503   // Multiline string in the middle of a function call.
504   Code = R"(
505 var x = foo(className, $@"some code:
506   class {className} {{
507     {className}() {{}}
508   }}",
509             y);)"; // y aligned with `className` arg.
510 
511   EXPECT_EQ(Code, format(Code, Style));
512 
513   // Interpolated string with embedded multiline string.
514   Code = R"(Console.WriteLine($"{string.Join(@",
515 		", values)}");)";
516 
517   EXPECT_EQ(Code, format(Code, Style));
518 }
519 
520 TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
521   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
522 
523   // Start code fragments with a comment line so that C++ raw string literals
524   // as seen are identical to expected formatted code.
525 
526   verifyFormat(R"(//
527 Shape[] shapes = new[] {
528   new Circle {
529     Radius = 2.7281,
530     Colour = Colours.Red,
531   },
532   new Square {
533     Side = 101.1,
534     Colour = Colours.Yellow,
535   },
536 };)",
537                Style);
538 
539   // Omitted final `,`s will change the formatting.
540   verifyFormat(R"(//
541 Shape[] shapes = new[] { new Circle { Radius = 2.7281, Colour = Colours.Red },
542                          new Square { Side = 101.1, Colour = Colours.Yellow } };)",
543                Style);
544 
545   // Lambdas can be supplied as initialiser arguments.
546   verifyFormat(R"(//
547 private Transformer _transformer = new X.Y {
548   Filler = (Shape shape) => { return new Transform.Fill(shape, RED); },
549   Scaler = (Shape shape) => { return new Transform.Resize(shape, 0.1); },
550 };)",
551                Style);
552 
553   // Dictionary initialisation.
554   verifyFormat(R"(//
555 var myDict = new Dictionary<string, string> {
556   ["name"] = _donald,
557   ["age"] = Convert.ToString(DateTime.Today.Year - 1934),
558   ["type"] = _duck,
559 };)",
560                Style);
561 }
562 
563 TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
564   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
565 
566   verifyFormat(R"(//
567 private MySet<Node>[] setPoints = {
568   new Point<Node>(),
569   new Point<Node>(),
570 };)",
571                Style);
572 }
573 
574 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
575   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
576 
577   verifyFormat(R"(//
578 PrintOrderDetails(orderNum: 31, productName: "Red Mug",
579                   sellerName: "Gift Shop");)",
580                Style);
581 
582   // Ensure that trailing comments do not cause problems.
583   verifyFormat(R"(//
584 PrintOrderDetails(orderNum: 31, productName: "Red Mug",  // comment
585                   sellerName: "Gift Shop");)",
586                Style);
587 
588   verifyFormat(R"(foreach (var tickCount in task.Begin(seed: 0)) {)", Style);
589 }
590 
591 TEST_F(FormatTestCSharp, CSharpPropertyAccessors) {
592   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
593 
594   verifyFormat("int Value { get }", Style);
595   verifyFormat("int Value { get; }", Style);
596   verifyFormat("int Value { internal get; }", Style);
597   verifyFormat("int Value { get; } = 0", Style);
598   verifyFormat("int Value { set }", Style);
599   verifyFormat("int Value { set; }", Style);
600   verifyFormat("int Value { internal set; }", Style);
601   verifyFormat("int Value { set; } = 0", Style);
602   verifyFormat("int Value { get; set }", Style);
603   verifyFormat("int Value { set; get }", Style);
604   verifyFormat("int Value { get; private set; }", Style);
605   verifyFormat("int Value { get; set; }", Style);
606   verifyFormat("int Value { get; set; } = 0", Style);
607   verifyFormat("int Value { internal get; internal set; }", Style);
608 
609   // Do not wrap expression body definitions.
610   verifyFormat(R"(//
611 public string Name {
612   get => _name;
613   set => _name = value;
614 })",
615                Style);
616 }
617 
618 TEST_F(FormatTestCSharp, CSharpSpaces) {
619   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
620   Style.SpaceBeforeSquareBrackets = false;
621   Style.SpacesInSquareBrackets = false;
622   Style.SpaceBeforeCpp11BracedList = true;
623   Style.Cpp11BracedListStyle = false;
624   Style.SpacesInContainerLiterals = false;
625   Style.SpaceAfterCStyleCast = false;
626 
627   verifyFormat(R"(new Car { "Door", 0.1 })", Style);
628   verifyFormat(R"(new Car { 0.1, "Door" })", Style);
629   verifyFormat(R"(new string[] { "A" })", Style);
630   verifyFormat(R"(new string[] {})", Style);
631   verifyFormat(R"(new Car { someVariableName })", Style);
632   verifyFormat(R"(new Car { someVariableName })", Style);
633   verifyFormat(R"(new Dictionary<string, string> { ["Key"] = "Value" };)",
634                Style);
635   verifyFormat(R"(Apply(x => x.Name, x => () => x.ID);)", Style);
636   verifyFormat(R"(bool[] xs = { true, true };)", Style);
637   verifyFormat(R"(taskContext.Factory.Run(async () => doThing(args);)", Style);
638   verifyFormat(R"(catch (TestException) when (innerFinallyExecuted))", Style);
639   verifyFormat(R"(private float[,] Values;)", Style);
640   verifyFormat(R"(Result this[Index x] => Foo(x);)", Style);
641 
642   verifyFormat(R"(char[,,] rawCharArray = MakeCharacterGrid();)", Style);
643 
644   // Not seen as a C-style cast.
645   verifyFormat(R"(//
646 foreach ((A a, B b) in someList) {
647 })",
648                Style);
649 
650   Style.SpacesInSquareBrackets = true;
651   verifyFormat(R"(private float[ , ] Values;)", Style);
652   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);
653   verifyFormat(R"(char[ ,, ] rawCharArray = MakeCharacterGrid();)", Style);
654 }
655 
656 TEST_F(FormatTestCSharp, CSharpNullableTypes) {
657   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
658   Style.SpacesInSquareBrackets = false;
659 
660   verifyFormat(R"(//
661 public class A {
662   void foo() { int? value = some.bar(); }
663 })",
664                Style); // int? is nullable not a conditional expression.
665 
666   verifyFormat(R"(void foo(int? x, int? y, int? z) {})",
667                Style); // Nullables in function definitions.
668 
669   verifyFormat(R"(public float? Value;)", Style); // no space before `?`.
670 
671   verifyFormat(R"(int?[] arr = new int?[10];)",
672                Style); // An array of a nullable type.
673 
674   verifyFormat(R"(var x = (int?)y;)", Style); // Cast to a nullable type.
675 
676   verifyFormat(R"(var x = new MyContainer<int?>();)", Style); // Generics.
677 }
678 
679 TEST_F(FormatTestCSharp, CSharpArraySubscripts) {
680   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
681 
682   // Do not format array subscript operators as attributes.
683   verifyFormat(R"(//
684 if (someThings[index].Contains(myThing)) {
685 })",
686                Style);
687 
688   verifyFormat(R"(//
689 if (someThings[i][j][k].Contains(myThing)) {
690 })",
691                Style);
692 }
693 
694 TEST_F(FormatTestCSharp, CSharpGenericTypeConstraints) {
695   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
696 
697   verifyFormat(R"(//
698 class ItemFactory<T>
699     where T : new() {})", Style);
700 
701   verifyFormat(R"(//
702 class Dictionary<TKey, TVal>
703     where TKey : IComparable<TKey>
704     where TVal : IMyInterface {
705   public void MyMethod<T>(T t)
706       where T : IMyInterface { doThing(); }
707 })",
708                Style);
709 
710   verifyFormat(R"(//
711 class ItemFactory<T>
712     where T : new(),
713               IAnInterface<T>,
714               IAnotherInterface<T>,
715               IAnotherInterfaceStill<T> {})",
716                Style);
717 
718   Style.ColumnLimit = 50; // Force lines to be wrapped.
719   verifyFormat(R"(//
720 class ItemFactory<T, U>
721     where T : new(),
722               IAnInterface<T>,
723               IAnotherInterface<T, U>,
724               IAnotherInterfaceStill<T, U> {})",
725                Style);
726 
727   // In other languages `where` can be used as a normal identifier.
728   // This example is in C++!
729   verifyFormat(R"(//
730 class A {
731   int f(int where) {}
732 };)",
733                getGoogleStyle(FormatStyle::LK_Cpp));
734 }
735 
736 } // namespace format
737 } // end namespace clang
738